context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections.Specialized; using Spring.Aop; using Spring.Aop.Framework; using Spring.Aop.Framework.Adapter; using Spring.Aop.Framework.DynamicProxy; using Spring.Aop.Support; using Spring.Aop.Target; using Spring.Core.TypeResolution; using Spring.Objects.Factory; #endregion namespace Spring.Transaction.Interceptor { /// <summary> /// Proxy factory object for simplified declarative transaction handling. /// </summary> /// <remarks> /// <p> /// Alternative to the standard AOP <see cref="Spring.Aop.Framework.ProxyFactoryObject"/> /// with a <see cref="Spring.Transaction.Interceptor.TransactionInterceptor"/>. /// </p> /// <p> /// This class is intended to cover the <i>typical</i> case of declarative /// transaction demarcation: namely, wrapping a (singleton) target object with a /// transactional proxy, proxying all the interfaces that the target implements. /// </p> /// <p> /// Internally, a <see cref="Spring.Transaction.Interceptor.TransactionInterceptor"/> /// instance is used, but the user of this class does not have to care. Optionally, an /// <see cref="Spring.Aop.IPointcut"/> can be specified to cause conditional invocation of /// the underlying <see cref="Spring.Transaction.Interceptor.TransactionInterceptor"/>. /// </p> /// <p> /// The /// <see cref="Spring.Transaction.Interceptor.TransactionProxyFactoryObject.PreInterceptors"/> /// and /// <see cref="Spring.Transaction.Interceptor.TransactionProxyFactoryObject.PostInterceptors"/> /// properties can be set to add additional interceptors to the mix. /// </p> /// </remarks> /// <author>Juergen Hoeller</author> /// <author>Dmitriy Kopylenko</author> /// <author>Rod Johnson</author> /// <author>Griffin Caprio (.NET)</author> public class TransactionProxyFactoryObject : ProxyConfig, IFactoryObject, IInitializingObject { private TransactionInterceptor _transactionInterceptor; private object _target; private Type[] _proxyInterfaces; private TruePointcut _pointcut; private object[] _preInterceptors; private object[] _postInterceptors; private IAdvisorAdapterRegistry _advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.Instance; private object _proxy; /// <summary> /// Creates a new instance of the /// <see cref="Spring.Transaction.Interceptor.TransactionProxyFactoryObject"/> class. /// </summary> public TransactionProxyFactoryObject() { _transactionInterceptor = new TransactionInterceptor(); } /// <summary> /// Set the transaction manager for this factory. /// </summary> /// <remarks> /// It is this instance that will perform actual transaction management: this class is /// just a way of invoking it. /// </remarks> public IPlatformTransactionManager PlatformTransactionManager { set { _transactionInterceptor.TransactionManager = value; } } /// <summary> /// Set the target object, i.e. the object to be wrapped with a transactional proxy. /// </summary> /// <remarks> /// <p> /// The target may be any object, in which case a /// <see cref="Spring.Aop.Target.SingletonTargetSource"/> will /// be created. If it is a <see cref="EmptyTargetSource"/>, no wrapper /// <see cref="EmptyTargetSource"/> is created: this enables the use of a pooling /// or prototype <see cref="EmptyTargetSource"/>. /// </p> /// </remarks> public object Target { set { _target = value; } } /// <summary> /// Specify the set of interfaces being proxied. /// </summary> /// <remarks> /// <p> /// If left null (the default), the AOP infrastructure works /// out which interfaces need proxying by analyzing the target, /// proxying <b>all</b> of the interfaces that the target object implements. /// </p> /// </remarks> public string[] ProxyInterfaces { set { _proxyInterfaces = TypeResolutionUtils.ResolveInterfaceArray( value ); } } /// <summary> /// Set properties with method names as keys and transaction attribute /// descriptors as values. /// </summary> /// <remarks> /// <p> /// The various transaction attribute descriptors are parsed via /// an instance of the /// <see cref="Spring.Transaction.Interceptor.TransactionAttributeEditor"/> class. /// </p> /// <note> /// Method names are always applied to the target class, no matter if defined in an /// interface or the class itself. /// </note> /// <p> /// Internally, a /// <see cref="Spring.Transaction.Interceptor.NameMatchTransactionAttributeSource"/> /// will be created from the given properties. /// </p> /// </remarks> /// <example> /// <p> /// An example string (method name and transaction attributes) might be: /// </p> /// <p> /// key = "myMethod", value = "PROPAGATION_REQUIRED,readOnly". /// </p> /// </example> public NameValueCollection TransactionAttributes { set { _transactionInterceptor.TransactionAttributes = value; } } /// <summary> /// Set the transaction attribute source which is used to find transaction /// attributes. /// </summary> /// <remarks> /// <p> /// If specifying a <see cref="System.String"/> property value, an /// appropriate <see cref="System.ComponentModel.TypeConverter"/> /// implementation will create a /// <see cref="Spring.Transaction.Interceptor.MethodMapTransactionAttributeSource"/> /// from the value. /// </p> /// </remarks> public ITransactionAttributeSource TransactionAttributeSource { set { _transactionInterceptor.TransactionAttributeSource = value; } } /// <summary> /// Set a pointcut, i.e an object that can cause conditional invocation /// of the <see cref="Spring.Transaction.Interceptor.TransactionInterceptor"/> /// depending on method and attributes passed. /// </summary> /// <remarks> /// <note> /// Additional interceptors are always invoked. /// </note> /// </remarks> public TruePointcut TruePointcut { set { _pointcut = value; } } /// <summary> /// Set additional interceptors (or advisors) to be applied before the /// implicit transaction interceptor. /// </summary> public object[] PreInterceptors { set { _preInterceptors = value; } } /// <summary> /// Set additional interceptors (or advisors) to be applied after the /// implicit transaction interceptor. /// </summary> /// <remarks> /// <p> /// Note that this is just necessary if you rely on those interceptors in general. /// </p> /// </remarks> public object[] PostInterceptors { set { _postInterceptors = value; } } /// <summary> /// Specify the <see cref="Spring.Aop.Framework.Adapter.IAdvisorAdapterRegistry"/> to use. /// </summary> /// <remarks>The default instance is the global AdvisorAdapterRegistry.</remarks> public IAdvisorAdapterRegistry AdvisorAdapterRegistry { set { _advisorAdapterRegistry = value; } } #region IFactoryObject Members /// <summary> /// Returns the object <see cref="System.Type"/> for this proxy factory. /// </summary> public Type ObjectType { get { if ( _proxy != null ) { return _proxy.GetType(); } else if ( _target != null && _target is ITargetSource ) { return _target.GetType(); } else { return null; } } } /// <summary> /// Returns the object wrapped by this proxy factory. /// </summary> /// <returns>The target object proxy.</returns> public object GetObject() { return _proxy; } /// <summary> /// Is this object a singleton? Always returns <b>true</b> in this implementation. /// </summary> public bool IsSingleton { get { return true; } } #endregion #region IInitializingObject Members /// <summary> /// Method run after all the properties have been set for this object. /// Responsible for actual proxy creation. /// </summary> public void AfterPropertiesSet() { _transactionInterceptor.AfterPropertiesSet(); if ( _target == null ) { throw new ArgumentException("'target' is required."); } ProxyFactory proxyFactory = new ProxyFactory(); if ( _preInterceptors != null ) { for ( int i = 0; i < _preInterceptors.Length; i++ ) { proxyFactory.AddAdvisor(_advisorAdapterRegistry.Wrap(_preInterceptors[i])); } } if ( _pointcut != null ) { IAdvisor advice = new DefaultPointcutAdvisor(_pointcut, _transactionInterceptor); proxyFactory.AddAdvisor(advice); } else { proxyFactory.AddAdvisor( new TransactionAttributeSourceAdvisor( _transactionInterceptor ) ); } if ( _postInterceptors != null ) { for ( int i = 0; i < _postInterceptors.Length; i++ ) { proxyFactory.AddAdvisor(_advisorAdapterRegistry.Wrap(_postInterceptors[i])); } } proxyFactory.CopyFrom(this); proxyFactory.TargetSource = createTargetSource(_target); if ( _proxyInterfaces != null ) { proxyFactory.Interfaces = _proxyInterfaces; } else if ( !ProxyTargetType ) { if ( _target is ITargetSource ) { throw new AopConfigException("Either 'ProxyInterfaces' or 'ProxyTargetType' is required " + "when using an ITargetSource as 'target'"); } proxyFactory.Interfaces = AopUtils.GetAllInterfaces(_target); } _proxy = proxyFactory.GetProxy(); } #endregion /// <summary> /// Set the target or <see cref="Spring.Aop.ITargetSource"/>. /// </summary> /// <param name="target"> /// The target. If this is an implementation of the <see cref="Spring.Aop.ITargetSource"/> /// interface, it is used as our <see cref="Spring.Aop.ITargetSource"/>; otherwise it is /// wrapped in a <see cref="Spring.Aop.Target.SingletonTargetSource"/>. /// </param> /// <returns>An <see cref="Spring.Aop.ITargetSource"/> for this object.</returns> protected ITargetSource createTargetSource( object target ) { if ( target is ITargetSource ) { return (ITargetSource) target; } else { return new SingletonTargetSource( target ); } } } }
// // 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.Conditions { using System; using System.Text; using NLog.Internal; /// <summary> /// Hand-written tokenizer for conditions. /// </summary> internal sealed class ConditionTokenizer { private static readonly ConditionTokenType[] charIndexToTokenType = BuildCharIndexToTokenType(); private readonly SimpleStringReader stringReader; /// <summary> /// Initializes a new instance of the <see cref="ConditionTokenizer"/> class. /// </summary> /// <param name="stringReader">The string reader.</param> public ConditionTokenizer(SimpleStringReader stringReader) { this.stringReader = stringReader; this.TokenType = ConditionTokenType.BeginningOfInput; this.GetNextToken(); } /// <summary> /// Gets the token position. /// </summary> /// <value>The token position.</value> public int TokenPosition { get; private set; } /// <summary> /// Gets the type of the token. /// </summary> /// <value>The type of the token.</value> public ConditionTokenType TokenType { get; private set; } /// <summary> /// Gets the token value. /// </summary> /// <value>The token value.</value> public string TokenValue { get; private set; } /// <summary> /// Gets the value of a string token. /// </summary> /// <value>The string token value.</value> public string StringTokenValue { get { string s = this.TokenValue; return s.Substring(1, s.Length - 2).Replace("''", "'"); } } /// <summary> /// Asserts current token type and advances to the next token. /// </summary> /// <param name="tokenType">Expected token type.</param> /// <remarks>If token type doesn't match, an exception is thrown.</remarks> public void Expect(ConditionTokenType tokenType) { if (this.TokenType != tokenType) { throw new ConditionParseException("Expected token of type: " + tokenType + ", got " + this.TokenType + " (" + this.TokenValue + ")."); } this.GetNextToken(); } /// <summary> /// Asserts that current token is a keyword and returns its value and advances to the next token. /// </summary> /// <returns>Keyword value.</returns> public string EatKeyword() { if (this.TokenType != ConditionTokenType.Keyword) { throw new ConditionParseException("Identifier expected"); } string s = (string)this.TokenValue; this.GetNextToken(); return s; } /// <summary> /// Gets or sets a value indicating whether current keyword is equal to the specified value. /// </summary> /// <param name="keyword">The keyword.</param> /// <returns> /// A value of <c>true</c> if current keyword is equal to the specified value; otherwise, <c>false</c>. /// </returns> public bool IsKeyword(string keyword) { if (this.TokenType != ConditionTokenType.Keyword) { return false; } if (!this.TokenValue.Equals(keyword, StringComparison.OrdinalIgnoreCase)) { return false; } return true; } /// <summary> /// Gets or sets a value indicating whether the tokenizer has reached the end of the token stream. /// </summary> /// <returns> /// A value of <c>true</c> if the tokenizer has reached the end of the token stream; otherwise, <c>false</c>. /// </returns> public bool IsEOF() { if (this.TokenType != ConditionTokenType.EndOfInput) { return false; } return true; } /// <summary> /// Gets or sets a value indicating whether current token is a number. /// </summary> /// <returns> /// A value of <c>true</c> if current token is a number; otherwise, <c>false</c>. /// </returns> public bool IsNumber() { return this.TokenType == ConditionTokenType.Number; } /// <summary> /// Gets or sets a value indicating whether the specified token is of specified type. /// </summary> /// <param name="tokenType">The token type.</param> /// <returns> /// A value of <c>true</c> if current token is of specified type; otherwise, <c>false</c>. /// </returns> public bool IsToken(ConditionTokenType tokenType) { return this.TokenType == tokenType; } /// <summary> /// Gets the next token and sets <see cref="TokenType"/> and <see cref="TokenValue"/> properties. /// </summary> public void GetNextToken() { if (this.TokenType == ConditionTokenType.EndOfInput) { throw new ConditionParseException("Cannot read past end of stream."); } this.SkipWhitespace(); this.TokenPosition = this.TokenPosition; int i = this.PeekChar(); if (i == -1) { this.TokenType = ConditionTokenType.EndOfInput; return; } char ch = (char)i; if (char.IsDigit(ch)) { this.ParseNumber(ch); return; } if (ch == '\'') { this.ParseSingleQuotedString(ch); return; } if (ch == '_' || char.IsLetter(ch)) { this.ParseKeyword(ch); return; } if (ch == '}' || ch == ':') { // when condition is embedded this.TokenType = ConditionTokenType.EndOfInput; return; } this.TokenValue = ch.ToString(); var success = TryGetComparisonToken(ch); if (success) return; success = TryGetLogicalToken(ch); if (success) return; if (ch >= 32 && ch < 128) { ConditionTokenType tt = charIndexToTokenType[ch]; if (tt != ConditionTokenType.Invalid) { this.TokenType = tt; this.TokenValue = new string(ch, 1); this.ReadChar(); return; } throw new ConditionParseException("Invalid punctuation: " + ch); } throw new ConditionParseException("Invalid token: " + ch); } /// <summary> /// Try the comparison tokens (greater, smaller, greater-equals, smaller-equals) /// </summary> /// <param name="ch">current char</param> /// <returns>is match</returns> private bool TryGetComparisonToken(char ch) { if (ch == '<') { this.ReadChar(); int nextChar = this.PeekChar(); if (nextChar == '>') { this.TokenType = ConditionTokenType.NotEqual; this.TokenValue = "<>"; this.ReadChar(); return true; } if (nextChar == '=') { this.TokenType = ConditionTokenType.LessThanOrEqualTo; this.TokenValue = "<="; this.ReadChar(); return true; } this.TokenType = ConditionTokenType.LessThan; this.TokenValue = "<"; return true; } if (ch == '>') { this.ReadChar(); int nextChar = this.PeekChar(); if (nextChar == '=') { this.TokenType = ConditionTokenType.GreaterThanOrEqualTo; this.TokenValue = ">="; this.ReadChar(); return true; } this.TokenType = ConditionTokenType.GreaterThan; this.TokenValue = ">"; return true; } return false; } /// <summary> /// Try the logical tokens (and, or, not, equals) /// </summary> /// <param name="ch">current char</param> /// <returns>is match</returns> private bool TryGetLogicalToken(char ch) { if (ch == '!') { this.ReadChar(); int nextChar = this.PeekChar(); if (nextChar == '=') { this.TokenType = ConditionTokenType.NotEqual; this.TokenValue = "!="; this.ReadChar(); return true; } this.TokenType = ConditionTokenType.Not; this.TokenValue = "!"; return true; } if (ch == '&') { this.ReadChar(); int nextChar = this.PeekChar(); if (nextChar == '&') { this.TokenType = ConditionTokenType.And; this.TokenValue = "&&"; this.ReadChar(); return true; } throw new ConditionParseException("Expected '&&' but got '&'"); } if (ch == '|') { this.ReadChar(); int nextChar = this.PeekChar(); if (nextChar == '|') { this.TokenType = ConditionTokenType.Or; this.TokenValue = "||"; this.ReadChar(); return true; } throw new ConditionParseException("Expected '||' but got '|'"); } if (ch == '=') { this.ReadChar(); int nextChar = this.PeekChar(); if (nextChar == '=') { this.TokenType = ConditionTokenType.EqualTo; this.TokenValue = "=="; this.ReadChar(); return true; } this.TokenType = ConditionTokenType.EqualTo; this.TokenValue = "="; return true; } return false; } private static ConditionTokenType[] BuildCharIndexToTokenType() { CharToTokenType[] charToTokenType = { new CharToTokenType('(', ConditionTokenType.LeftParen), new CharToTokenType(')', ConditionTokenType.RightParen), new CharToTokenType('.', ConditionTokenType.Dot), new CharToTokenType(',', ConditionTokenType.Comma), new CharToTokenType('!', ConditionTokenType.Not), new CharToTokenType('-', ConditionTokenType.Minus), }; var result = new ConditionTokenType[128]; for (int i = 0; i < 128; ++i) { result[i] = ConditionTokenType.Invalid; } foreach (CharToTokenType cht in charToTokenType) { // Console.WriteLine("Setting up {0} to {1}", cht.ch, cht.tokenType); result[(int)cht.Character] = cht.TokenType; } return result; } private void ParseSingleQuotedString(char ch) { int i; this.TokenType = ConditionTokenType.String; StringBuilder sb = new StringBuilder(); sb.Append(ch); this.ReadChar(); while ((i = this.PeekChar()) != -1) { ch = (char)i; sb.Append((char)this.ReadChar()); if (ch == '\'') { if (this.PeekChar() == (int)'\'') { sb.Append('\''); this.ReadChar(); } else { break; } } } if (i == -1) { throw new ConditionParseException("String literal is missing a closing quote character."); } this.TokenValue = sb.ToString(); } private void ParseKeyword(char ch) { int i; this.TokenType = ConditionTokenType.Keyword; StringBuilder sb = new StringBuilder(); sb.Append((char)ch); this.ReadChar(); while ((i = this.PeekChar()) != -1) { if ((char)i == '_' || (char)i == '-' || char.IsLetterOrDigit((char)i)) { sb.Append((char)this.ReadChar()); } else { break; } } this.TokenValue = sb.ToString(); } private void ParseNumber(char ch) { int i; this.TokenType = ConditionTokenType.Number; StringBuilder sb = new StringBuilder(); sb.Append(ch); this.ReadChar(); while ((i = this.PeekChar()) != -1) { ch = (char)i; if (char.IsDigit(ch) || (ch == '.')) { sb.Append((char)this.ReadChar()); } else { break; } } this.TokenValue = sb.ToString(); } private void SkipWhitespace() { int ch; while ((ch = this.PeekChar()) != -1) { if (!char.IsWhiteSpace((char)ch)) { break; } this.ReadChar(); } } private int PeekChar() { return this.stringReader.Peek(); } private int ReadChar() { return this.stringReader.Read(); } /// <summary> /// Mapping between characters and token types for punctuations. /// </summary> private struct CharToTokenType { public readonly char Character; public readonly ConditionTokenType TokenType; /// <summary> /// Initializes a new instance of the CharToTokenType struct. /// </summary> /// <param name="character">The character.</param> /// <param name="tokenType">Type of the token.</param> public CharToTokenType(char character, ConditionTokenType tokenType) { this.Character = character; this.TokenType = tokenType; } } } }
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources; 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 scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="ParentalStatusViewServiceClient"/> instances.</summary> public sealed partial class ParentalStatusViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ParentalStatusViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ParentalStatusViewServiceSettings"/>.</returns> public static ParentalStatusViewServiceSettings GetDefault() => new ParentalStatusViewServiceSettings(); /// <summary> /// Constructs a new <see cref="ParentalStatusViewServiceSettings"/> object with default settings. /// </summary> public ParentalStatusViewServiceSettings() { } private ParentalStatusViewServiceSettings(ParentalStatusViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetParentalStatusViewSettings = existing.GetParentalStatusViewSettings; OnCopy(existing); } partial void OnCopy(ParentalStatusViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ParentalStatusViewServiceClient.GetParentalStatusView</c> and /// <c>ParentalStatusViewServiceClient.GetParentalStatusViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetParentalStatusViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ParentalStatusViewServiceSettings"/> object.</returns> public ParentalStatusViewServiceSettings Clone() => new ParentalStatusViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="ParentalStatusViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class ParentalStatusViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<ParentalStatusViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ParentalStatusViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ParentalStatusViewServiceClientBuilder() { UseJwtAccessWithScopes = ParentalStatusViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ParentalStatusViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ParentalStatusViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ParentalStatusViewServiceClient Build() { ParentalStatusViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ParentalStatusViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ParentalStatusViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ParentalStatusViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ParentalStatusViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<ParentalStatusViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ParentalStatusViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ParentalStatusViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ParentalStatusViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ParentalStatusViewServiceClient.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>ParentalStatusViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage parental status views. /// </remarks> public abstract partial class ParentalStatusViewServiceClient { /// <summary> /// The default endpoint for the ParentalStatusViewService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ParentalStatusViewService scopes.</summary> /// <remarks> /// The default ParentalStatusViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); 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="ParentalStatusViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ParentalStatusViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ParentalStatusViewServiceClient"/>.</returns> public static stt::Task<ParentalStatusViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ParentalStatusViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ParentalStatusViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ParentalStatusViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ParentalStatusViewServiceClient"/>.</returns> public static ParentalStatusViewServiceClient Create() => new ParentalStatusViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ParentalStatusViewServiceClient"/> 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="ParentalStatusViewServiceSettings"/>.</param> /// <returns>The created <see cref="ParentalStatusViewServiceClient"/>.</returns> internal static ParentalStatusViewServiceClient Create(grpccore::CallInvoker callInvoker, ParentalStatusViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ParentalStatusViewService.ParentalStatusViewServiceClient grpcClient = new ParentalStatusViewService.ParentalStatusViewServiceClient(callInvoker); return new ParentalStatusViewServiceClientImpl(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 ParentalStatusViewService client</summary> public virtual ParentalStatusViewService.ParentalStatusViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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 gagvr::ParentalStatusView GetParentalStatusView(GetParentalStatusViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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<gagvr::ParentalStatusView> GetParentalStatusViewAsync(GetParentalStatusViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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<gagvr::ParentalStatusView> GetParentalStatusViewAsync(GetParentalStatusViewRequest request, st::CancellationToken cancellationToken) => GetParentalStatusViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the parental status view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ParentalStatusView GetParentalStatusView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetParentalStatusView(new GetParentalStatusViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the parental status view to fetch. /// </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<gagvr::ParentalStatusView> GetParentalStatusViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetParentalStatusViewAsync(new GetParentalStatusViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the parental status view to fetch. /// </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<gagvr::ParentalStatusView> GetParentalStatusViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetParentalStatusViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the parental status view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ParentalStatusView GetParentalStatusView(gagvr::ParentalStatusViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetParentalStatusView(new GetParentalStatusViewRequest { ResourceNameAsParentalStatusViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the parental status view to fetch. /// </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<gagvr::ParentalStatusView> GetParentalStatusViewAsync(gagvr::ParentalStatusViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetParentalStatusViewAsync(new GetParentalStatusViewRequest { ResourceNameAsParentalStatusViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the parental status view to fetch. /// </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<gagvr::ParentalStatusView> GetParentalStatusViewAsync(gagvr::ParentalStatusViewName resourceName, st::CancellationToken cancellationToken) => GetParentalStatusViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ParentalStatusViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage parental status views. /// </remarks> public sealed partial class ParentalStatusViewServiceClientImpl : ParentalStatusViewServiceClient { private readonly gaxgrpc::ApiCall<GetParentalStatusViewRequest, gagvr::ParentalStatusView> _callGetParentalStatusView; /// <summary> /// Constructs a client wrapper for the ParentalStatusViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ParentalStatusViewServiceSettings"/> used within this client. /// </param> public ParentalStatusViewServiceClientImpl(ParentalStatusViewService.ParentalStatusViewServiceClient grpcClient, ParentalStatusViewServiceSettings settings) { GrpcClient = grpcClient; ParentalStatusViewServiceSettings effectiveSettings = settings ?? ParentalStatusViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetParentalStatusView = clientHelper.BuildApiCall<GetParentalStatusViewRequest, gagvr::ParentalStatusView>(grpcClient.GetParentalStatusViewAsync, grpcClient.GetParentalStatusView, effectiveSettings.GetParentalStatusViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetParentalStatusView); Modify_GetParentalStatusViewApiCall(ref _callGetParentalStatusView); 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_GetParentalStatusViewApiCall(ref gaxgrpc::ApiCall<GetParentalStatusViewRequest, gagvr::ParentalStatusView> call); partial void OnConstruction(ParentalStatusViewService.ParentalStatusViewServiceClient grpcClient, ParentalStatusViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ParentalStatusViewService client</summary> public override ParentalStatusViewService.ParentalStatusViewServiceClient GrpcClient { get; } partial void Modify_GetParentalStatusViewRequest(ref GetParentalStatusViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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 gagvr::ParentalStatusView GetParentalStatusView(GetParentalStatusViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetParentalStatusViewRequest(ref request, ref callSettings); return _callGetParentalStatusView.Sync(request, callSettings); } /// <summary> /// Returns the requested parental status view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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<gagvr::ParentalStatusView> GetParentalStatusViewAsync(GetParentalStatusViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetParentalStatusViewRequest(ref request, ref callSettings); return _callGetParentalStatusView.Async(request, callSettings); } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmGRVitemFnV { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmGRVitemFnV() : base() { FormClosed += frmGRVitemFnV_FormClosed; Resize += frmGRVitemFnV_Resize; Load += frmGRVitemFnV_Load; KeyPress += frmGRVitemFnV_KeyPress; KeyDown += frmGRVitemFnV_KeyDown; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.TextBox txtPackSize; private System.Windows.Forms.Button withEventsField_cmdEditPackSize; public System.Windows.Forms.Button cmdEditPackSize { get { return withEventsField_cmdEditPackSize; } set { if (withEventsField_cmdEditPackSize != null) { withEventsField_cmdEditPackSize.Click -= cmdEditPackSize_Click; } withEventsField_cmdEditPackSize = value; if (withEventsField_cmdEditPackSize != null) { withEventsField_cmdEditPackSize.Click += cmdEditPackSize_Click; } } } public System.Windows.Forms.GroupBox frmFNVeg; private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter -= txtSearch_Enter; withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter += txtSearch_Enter; withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.TextBox withEventsField_txtBCode; public System.Windows.Forms.TextBox txtBCode { get { return withEventsField_txtBCode; } set { if (withEventsField_txtBCode != null) { withEventsField_txtBCode.Enter -= txtBCode_Enter; withEventsField_txtBCode.KeyDown -= txtBCode_KeyDown; withEventsField_txtBCode.KeyPress -= txtBCode_KeyPress; } withEventsField_txtBCode = value; if (withEventsField_txtBCode != null) { withEventsField_txtBCode.Enter += txtBCode_Enter; withEventsField_txtBCode.KeyDown += txtBCode_KeyDown; withEventsField_txtBCode.KeyPress += txtBCode_KeyPress; } } } public System.Windows.Forms.TextBox _txtEdit_2; public System.Windows.Forms.TextBox _txtEdit_1; private System.Windows.Forms.Button withEventsField_cmdPriceBOM; public System.Windows.Forms.Button cmdPriceBOM { get { return withEventsField_cmdPriceBOM; } set { if (withEventsField_cmdPriceBOM != null) { withEventsField_cmdPriceBOM.Click -= cmdPriceBOM_Click; } withEventsField_cmdPriceBOM = value; if (withEventsField_cmdPriceBOM != null) { withEventsField_cmdPriceBOM.Click += cmdPriceBOM_Click; } } } private System.Windows.Forms.Timer withEventsField_tmrAutoGRV; public System.Windows.Forms.Timer tmrAutoGRV { get { return withEventsField_tmrAutoGRV; } set { if (withEventsField_tmrAutoGRV != null) { withEventsField_tmrAutoGRV.Tick -= tmrAutoGRV_Tick; } withEventsField_tmrAutoGRV = value; if (withEventsField_tmrAutoGRV != null) { withEventsField_tmrAutoGRV.Tick += tmrAutoGRV_Tick; } } } private System.Windows.Forms.Button withEventsField_cmdVat; public System.Windows.Forms.Button cmdVat { get { return withEventsField_cmdVat; } set { if (withEventsField_cmdVat != null) { withEventsField_cmdVat.Click -= cmdVAT_Click; } withEventsField_cmdVat = value; if (withEventsField_cmdVat != null) { withEventsField_cmdVat.Click += cmdVAT_Click; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } private System.Windows.Forms.Button withEventsField_cmdNext; public System.Windows.Forms.Button cmdNext { get { return withEventsField_cmdNext; } set { if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click -= cmdNext_Click; } withEventsField_cmdNext = value; if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click += cmdNext_Click; } } } private System.Windows.Forms.Button withEventsField_cmdBack; public System.Windows.Forms.Button cmdBack { get { return withEventsField_cmdBack; } set { if (withEventsField_cmdBack != null) { withEventsField_cmdBack.Click -= cmdBack_Click; } withEventsField_cmdBack = value; if (withEventsField_cmdBack != null) { withEventsField_cmdBack.Click += cmdBack_Click; } } } private System.Windows.Forms.Button withEventsField_cmdStockItem; public System.Windows.Forms.Button cmdStockItem { get { return withEventsField_cmdStockItem; } set { if (withEventsField_cmdStockItem != null) { withEventsField_cmdStockItem.Click -= cmdStockItem_Click; } withEventsField_cmdStockItem = value; if (withEventsField_cmdStockItem != null) { withEventsField_cmdStockItem.Click += cmdStockItem_Click; } } } private System.Windows.Forms.Button withEventsField_cmdDiscount; public System.Windows.Forms.Button cmdDiscount { get { return withEventsField_cmdDiscount; } set { if (withEventsField_cmdDiscount != null) { withEventsField_cmdDiscount.Click -= cmdDiscount_Click; } withEventsField_cmdDiscount = value; if (withEventsField_cmdDiscount != null) { withEventsField_cmdDiscount.Click += cmdDiscount_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPrintOrder; public System.Windows.Forms.Button cmdPrintOrder { get { return withEventsField_cmdPrintOrder; } set { if (withEventsField_cmdPrintOrder != null) { withEventsField_cmdPrintOrder.Click -= cmdPrintOrder_Click; } withEventsField_cmdPrintOrder = value; if (withEventsField_cmdPrintOrder != null) { withEventsField_cmdPrintOrder.Click += cmdPrintOrder_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPrintGRV; public System.Windows.Forms.Button cmdPrintGRV { get { return withEventsField_cmdPrintGRV; } set { if (withEventsField_cmdPrintGRV != null) { withEventsField_cmdPrintGRV.Click -= cmdPrintGRV_Click; } withEventsField_cmdPrintGRV = value; if (withEventsField_cmdPrintGRV != null) { withEventsField_cmdPrintGRV.Click += cmdPrintGRV_Click; } } } private System.Windows.Forms.Button withEventsField_cmdDelete; public System.Windows.Forms.Button cmdDelete { get { return withEventsField_cmdDelete; } set { if (withEventsField_cmdDelete != null) { withEventsField_cmdDelete.Click -= cmdDelete_Click; } withEventsField_cmdDelete = value; if (withEventsField_cmdDelete != null) { withEventsField_cmdDelete.Click += cmdDelete_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPack; public System.Windows.Forms.Button cmdPack { get { return withEventsField_cmdPack; } set { if (withEventsField_cmdPack != null) { withEventsField_cmdPack.Click -= cmdPack_Click; } withEventsField_cmdPack = value; if (withEventsField_cmdPack != null) { withEventsField_cmdPack.Click += cmdPack_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPrice; public System.Windows.Forms.Button cmdPrice { get { return withEventsField_cmdPrice; } set { if (withEventsField_cmdPrice != null) { withEventsField_cmdPrice.Click -= cmdPrice_Click; } withEventsField_cmdPrice = value; if (withEventsField_cmdPrice != null) { withEventsField_cmdPrice.Click += cmdPrice_Click; } } } private System.Windows.Forms.Button withEventsField_cmdEdit; public System.Windows.Forms.Button cmdEdit { get { return withEventsField_cmdEdit; } set { if (withEventsField_cmdEdit != null) { withEventsField_cmdEdit.Click -= cmdEdit_Click; } withEventsField_cmdEdit = value; if (withEventsField_cmdEdit != null) { withEventsField_cmdEdit.Click += cmdEdit_Click; } } } private System.Windows.Forms.Button withEventsField_cmdNew; public System.Windows.Forms.Button cmdNew { get { return withEventsField_cmdNew; } set { if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click -= cmdNew_Click; } withEventsField_cmdNew = value; if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click += cmdNew_Click; } } } private System.Windows.Forms.Button withEventsField_cmdQuick; public System.Windows.Forms.Button cmdQuick { get { return withEventsField_cmdQuick; } set { if (withEventsField_cmdQuick != null) { withEventsField_cmdQuick.Click -= cmdQuick_Click; } withEventsField_cmdQuick = value; if (withEventsField_cmdQuick != null) { withEventsField_cmdQuick.Click += cmdQuick_Click; } } } private System.Windows.Forms.Button withEventsField_cmdSort; public System.Windows.Forms.Button cmdSort { get { return withEventsField_cmdSort; } set { if (withEventsField_cmdSort != null) { withEventsField_cmdSort.Click -= cmdSort_Click; } withEventsField_cmdSort = value; if (withEventsField_cmdSort != null) { withEventsField_cmdSort.Click += cmdSort_Click; } } } private System.Windows.Forms.Panel withEventsField_Picture2; public System.Windows.Forms.Panel Picture2 { get { return withEventsField_Picture2; } set { if (withEventsField_Picture2 != null) { withEventsField_Picture2.Resize -= Picture2_Resize; } withEventsField_Picture2 = value; if (withEventsField_Picture2 != null) { withEventsField_Picture2.Resize += Picture2_Resize; } } } public System.Windows.Forms.Label _lblTotal_5; public System.Windows.Forms.Label _lblTotal_4; public System.Windows.Forms.Label _lblTotal_3; public System.Windows.Forms.Label _lblTotal_2; public System.Windows.Forms.Label _lblTotal_1; public System.Windows.Forms.Label _lblTotal_0; public System.Windows.Forms.Label lblTotalInclusive; public System.Windows.Forms.Label lblTotalExclusive; public System.Windows.Forms.Label lblDepositInclusive; public System.Windows.Forms.Label lblDepositExclusive; public System.Windows.Forms.Label lblContentInclusive; public System.Windows.Forms.Label lblContentExclusive; public System.Windows.Forms.Label _lbl_2; public System.Windows.Forms.Label lblBrokenPack; public System.Windows.Forms.Label _lbl_8; public System.Windows.Forms.Label lblQuantity; public System.Windows.Forms.GroupBox frmTotals; public System.Windows.Forms.Label lblSupplier; public System.Windows.Forms.Panel Picture1; public System.Windows.Forms.TextBox _txtEdit_0; private myDataGridView withEventsField_gridItem; public myDataGridView gridItem { get { return withEventsField_gridItem; } set { if (withEventsField_gridItem != null) { withEventsField_gridItem.CellClick -= gridItem_ClickEvent; withEventsField_gridItem.CellEnter -= gridItem_EnterCell; withEventsField_gridItem.Enter -= gridItem_Enter; withEventsField_gridItem.KeyPress -= gridItem_KeyPress; withEventsField_gridItem.CellLeave -= gridItem_LeaveCell; } withEventsField_gridItem = value; if (withEventsField_gridItem != null) { withEventsField_gridItem.CellClick += gridItem_ClickEvent; withEventsField_gridItem.CellEnter += gridItem_EnterCell; withEventsField_gridItem.Enter += gridItem_Enter; withEventsField_gridItem.KeyPress += gridItem_KeyPress; withEventsField_gridItem.CellLeave += gridItem_LeaveCell; } } } public System.Windows.Forms.TextBox txtSearch0; private System.Windows.Forms.ListBox withEventsField_lstWorkspace; public System.Windows.Forms.ListBox lstWorkspace { get { return withEventsField_lstWorkspace; } set { if (withEventsField_lstWorkspace != null) { withEventsField_lstWorkspace.DoubleClick -= lstWorkspace_DoubleClick; withEventsField_lstWorkspace.KeyPress -= lstWorkspace_KeyPress; withEventsField_lstWorkspace.KeyDown -= lstWorkspace_KeyDown; } withEventsField_lstWorkspace = value; if (withEventsField_lstWorkspace != null) { withEventsField_lstWorkspace.DoubleClick += lstWorkspace_DoubleClick; withEventsField_lstWorkspace.KeyPress += lstWorkspace_KeyPress; withEventsField_lstWorkspace.KeyDown += lstWorkspace_KeyDown; } } } public System.Windows.Forms.Label _lbl_1; public System.Windows.Forms.Label Label1; public System.Windows.Forms.Label lblReturns; public System.Windows.Forms.Label _lbl_7; public System.Windows.Forms.Label _lbl_0; //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lblTotal As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents txtEdit As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmGRVitemFnV)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.frmFNVeg = new System.Windows.Forms.GroupBox(); this.txtPackSize = new System.Windows.Forms.TextBox(); this.cmdEditPackSize = new System.Windows.Forms.Button(); this.txtSearch = new System.Windows.Forms.TextBox(); this.txtBCode = new System.Windows.Forms.TextBox(); this._txtEdit_2 = new System.Windows.Forms.TextBox(); this._txtEdit_1 = new System.Windows.Forms.TextBox(); this.Picture2 = new System.Windows.Forms.Panel(); this.cmdPriceBOM = new System.Windows.Forms.Button(); this.tmrAutoGRV = new System.Windows.Forms.Timer(components); this.cmdVat = new System.Windows.Forms.Button(); this.cmdExit = new System.Windows.Forms.Button(); this.cmdNext = new System.Windows.Forms.Button(); this.cmdBack = new System.Windows.Forms.Button(); this.cmdStockItem = new System.Windows.Forms.Button(); this.cmdDiscount = new System.Windows.Forms.Button(); this.cmdPrintOrder = new System.Windows.Forms.Button(); this.cmdPrintGRV = new System.Windows.Forms.Button(); this.cmdDelete = new System.Windows.Forms.Button(); this.cmdPack = new System.Windows.Forms.Button(); this.cmdPrice = new System.Windows.Forms.Button(); this.cmdEdit = new System.Windows.Forms.Button(); this.cmdNew = new System.Windows.Forms.Button(); this.cmdQuick = new System.Windows.Forms.Button(); this.cmdSort = new System.Windows.Forms.Button(); this.frmTotals = new System.Windows.Forms.GroupBox(); this._lblTotal_5 = new System.Windows.Forms.Label(); this._lblTotal_4 = new System.Windows.Forms.Label(); this._lblTotal_3 = new System.Windows.Forms.Label(); this._lblTotal_2 = new System.Windows.Forms.Label(); this._lblTotal_1 = new System.Windows.Forms.Label(); this._lblTotal_0 = new System.Windows.Forms.Label(); this.lblTotalInclusive = new System.Windows.Forms.Label(); this.lblTotalExclusive = new System.Windows.Forms.Label(); this.lblDepositInclusive = new System.Windows.Forms.Label(); this.lblDepositExclusive = new System.Windows.Forms.Label(); this.lblContentInclusive = new System.Windows.Forms.Label(); this.lblContentExclusive = new System.Windows.Forms.Label(); this._lbl_2 = new System.Windows.Forms.Label(); this.lblBrokenPack = new System.Windows.Forms.Label(); this._lbl_8 = new System.Windows.Forms.Label(); this.lblQuantity = new System.Windows.Forms.Label(); this.Picture1 = new System.Windows.Forms.Panel(); this.lblSupplier = new System.Windows.Forms.Label(); this._txtEdit_0 = new System.Windows.Forms.TextBox(); this.gridItem = new myDataGridView(); this.txtSearch0 = new System.Windows.Forms.TextBox(); this.lstWorkspace = new System.Windows.Forms.ListBox(); this._lbl_1 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.lblReturns = new System.Windows.Forms.Label(); this._lbl_7 = new System.Windows.Forms.Label(); this._lbl_0 = new System.Windows.Forms.Label(); //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lblTotal = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.txtEdit = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components) this.frmFNVeg.SuspendLayout(); this.Picture2.SuspendLayout(); this.frmTotals.SuspendLayout(); this.Picture1.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.gridItem).BeginInit(); //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lblTotal, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.txtEdit, System.ComponentModel.ISupportInitialize).BeginInit() this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.Text = "GRV Processing Form - Fruit and Veg"; this.ClientSize = new System.Drawing.Size(836, 566); this.Location = new System.Drawing.Point(4, 23); this.ControlBox = false; this.KeyPreview = true; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; this.Enabled = true; this.MaximizeBox = true; this.MinimizeBox = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.Name = "frmGRVitemFnV"; this.frmFNVeg.Text = "Pack Size Volume"; this.frmFNVeg.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.frmFNVeg.Size = new System.Drawing.Size(192, 49); this.frmFNVeg.Location = new System.Drawing.Point(48, 472); this.frmFNVeg.TabIndex = 48; this.frmFNVeg.BackColor = System.Drawing.SystemColors.Control; this.frmFNVeg.Enabled = true; this.frmFNVeg.ForeColor = System.Drawing.SystemColors.ControlText; this.frmFNVeg.RightToLeft = System.Windows.Forms.RightToLeft.No; this.frmFNVeg.Visible = true; this.frmFNVeg.Padding = new System.Windows.Forms.Padding(0); this.frmFNVeg.Name = "frmFNVeg"; this.txtPackSize.AutoSize = false; this.txtPackSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtPackSize.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.txtPackSize.Enabled = false; this.txtPackSize.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.txtPackSize.Size = new System.Drawing.Size(100, 19); this.txtPackSize.Location = new System.Drawing.Point(8, 24); this.txtPackSize.TabIndex = 50; this.txtPackSize.Text = "0.00"; this.txtPackSize.AcceptsReturn = true; this.txtPackSize.CausesValidation = true; this.txtPackSize.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPackSize.HideSelection = true; this.txtPackSize.ReadOnly = false; this.txtPackSize.MaxLength = 0; this.txtPackSize.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPackSize.Multiline = false; this.txtPackSize.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPackSize.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPackSize.TabStop = true; this.txtPackSize.Visible = true; this.txtPackSize.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPackSize.Name = "txtPackSize"; this.cmdEditPackSize.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdEditPackSize.Text = "&Edit Size"; this.cmdEditPackSize.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdEditPackSize.Size = new System.Drawing.Size(70, 32); this.cmdEditPackSize.Location = new System.Drawing.Point(112, 14); this.cmdEditPackSize.TabIndex = 49; this.cmdEditPackSize.TabStop = false; this.cmdEditPackSize.Tag = "0"; this.cmdEditPackSize.BackColor = System.Drawing.SystemColors.Control; this.cmdEditPackSize.CausesValidation = true; this.cmdEditPackSize.Enabled = true; this.cmdEditPackSize.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdEditPackSize.Cursor = System.Windows.Forms.Cursors.Default; this.cmdEditPackSize.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdEditPackSize.Name = "cmdEditPackSize"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(142, 19); this.txtSearch.Location = new System.Drawing.Point(45, 104); this.txtSearch.TabIndex = 0; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.txtBCode.AutoSize = false; this.txtBCode.Size = new System.Drawing.Size(142, 19); this.txtBCode.Location = new System.Drawing.Point(45, 99); this.txtBCode.TabIndex = 1; this.txtBCode.Visible = false; this.txtBCode.AcceptsReturn = true; this.txtBCode.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtBCode.BackColor = System.Drawing.SystemColors.Window; this.txtBCode.CausesValidation = true; this.txtBCode.Enabled = true; this.txtBCode.ForeColor = System.Drawing.SystemColors.WindowText; this.txtBCode.HideSelection = true; this.txtBCode.ReadOnly = false; this.txtBCode.MaxLength = 0; this.txtBCode.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtBCode.Multiline = false; this.txtBCode.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtBCode.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtBCode.TabStop = true; this.txtBCode.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtBCode.Name = "txtBCode"; this._txtEdit_2.AutoSize = false; this._txtEdit_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtEdit_2.BackColor = System.Drawing.Color.FromArgb(255, 255, 192); this._txtEdit_2.Size = new System.Drawing.Size(55, 16); this._txtEdit_2.Location = new System.Drawing.Point(534, 87); this._txtEdit_2.MaxLength = 10; this._txtEdit_2.TabIndex = 43; this._txtEdit_2.Tag = "0"; this._txtEdit_2.Text = "0"; this._txtEdit_2.Visible = false; this._txtEdit_2.AcceptsReturn = true; this._txtEdit_2.CausesValidation = true; this._txtEdit_2.Enabled = true; this._txtEdit_2.ForeColor = System.Drawing.SystemColors.WindowText; this._txtEdit_2.HideSelection = true; this._txtEdit_2.ReadOnly = false; this._txtEdit_2.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtEdit_2.Multiline = false; this._txtEdit_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtEdit_2.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtEdit_2.TabStop = true; this._txtEdit_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._txtEdit_2.Name = "_txtEdit_2"; this._txtEdit_1.AutoSize = false; this._txtEdit_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtEdit_1.BackColor = System.Drawing.Color.FromArgb(255, 255, 192); this._txtEdit_1.Size = new System.Drawing.Size(55, 16); this._txtEdit_1.Location = new System.Drawing.Point(462, 87); this._txtEdit_1.MaxLength = 10; this._txtEdit_1.TabIndex = 42; this._txtEdit_1.Tag = "0"; this._txtEdit_1.Text = "0"; this._txtEdit_1.Visible = false; this._txtEdit_1.AcceptsReturn = true; this._txtEdit_1.CausesValidation = true; this._txtEdit_1.Enabled = true; this._txtEdit_1.ForeColor = System.Drawing.SystemColors.WindowText; this._txtEdit_1.HideSelection = true; this._txtEdit_1.ReadOnly = false; this._txtEdit_1.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtEdit_1.Multiline = false; this._txtEdit_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtEdit_1.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtEdit_1.TabStop = true; this._txtEdit_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._txtEdit_1.Name = "_txtEdit_1"; this.Picture2.Dock = System.Windows.Forms.DockStyle.Top; this.Picture2.BackColor = System.Drawing.Color.Blue; this.Picture2.Size = new System.Drawing.Size(836, 49); this.Picture2.Location = new System.Drawing.Point(0, 0); this.Picture2.TabIndex = 27; this.Picture2.TabStop = false; this.Picture2.CausesValidation = true; this.Picture2.Enabled = true; this.Picture2.ForeColor = System.Drawing.SystemColors.ControlText; this.Picture2.Cursor = System.Windows.Forms.Cursors.Default; this.Picture2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Picture2.Visible = true; this.Picture2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Picture2.Name = "Picture2"; this.cmdPriceBOM.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPriceBOM.Text = "Change &BOM Price"; this.cmdPriceBOM.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdPriceBOM.Size = new System.Drawing.Size(70, 40); this.cmdPriceBOM.Location = new System.Drawing.Point(731, 3); this.cmdPriceBOM.TabIndex = 51; this.cmdPriceBOM.TabStop = false; this.cmdPriceBOM.Tag = "0"; this.cmdPriceBOM.Visible = false; this.cmdPriceBOM.BackColor = System.Drawing.SystemColors.Control; this.cmdPriceBOM.CausesValidation = true; this.cmdPriceBOM.Enabled = true; this.cmdPriceBOM.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPriceBOM.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPriceBOM.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPriceBOM.Name = "cmdPriceBOM"; this.tmrAutoGRV.Enabled = false; this.tmrAutoGRV.Interval = 10; this.cmdVat.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdVat.Text = "Change VAT"; this.cmdVat.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdVat.Size = new System.Drawing.Size(70, 40); this.cmdVat.Location = new System.Drawing.Point(435, 3); this.cmdVat.TabIndex = 44; this.cmdVat.TabStop = false; this.cmdVat.Tag = "0"; this.cmdVat.BackColor = System.Drawing.SystemColors.Control; this.cmdVat.CausesValidation = true; this.cmdVat.Enabled = true; this.cmdVat.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdVat.Cursor = System.Windows.Forms.Cursors.Default; this.cmdVat.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdVat.Name = "cmdVat"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdExit.Size = new System.Drawing.Size(67, 40); this.cmdExit.Location = new System.Drawing.Point(885, 3); this.cmdExit.TabIndex = 40; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNext.Text = "&Next >>"; this.cmdNext.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdNext.Size = new System.Drawing.Size(67, 40); this.cmdNext.Location = new System.Drawing.Point(813, 3); this.cmdNext.TabIndex = 39; this.cmdNext.TabStop = false; this.cmdNext.BackColor = System.Drawing.SystemColors.Control; this.cmdNext.CausesValidation = true; this.cmdNext.Enabled = true; this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNext.Name = "cmdNext"; this.cmdBack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBack.Text = "<< &Back"; this.cmdBack.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdBack.Size = new System.Drawing.Size(67, 40); this.cmdBack.Location = new System.Drawing.Point(744, 3); this.cmdBack.TabIndex = 38; this.cmdBack.TabStop = false; this.cmdBack.BackColor = System.Drawing.SystemColors.Control; this.cmdBack.CausesValidation = true; this.cmdBack.Enabled = true; this.cmdBack.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBack.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBack.Name = "cmdBack"; this.cmdStockItem.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdStockItem.Text = "All Stoc&k Items"; this.cmdStockItem.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdStockItem.Size = new System.Drawing.Size(70, 40); this.cmdStockItem.Location = new System.Drawing.Point(3, 3); this.cmdStockItem.TabIndex = 37; this.cmdStockItem.TabStop = false; this.cmdStockItem.Tag = "0"; this.cmdStockItem.BackColor = System.Drawing.SystemColors.Control; this.cmdStockItem.CausesValidation = true; this.cmdStockItem.Enabled = true; this.cmdStockItem.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdStockItem.Cursor = System.Windows.Forms.Cursors.Default; this.cmdStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdStockItem.Name = "cmdStockItem"; this.cmdDiscount.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdDiscount.Text = "&Discount"; this.cmdDiscount.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdDiscount.Size = new System.Drawing.Size(70, 40); this.cmdDiscount.Location = new System.Drawing.Point(291, 3); this.cmdDiscount.TabIndex = 36; this.cmdDiscount.TabStop = false; this.cmdDiscount.BackColor = System.Drawing.SystemColors.Control; this.cmdDiscount.CausesValidation = true; this.cmdDiscount.Enabled = true; this.cmdDiscount.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdDiscount.Cursor = System.Windows.Forms.Cursors.Default; this.cmdDiscount.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdDiscount.Name = "cmdDiscount"; this.cmdPrintOrder.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPrintOrder.Text = "Print &Order"; this.cmdPrintOrder.Size = new System.Drawing.Size(79, 19); this.cmdPrintOrder.Location = new System.Drawing.Point(507, 3); this.cmdPrintOrder.TabIndex = 35; this.cmdPrintOrder.TabStop = false; this.cmdPrintOrder.BackColor = System.Drawing.SystemColors.Control; this.cmdPrintOrder.CausesValidation = true; this.cmdPrintOrder.Enabled = true; this.cmdPrintOrder.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrintOrder.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrintOrder.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrintOrder.Name = "cmdPrintOrder"; this.cmdPrintGRV.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPrintGRV.Text = "Print &GRV"; this.cmdPrintGRV.Size = new System.Drawing.Size(79, 19); this.cmdPrintGRV.Location = new System.Drawing.Point(507, 24); this.cmdPrintGRV.TabIndex = 34; this.cmdPrintGRV.TabStop = false; this.cmdPrintGRV.BackColor = System.Drawing.SystemColors.Control; this.cmdPrintGRV.CausesValidation = true; this.cmdPrintGRV.Enabled = true; this.cmdPrintGRV.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrintGRV.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrintGRV.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrintGRV.Name = "cmdPrintGRV"; this.cmdDelete.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdDelete.Text = "Dele&te"; this.cmdDelete.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdDelete.Size = new System.Drawing.Size(70, 40); this.cmdDelete.Location = new System.Drawing.Point(75, 3); this.cmdDelete.TabIndex = 33; this.cmdDelete.TabStop = false; this.cmdDelete.Tag = "0"; this.cmdDelete.BackColor = System.Drawing.SystemColors.Control; this.cmdDelete.CausesValidation = true; this.cmdDelete.Enabled = true; this.cmdDelete.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdDelete.Cursor = System.Windows.Forms.Cursors.Default; this.cmdDelete.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdDelete.Name = "cmdDelete"; this.cmdPack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPack.Text = "Break / Build P&ack"; this.cmdPack.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdPack.Size = new System.Drawing.Size(70, 40); this.cmdPack.Location = new System.Drawing.Point(147, 3); this.cmdPack.TabIndex = 32; this.cmdPack.TabStop = false; this.cmdPack.Tag = "0"; this.cmdPack.BackColor = System.Drawing.SystemColors.Control; this.cmdPack.CausesValidation = true; this.cmdPack.Enabled = true; this.cmdPack.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPack.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPack.Name = "cmdPack"; this.cmdPrice.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPrice.Text = "&Change Price"; this.cmdPrice.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdPrice.Size = new System.Drawing.Size(70, 40); this.cmdPrice.Location = new System.Drawing.Point(219, 3); this.cmdPrice.TabIndex = 31; this.cmdPrice.TabStop = false; this.cmdPrice.Tag = "0"; this.cmdPrice.BackColor = System.Drawing.SystemColors.Control; this.cmdPrice.CausesValidation = true; this.cmdPrice.Enabled = true; this.cmdPrice.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrice.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrice.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrice.Name = "cmdPrice"; this.cmdEdit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdEdit.Text = "&Edit Stock Item"; this.cmdEdit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdEdit.Size = new System.Drawing.Size(70, 40); this.cmdEdit.Location = new System.Drawing.Point(588, 3); this.cmdEdit.TabIndex = 30; this.cmdEdit.TabStop = false; this.cmdEdit.Tag = "0"; this.cmdEdit.Visible = false; this.cmdEdit.BackColor = System.Drawing.SystemColors.Control; this.cmdEdit.CausesValidation = true; this.cmdEdit.Enabled = true; this.cmdEdit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdEdit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdEdit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdEdit.Name = "cmdEdit"; this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNew.Text = "Ne&w Stock Item"; this.cmdNew.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdNew.Size = new System.Drawing.Size(70, 40); this.cmdNew.Location = new System.Drawing.Point(660, 3); this.cmdNew.TabIndex = 29; this.cmdNew.TabStop = false; this.cmdNew.Tag = "0"; this.cmdNew.Visible = false; this.cmdNew.BackColor = System.Drawing.SystemColors.Control; this.cmdNew.CausesValidation = true; this.cmdNew.Enabled = true; this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNew.Name = "cmdNew"; this.cmdQuick.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdQuick.Text = "&Quick Edit"; this.cmdQuick.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdQuick.Size = new System.Drawing.Size(70, 40); this.cmdQuick.Location = new System.Drawing.Point(363, 3); this.cmdQuick.TabIndex = 28; this.cmdQuick.TabStop = false; this.cmdQuick.BackColor = System.Drawing.SystemColors.Control; this.cmdQuick.CausesValidation = true; this.cmdQuick.Enabled = true; this.cmdQuick.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdQuick.Cursor = System.Windows.Forms.Cursors.Default; this.cmdQuick.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdQuick.Name = "cmdQuick"; this.cmdSort.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdSort.Text = "&Sort"; this.cmdSort.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdSort.Size = new System.Drawing.Size(73, 40); this.cmdSort.Location = new System.Drawing.Point(3, 3); this.cmdSort.TabIndex = 41; this.cmdSort.TabStop = false; this.cmdSort.Tag = "0"; this.cmdSort.BackColor = System.Drawing.SystemColors.Control; this.cmdSort.CausesValidation = true; this.cmdSort.Enabled = true; this.cmdSort.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdSort.Cursor = System.Windows.Forms.Cursors.Default; this.cmdSort.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdSort.Name = "cmdSort"; this.frmTotals.Text = "Sub Totals"; this.frmTotals.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.frmTotals.Size = new System.Drawing.Size(457, 130); this.frmTotals.Location = new System.Drawing.Point(102, 294); this.frmTotals.TabIndex = 9; this.frmTotals.BackColor = System.Drawing.SystemColors.Control; this.frmTotals.Enabled = true; this.frmTotals.ForeColor = System.Drawing.SystemColors.ControlText; this.frmTotals.RightToLeft = System.Windows.Forms.RightToLeft.No; this.frmTotals.Visible = true; this.frmTotals.Padding = new System.Windows.Forms.Padding(0); this.frmTotals.Name = "frmTotals"; this._lblTotal_5.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_5.BackColor = System.Drawing.Color.Transparent; this._lblTotal_5.Text = "Inclusive Total :"; this._lblTotal_5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lblTotal_5.Size = new System.Drawing.Size(115, 16); this._lblTotal_5.Location = new System.Drawing.Point(234, 102); this._lblTotal_5.TabIndex = 26; this._lblTotal_5.Enabled = true; this._lblTotal_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_5.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_5.UseMnemonic = true; this._lblTotal_5.Visible = true; this._lblTotal_5.AutoSize = false; this._lblTotal_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_5.Name = "_lblTotal_5"; this._lblTotal_4.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_4.BackColor = System.Drawing.Color.Transparent; this._lblTotal_4.Text = "Exclusive Total :"; this._lblTotal_4.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lblTotal_4.Size = new System.Drawing.Size(115, 16); this._lblTotal_4.Location = new System.Drawing.Point(234, 84); this._lblTotal_4.TabIndex = 25; this._lblTotal_4.Enabled = true; this._lblTotal_4.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_4.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_4.UseMnemonic = true; this._lblTotal_4.Visible = true; this._lblTotal_4.AutoSize = false; this._lblTotal_4.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_4.Name = "_lblTotal_4"; this._lblTotal_3.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_3.BackColor = System.Drawing.Color.Transparent; this._lblTotal_3.Text = "Total Selling :"; this._lblTotal_3.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lblTotal_3.Size = new System.Drawing.Size(115, 16); this._lblTotal_3.Location = new System.Drawing.Point(234, 66); this._lblTotal_3.TabIndex = 24; this._lblTotal_3.Enabled = true; this._lblTotal_3.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_3.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_3.UseMnemonic = true; this._lblTotal_3.Visible = true; this._lblTotal_3.AutoSize = false; this._lblTotal_3.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_3.Name = "_lblTotal_3"; this._lblTotal_2.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_2.BackColor = System.Drawing.Color.Transparent; this._lblTotal_2.Text = "Total GP% :"; this._lblTotal_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lblTotal_2.Size = new System.Drawing.Size(115, 16); this._lblTotal_2.Location = new System.Drawing.Point(234, 48); this._lblTotal_2.TabIndex = 23; this._lblTotal_2.Enabled = true; this._lblTotal_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_2.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_2.UseMnemonic = true; this._lblTotal_2.Visible = true; this._lblTotal_2.AutoSize = false; this._lblTotal_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_2.Name = "_lblTotal_2"; this._lblTotal_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_1.BackColor = System.Drawing.Color.Transparent; this._lblTotal_1.Text = "Inclusive Content :"; this._lblTotal_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lblTotal_1.Size = new System.Drawing.Size(115, 16); this._lblTotal_1.Location = new System.Drawing.Point(234, 30); this._lblTotal_1.TabIndex = 22; this._lblTotal_1.Enabled = true; this._lblTotal_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_1.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_1.UseMnemonic = true; this._lblTotal_1.Visible = true; this._lblTotal_1.AutoSize = false; this._lblTotal_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_1.Name = "_lblTotal_1"; this._lblTotal_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_0.BackColor = System.Drawing.Color.Transparent; this._lblTotal_0.Text = "Exclusive Content :"; this._lblTotal_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lblTotal_0.Size = new System.Drawing.Size(115, 16); this._lblTotal_0.Location = new System.Drawing.Point(234, 12); this._lblTotal_0.TabIndex = 21; this._lblTotal_0.Enabled = true; this._lblTotal_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_0.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_0.UseMnemonic = true; this._lblTotal_0.Visible = true; this._lblTotal_0.AutoSize = false; this._lblTotal_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_0.Name = "_lblTotal_0"; this.lblTotalInclusive.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalInclusive.BackColor = System.Drawing.Color.FromArgb(128, 255, 128); this.lblTotalInclusive.Text = "0.00"; this.lblTotalInclusive.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.lblTotalInclusive.Size = new System.Drawing.Size(100, 16); this.lblTotalInclusive.Location = new System.Drawing.Point(351, 102); this.lblTotalInclusive.TabIndex = 20; this.lblTotalInclusive.Enabled = true; this.lblTotalInclusive.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalInclusive.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalInclusive.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalInclusive.UseMnemonic = true; this.lblTotalInclusive.Visible = true; this.lblTotalInclusive.AutoSize = false; this.lblTotalInclusive.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalInclusive.Name = "lblTotalInclusive"; this.lblTotalExclusive.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalExclusive.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblTotalExclusive.Text = "0.00"; this.lblTotalExclusive.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.lblTotalExclusive.Size = new System.Drawing.Size(100, 16); this.lblTotalExclusive.Location = new System.Drawing.Point(351, 84); this.lblTotalExclusive.TabIndex = 19; this.lblTotalExclusive.Enabled = true; this.lblTotalExclusive.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalExclusive.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalExclusive.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalExclusive.UseMnemonic = true; this.lblTotalExclusive.Visible = true; this.lblTotalExclusive.AutoSize = false; this.lblTotalExclusive.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalExclusive.Name = "lblTotalExclusive"; this.lblDepositInclusive.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblDepositInclusive.BackColor = System.Drawing.Color.FromArgb(128, 128, 255); this.lblDepositInclusive.Text = "0.00"; this.lblDepositInclusive.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.lblDepositInclusive.Size = new System.Drawing.Size(100, 16); this.lblDepositInclusive.Location = new System.Drawing.Point(351, 66); this.lblDepositInclusive.TabIndex = 18; this.lblDepositInclusive.Enabled = true; this.lblDepositInclusive.ForeColor = System.Drawing.SystemColors.ControlText; this.lblDepositInclusive.Cursor = System.Windows.Forms.Cursors.Default; this.lblDepositInclusive.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblDepositInclusive.UseMnemonic = true; this.lblDepositInclusive.Visible = true; this.lblDepositInclusive.AutoSize = false; this.lblDepositInclusive.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblDepositInclusive.Name = "lblDepositInclusive"; this.lblDepositExclusive.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblDepositExclusive.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.lblDepositExclusive.Text = "0.00"; this.lblDepositExclusive.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.lblDepositExclusive.Size = new System.Drawing.Size(100, 16); this.lblDepositExclusive.Location = new System.Drawing.Point(351, 48); this.lblDepositExclusive.TabIndex = 17; this.lblDepositExclusive.Enabled = true; this.lblDepositExclusive.ForeColor = System.Drawing.SystemColors.ControlText; this.lblDepositExclusive.Cursor = System.Windows.Forms.Cursors.Default; this.lblDepositExclusive.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblDepositExclusive.UseMnemonic = true; this.lblDepositExclusive.Visible = true; this.lblDepositExclusive.AutoSize = false; this.lblDepositExclusive.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblDepositExclusive.Name = "lblDepositExclusive"; this.lblContentInclusive.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblContentInclusive.BackColor = System.Drawing.Color.FromArgb(128, 128, 255); this.lblContentInclusive.Text = "0.00"; this.lblContentInclusive.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.lblContentInclusive.Size = new System.Drawing.Size(100, 16); this.lblContentInclusive.Location = new System.Drawing.Point(351, 30); this.lblContentInclusive.TabIndex = 16; this.lblContentInclusive.Enabled = true; this.lblContentInclusive.ForeColor = System.Drawing.SystemColors.ControlText; this.lblContentInclusive.Cursor = System.Windows.Forms.Cursors.Default; this.lblContentInclusive.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblContentInclusive.UseMnemonic = true; this.lblContentInclusive.Visible = true; this.lblContentInclusive.AutoSize = false; this.lblContentInclusive.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblContentInclusive.Name = "lblContentInclusive"; this.lblContentExclusive.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblContentExclusive.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.lblContentExclusive.Text = "0.00"; this.lblContentExclusive.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.lblContentExclusive.Size = new System.Drawing.Size(100, 16); this.lblContentExclusive.Location = new System.Drawing.Point(351, 12); this.lblContentExclusive.TabIndex = 15; this.lblContentExclusive.Enabled = true; this.lblContentExclusive.ForeColor = System.Drawing.SystemColors.ControlText; this.lblContentExclusive.Cursor = System.Windows.Forms.Cursors.Default; this.lblContentExclusive.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblContentExclusive.UseMnemonic = true; this.lblContentExclusive.Visible = true; this.lblContentExclusive.AutoSize = false; this.lblContentExclusive.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblContentExclusive.Name = "lblContentExclusive"; this._lbl_2.Text = "Broken Packs"; this._lbl_2.Size = new System.Drawing.Size(67, 13); this._lbl_2.Location = new System.Drawing.Point(78, 15); this._lbl_2.TabIndex = 13; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_2.BackColor = System.Drawing.Color.Transparent; this._lbl_2.Enabled = true; this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_2.UseMnemonic = true; this._lbl_2.Visible = true; this._lbl_2.AutoSize = true; this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_2.Name = "_lbl_2"; this.lblBrokenPack.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblBrokenPack.Text = "lblQuantity"; this.lblBrokenPack.Size = new System.Drawing.Size(64, 17); this.lblBrokenPack.Location = new System.Drawing.Point(81, 27); this.lblBrokenPack.TabIndex = 12; this.lblBrokenPack.BackColor = System.Drawing.SystemColors.Control; this.lblBrokenPack.Enabled = true; this.lblBrokenPack.ForeColor = System.Drawing.SystemColors.ControlText; this.lblBrokenPack.Cursor = System.Windows.Forms.Cursors.Default; this.lblBrokenPack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblBrokenPack.UseMnemonic = true; this.lblBrokenPack.Visible = true; this.lblBrokenPack.AutoSize = false; this.lblBrokenPack.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblBrokenPack.Name = "lblBrokenPack"; this._lbl_8.Text = "No Of Cases"; this._lbl_8.Size = new System.Drawing.Size(60, 13); this._lbl_8.Location = new System.Drawing.Point(9, 15); this._lbl_8.TabIndex = 11; this._lbl_8.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_8.BackColor = System.Drawing.Color.Transparent; this._lbl_8.Enabled = true; this._lbl_8.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_8.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_8.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_8.UseMnemonic = true; this._lbl_8.Visible = true; this._lbl_8.AutoSize = true; this._lbl_8.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_8.Name = "_lbl_8"; this.lblQuantity.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblQuantity.Text = "lblQuantity"; this.lblQuantity.Size = new System.Drawing.Size(64, 17); this.lblQuantity.Location = new System.Drawing.Point(9, 27); this.lblQuantity.TabIndex = 10; this.lblQuantity.BackColor = System.Drawing.SystemColors.Control; this.lblQuantity.Enabled = true; this.lblQuantity.ForeColor = System.Drawing.SystemColors.ControlText; this.lblQuantity.Cursor = System.Windows.Forms.Cursors.Default; this.lblQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblQuantity.UseMnemonic = true; this.lblQuantity.Visible = true; this.lblQuantity.AutoSize = false; this.lblQuantity.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblQuantity.Name = "lblQuantity"; this.Picture1.Dock = System.Windows.Forms.DockStyle.Top; this.Picture1.BackColor = System.Drawing.Color.Red; this.Picture1.Size = new System.Drawing.Size(836, 25); this.Picture1.Location = new System.Drawing.Point(0, 49); this.Picture1.TabIndex = 7; this.Picture1.TabStop = false; this.Picture1.CausesValidation = true; this.Picture1.Enabled = true; this.Picture1.ForeColor = System.Drawing.SystemColors.ControlText; this.Picture1.Cursor = System.Windows.Forms.Cursors.Default; this.Picture1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Picture1.Visible = true; this.Picture1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Picture1.Name = "Picture1"; this.lblSupplier.Text = "lblSupplier"; this.lblSupplier.Font = new System.Drawing.Font("Arial", 12f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.lblSupplier.ForeColor = System.Drawing.Color.White; this.lblSupplier.Size = new System.Drawing.Size(85, 20); this.lblSupplier.Location = new System.Drawing.Point(0, 0); this.lblSupplier.TabIndex = 8; this.lblSupplier.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblSupplier.BackColor = System.Drawing.Color.Transparent; this.lblSupplier.Enabled = true; this.lblSupplier.Cursor = System.Windows.Forms.Cursors.Default; this.lblSupplier.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblSupplier.UseMnemonic = true; this.lblSupplier.Visible = true; this.lblSupplier.AutoSize = true; this.lblSupplier.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblSupplier.Name = "lblSupplier"; this._txtEdit_0.AutoSize = false; this._txtEdit_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtEdit_0.BackColor = System.Drawing.Color.FromArgb(255, 255, 192); this._txtEdit_0.Size = new System.Drawing.Size(55, 16); this._txtEdit_0.Location = new System.Drawing.Point(279, 138); this._txtEdit_0.MaxLength = 8; this._txtEdit_0.TabIndex = 3; this._txtEdit_0.Tag = "0"; this._txtEdit_0.Text = "0"; this._txtEdit_0.Visible = false; this._txtEdit_0.AcceptsReturn = true; this._txtEdit_0.CausesValidation = true; this._txtEdit_0.Enabled = true; this._txtEdit_0.ForeColor = System.Drawing.SystemColors.WindowText; this._txtEdit_0.HideSelection = true; this._txtEdit_0.ReadOnly = false; this._txtEdit_0.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtEdit_0.Multiline = false; this._txtEdit_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtEdit_0.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtEdit_0.TabStop = true; this._txtEdit_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._txtEdit_0.Name = "_txtEdit_0"; //gridItem.OcxState = CType(resources.GetObject("gridItem.OcxState"), System.Windows.Forms.AxHost.State) this.gridItem.Size = new System.Drawing.Size(493, 319); this.gridItem.Location = new System.Drawing.Point(195, 117); this.gridItem.TabIndex = 4; this.gridItem.Name = "gridItem"; this.txtSearch0.AutoSize = false; this.txtSearch0.Size = new System.Drawing.Size(142, 19); this.txtSearch0.Location = new System.Drawing.Point(45, 99); this.txtSearch0.TabIndex = 47; this.txtSearch0.Visible = false; this.txtSearch0.AcceptsReturn = true; this.txtSearch0.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch0.BackColor = System.Drawing.SystemColors.Window; this.txtSearch0.CausesValidation = true; this.txtSearch0.Enabled = true; this.txtSearch0.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch0.HideSelection = true; this.txtSearch0.ReadOnly = false; this.txtSearch0.MaxLength = 0; this.txtSearch0.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch0.Multiline = false; this.txtSearch0.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch0.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch0.TabStop = true; this.txtSearch0.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch0.Name = "txtSearch0"; this.lstWorkspace.Size = new System.Drawing.Size(187, 306); this.lstWorkspace.Location = new System.Drawing.Point(0, 128); this.lstWorkspace.TabIndex = 2; this.lstWorkspace.TabStop = false; this.lstWorkspace.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lstWorkspace.BackColor = System.Drawing.SystemColors.Window; this.lstWorkspace.CausesValidation = true; this.lstWorkspace.Enabled = true; this.lstWorkspace.ForeColor = System.Drawing.SystemColors.WindowText; this.lstWorkspace.IntegralHeight = true; this.lstWorkspace.Cursor = System.Windows.Forms.Cursors.Default; this.lstWorkspace.SelectionMode = System.Windows.Forms.SelectionMode.One; this.lstWorkspace.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lstWorkspace.Sorted = false; this.lstWorkspace.Visible = true; this.lstWorkspace.MultiColumn = false; this.lstWorkspace.Name = "lstWorkspace"; this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_1.Text = "&Search"; this._lbl_1.Size = new System.Drawing.Size(34, 13); this._lbl_1.Location = new System.Drawing.Point(8, 104); this._lbl_1.TabIndex = 46; this._lbl_1.BackColor = System.Drawing.Color.Transparent; this._lbl_1.Enabled = true; this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_1.UseMnemonic = true; this._lbl_1.Visible = true; this._lbl_1.AutoSize = true; this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_1.Name = "_lbl_1"; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopRight; this.Label1.Text = "&Barcode"; this.Label1.Size = new System.Drawing.Size(40, 13); this.Label1.Location = new System.Drawing.Point(0, 102); this.Label1.TabIndex = 45; this.Label1.Visible = false; this.Label1.BackColor = System.Drawing.Color.Transparent; this.Label1.Enabled = true; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.AutoSize = true; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this.lblReturns.BackColor = System.Drawing.Color.Red; this.lblReturns.Text = "RETURNS"; this.lblReturns.Font = new System.Drawing.Font("Arial", 24f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.lblReturns.ForeColor = System.Drawing.SystemColors.WindowText; this.lblReturns.Size = new System.Drawing.Size(166, 34); this.lblReturns.Location = new System.Drawing.Point(195, 480); this.lblReturns.TabIndex = 14; this.lblReturns.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblReturns.Enabled = true; this.lblReturns.Cursor = System.Windows.Forms.Cursors.Default; this.lblReturns.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblReturns.UseMnemonic = true; this.lblReturns.Visible = true; this.lblReturns.AutoSize = false; this.lblReturns.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblReturns.Name = "lblReturns"; this._lbl_7.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_7.Text = "Search"; this._lbl_7.Size = new System.Drawing.Size(34, 13); this._lbl_7.Location = new System.Drawing.Point(48, 102); this._lbl_7.TabIndex = 5; this._lbl_7.Visible = false; this._lbl_7.BackColor = System.Drawing.Color.Transparent; this._lbl_7.Enabled = true; this._lbl_7.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_7.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_7.UseMnemonic = true; this._lbl_7.AutoSize = true; this._lbl_7.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_7.Name = "_lbl_7"; this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopCenter; this._lbl_0.BackColor = System.Drawing.Color.FromArgb(128, 128, 255); this._lbl_0.Text = "Stock Item Selector"; this._lbl_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_0.ForeColor = System.Drawing.Color.White; this._lbl_0.Size = new System.Drawing.Size(190, 16); this._lbl_0.Location = new System.Drawing.Point(0, 81); this._lbl_0.TabIndex = 6; this._lbl_0.Enabled = true; this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_0.UseMnemonic = true; this._lbl_0.Visible = true; this._lbl_0.AutoSize = false; this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._lbl_0.Name = "_lbl_0"; this.Controls.Add(frmFNVeg); this.Controls.Add(txtSearch); this.Controls.Add(txtBCode); this.Controls.Add(_txtEdit_2); this.Controls.Add(_txtEdit_1); this.Controls.Add(Picture2); this.Controls.Add(frmTotals); this.Controls.Add(Picture1); this.Controls.Add(_txtEdit_0); this.Controls.Add(gridItem); this.Controls.Add(txtSearch0); this.Controls.Add(lstWorkspace); this.Controls.Add(_lbl_1); this.Controls.Add(Label1); this.Controls.Add(lblReturns); this.Controls.Add(_lbl_7); this.Controls.Add(_lbl_0); this.frmFNVeg.Controls.Add(txtPackSize); this.frmFNVeg.Controls.Add(cmdEditPackSize); this.Picture2.Controls.Add(cmdPriceBOM); this.Picture2.Controls.Add(cmdVat); this.Picture2.Controls.Add(cmdExit); this.Picture2.Controls.Add(cmdNext); this.Picture2.Controls.Add(cmdBack); this.Picture2.Controls.Add(cmdStockItem); this.Picture2.Controls.Add(cmdDiscount); this.Picture2.Controls.Add(cmdPrintOrder); this.Picture2.Controls.Add(cmdPrintGRV); this.Picture2.Controls.Add(cmdDelete); this.Picture2.Controls.Add(cmdPack); this.Picture2.Controls.Add(cmdPrice); this.Picture2.Controls.Add(cmdEdit); this.Picture2.Controls.Add(cmdNew); this.Picture2.Controls.Add(cmdQuick); this.Picture2.Controls.Add(cmdSort); this.frmTotals.Controls.Add(_lblTotal_5); this.frmTotals.Controls.Add(_lblTotal_4); this.frmTotals.Controls.Add(_lblTotal_3); this.frmTotals.Controls.Add(_lblTotal_2); this.frmTotals.Controls.Add(_lblTotal_1); this.frmTotals.Controls.Add(_lblTotal_0); this.frmTotals.Controls.Add(lblTotalInclusive); this.frmTotals.Controls.Add(lblTotalExclusive); this.frmTotals.Controls.Add(lblDepositInclusive); this.frmTotals.Controls.Add(lblDepositExclusive); this.frmTotals.Controls.Add(lblContentInclusive); this.frmTotals.Controls.Add(lblContentExclusive); this.frmTotals.Controls.Add(_lbl_2); this.frmTotals.Controls.Add(lblBrokenPack); this.frmTotals.Controls.Add(_lbl_8); this.frmTotals.Controls.Add(lblQuantity); this.Picture1.Controls.Add(lblSupplier); //Me.lbl.SetIndex(_lbl_2, CType(2, Short)) //Me.lbl.SetIndex(_lbl_8, CType(8, Short)) //Me.lbl.SetIndex(_lbl_1, CType(1, Short)) //Me.lbl.SetIndex(_lbl_7, CType(7, Short)) //Me.lbl.SetIndex(_lbl_0, CType(0, Short)) //Me.lblTotal.SetIndex(_lblTotal_5, CType(5, Short)) //Me.lblTotal.SetIndex(_lblTotal_4, CType(4, Short)) //Me.lblTotal.SetIndex(_lblTotal_3, CType(3, Short)) //Me.lblTotal.SetIndex(_lblTotal_2, CType(2, Short)) //Me.lblTotal.SetIndex(_lblTotal_1, CType(1, Short)) //Me.lblTotal.SetIndex(_lblTotal_0, CType(0, Short)) //Me.txtEdit.SetIndex(_txtEdit_2, CType(2, Short)) //Me.txtEdit.SetIndex(_txtEdit_1, CType(1, Short)) //Me.txtEdit.SetIndex(_txtEdit_0, CType(0, Short)) //CType(Me.txtEdit, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lblTotal, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() ((System.ComponentModel.ISupportInitialize)this.gridItem).EndInit(); this.frmFNVeg.ResumeLayout(false); this.Picture2.ResumeLayout(false); this.frmTotals.ResumeLayout(false); this.Picture1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using WebsitePanel.Providers.Common; using System.Linq; namespace WebsitePanel.Providers.Web { public class HtaccessFolder : IComparable { #region Constants public const string HTTPD_CONF_FILE = "httpd.conf"; public const string HTACCESS_FILE = ".htaccess"; public const string HTPASSWDS_FILE = ".htpasswds"; public const string HTGROUPS_FILE = ".htgroups"; public const string AUTH_NAME_DIRECTIVE = "AuthName"; public const string AUTH_TYPE_DIRECTIVE = "AuthType"; public const string AUTH_TYPE_BASIC = "Basic"; public const string AUTH_TYPE_DIGEST = "Digest"; public const string DEFAULT_AUTH_TYPE = AUTH_TYPE_BASIC; public static readonly string[] PASSWORD_ENCODING_TYPES = new string[] { "Apache MD5", "Unix Crypt", "SHA1" }; public static readonly string[] AUTH_TYPES = new string[] { AUTH_TYPE_BASIC, AUTH_TYPE_DIGEST }; public const string REQUIRE_DIRECTIVE = "Require"; public const string AUTH_BASIC_PROVIDER_FILE = "AuthBasicProvider file"; public const string AUTH_DIGEST_PROVIDER_FILE = "AuthDigestProvider file"; public const string VALID_USER = "valid-user"; public const string REQUIRE_USER = "user"; public const string REQUIRE_GROUP = "group"; public const string AUTH_USER_FILE_DIRECTIVE = "AuthUserFile"; public const string AUTH_GROUP_FILE_DIRECTIVE = "AuthGroupFile"; protected static string LinesSeparator = System.Environment.NewLine; #endregion #region parsing regexps protected static readonly Regex RE_AUTH_NAME = new Regex("^\\s*AuthName\\s+\"?([^\"]+)\"?\\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); protected static readonly Regex RE_AUTH_TYPE = new Regex(@"^\s*AuthType\s+(basic|digest)\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); protected static readonly Regex RE_REQUIRE = new Regex(@"^\s*Require\s+(.+)\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); protected static readonly Regex RE_AUTH_PROVIDER = new Regex(@"^\s*Auth(Basic|Digest)Provider\s+(file)\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); protected static readonly Regex RE_AUTH_USER_FILE = new Regex(@"^\s*AuthUserFile\s+(.+)\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); protected static readonly Regex RE_AUTH_GROUP_FILE = new Regex(@"^\s*AuthGroupFile\s+(.+)\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); public static readonly Regex RE_DIGEST_PASSWORD = new Regex(@"^[^:]*:[0-9a-f]{32}$", RegexOptions.Compiled | RegexOptions.IgnoreCase); #endregion #region private fields private string siteRootPath; private string path; private string contentPath; private string htaccessContent; private string authName; private string authType = DEFAULT_AUTH_TYPE; private List<string> users; private List<string> groups; private bool validUser = false; private string authUserFile; private string authGroupFile; private bool doAuthUpdate = false; private string filename = HTACCESS_FILE; #endregion #region public properties public string Path { get { return path; } set { path = value; if (path.EndsWith("\\") && !path.Equals("\\")) { path = path.Substring(0, path.Length - 1); } } } public string ContentPath { get { return contentPath; } set { contentPath = value; } } public string HtaccessContent { get { return htaccessContent; } set { htaccessContent = value; } } public string AuthName { get { return authName; } set { authName = value; } } public string AuthType { get { return authType; } set { authType = value; } } public List<string> Users { get { return users; } set { users = value; } } public List<string> Groups { get { return groups; } set { groups = value; } } public bool ValidUser { get { return validUser; } set { validUser = value; } } public bool DoAuthUpdate { get { return doAuthUpdate; } set { doAuthUpdate = value; } } public string AuthUserFile { get { return authUserFile; } set { authUserFile = value; } } public string AuthGroupFile { get { return authGroupFile; } set { authGroupFile = value; } } public string SiteRootPath { get { return siteRootPath; } set { siteRootPath = value; } } #endregion public HtaccessFolder() { Users = new List<string>(); Groups = new List<string>(); } public HtaccessFolder(string siteRootPath, string path, string contentPath) : this() { this.SiteRootPath = siteRootPath; this.Path = path; this.ContentPath = contentPath; ReadHtaccess(); } private void ReadHttpdConf() { filename = HTTPD_CONF_FILE; string htpath = System.IO.Path.Combine(ContentPath, filename); HtaccessContent = ReadFile(htpath); } public void ReadHtaccess() { filename = HTACCESS_FILE; string htpath = System.IO.Path.Combine(ContentPath, filename); HtaccessContent = ReadFile(htpath); ParseHtaccess(); } private void ParseHtaccess() { validUser = false; Match mAuthName = RE_AUTH_NAME.Match(HtaccessContent); if (mAuthName.Success) { AuthName = mAuthName.Groups[1].Value; } Match mAuthType = RE_AUTH_TYPE.Match(HtaccessContent); if (mAuthType.Success) { AuthType = mAuthType.Groups[1].Value; } Match mRequire = RE_REQUIRE.Match(HtaccessContent); if (mRequire.Success) { ParseRequirements(mRequire.Groups[1].Value); } Match mAuthUserFile = RE_AUTH_USER_FILE.Match(HtaccessContent); if (mAuthUserFile.Success) { AuthUserFile = mAuthUserFile.Groups[1].Value; } else { string authUserFilePath = System.IO.Path.Combine(SiteRootPath, HTPASSWDS_FILE); if (File.Exists(authUserFilePath)) { AuthUserFile = authUserFilePath; } } Match mAuthGroupFile = RE_AUTH_GROUP_FILE.Match(HtaccessContent); if (mAuthGroupFile.Success) { AuthGroupFile = mAuthGroupFile.Groups[1].Value; } else { string authGroupFilePath = System.IO.Path.Combine(SiteRootPath, HTGROUPS_FILE); if (File.Exists(authGroupFilePath)) { AuthGroupFile = authGroupFilePath; } } } private void ParseRequirements(string requirementsLine) { bool acceptUsers = false, acceptGroups = false; foreach (string requirement in requirementsLine.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)) { string req = requirement.Trim(); if (req.Equals(VALID_USER)) { ValidUser = true; acceptUsers = acceptGroups = false; } else if (req.Equals(REQUIRE_USER)) { acceptUsers = true; acceptGroups = false; } else if (req.Equals(REQUIRE_GROUP)) { acceptUsers = false; acceptGroups = true; } else { if (acceptUsers) { Users.Add(req); } else if (acceptGroups) { Groups.Add(req); } } } } public void Update() { if (Directory.Exists(ContentPath)) { if (doAuthUpdate) { UpdateAuthDirectives(); } string htaccessPath = System.IO.Path.Combine(ContentPath, filename); WriteFile(htaccessPath, HtaccessContent); } } private void UpdateAuthDirectives() { if (Users.Contains(VALID_USER)) { ValidUser = true; Users.Remove(VALID_USER); } else { ValidUser = false; } // update AuthName Match mAuthName = RE_AUTH_NAME.Match(HtaccessContent); if (!string.IsNullOrEmpty(AuthName)) { string s = string.Format("{0} \"{1}\"", AUTH_NAME_DIRECTIVE, AuthName); if (mAuthName.Success) { HtaccessContent = RE_AUTH_NAME.Replace(HtaccessContent, s); } else { HtaccessContent += s + Environment.NewLine; } } else { if (mAuthName.Success) { HtaccessContent = RE_AUTH_NAME.Replace(HtaccessContent, ""); } } // update AuthType Match mAuthType = RE_AUTH_TYPE.Match(HtaccessContent); if (!string.IsNullOrEmpty(AuthType)) { string s = string.Format("{0} {1}", AUTH_TYPE_DIRECTIVE, AuthType); if (mAuthType.Success) { HtaccessContent = RE_AUTH_TYPE.Replace(HtaccessContent, s); } else { HtaccessContent += s + Environment.NewLine; } } else { if (mAuthType.Success) { HtaccessContent = RE_AUTH_TYPE.Replace(HtaccessContent, ""); } } // update Auth(Basic|Digest)Provider Match mAuthProvider = RE_AUTH_PROVIDER.Match(HtaccessContent); string prov = AuthType == "Basic" ? AUTH_BASIC_PROVIDER_FILE : AUTH_DIGEST_PROVIDER_FILE; if (mAuthProvider.Success) { HtaccessContent = RE_AUTH_PROVIDER.Replace(HtaccessContent, prov); } else { HtaccessContent += prov + Environment.NewLine; } // update AuthUserFile Match mAuthUserFile = RE_AUTH_USER_FILE.Match(HtaccessContent); if (!string.IsNullOrEmpty(AuthUserFile)) { string s = string.Format("{0} {1}", AUTH_USER_FILE_DIRECTIVE, AuthUserFile); if (mAuthUserFile.Success) { HtaccessContent = RE_AUTH_USER_FILE.Replace(HtaccessContent, s); } else { HtaccessContent += s + Environment.NewLine; } } else { if (mAuthUserFile.Success) { HtaccessContent = RE_AUTH_USER_FILE.Replace(HtaccessContent, ""); } } // update AuthUserFile Match mAuthGroupFile = RE_AUTH_GROUP_FILE.Match(HtaccessContent); if (!string.IsNullOrEmpty(AuthGroupFile)) { string s = string.Format("{0} {1}", AUTH_GROUP_FILE_DIRECTIVE, AuthGroupFile); if (mAuthGroupFile.Success) { HtaccessContent = RE_AUTH_GROUP_FILE.Replace(HtaccessContent, s); } else { HtaccessContent += s + Environment.NewLine; } } else { if (mAuthGroupFile.Success) { HtaccessContent = RE_AUTH_GROUP_FILE.Replace(HtaccessContent, ""); } } // update Require Match mRequire = RE_REQUIRE.Match(HtaccessContent); if (ValidUser || Users.Count > 0 || Groups.Count > 0) { string s = GenerateReqiure(); if (mRequire.Success) { HtaccessContent = RE_REQUIRE.Replace(HtaccessContent, s); } else { HtaccessContent += s + Environment.NewLine; } } else { if (mRequire.Success) { HtaccessContent = RE_AUTH_TYPE.Replace(HtaccessContent, ""); } } } private string GenerateReqiure() { StringBuilder sb = new StringBuilder(); sb.Append(REQUIRE_DIRECTIVE); if (ValidUser) { sb.Append(" ").Append(VALID_USER); } if (Users.Count > 0) { sb.Append(" ").Append(REQUIRE_USER); foreach (string user in Users) { sb.AppendFormat(" {0}", user); } } if (Groups.Count > 0) { sb.Append(" ").Append(REQUIRE_GROUP); foreach (string group in Groups) { sb.AppendFormat(" {0}", group); } } return sb.ToString(); } #region Implementation of IComparable public int CompareTo(object obj) { HtaccessFolder folder = obj as HtaccessFolder; if (folder != null) { return String.CompareOrdinal(this.Path.ToLower(), folder.Path.ToLower()); } return 0; } #endregion #region static helper members public static void GetDirectoriesWithHtaccess(string siteRootPath, string virtualRoot, string rootPath, string subPath, List<HtaccessFolder> folders) { if (Directory.Exists(subPath)) { if (HasHtaccessInDirectory(subPath)) { // Check this subPath is in folders list already bool included = folders.Any(x => String.Equals(subPath, x.ContentPath, StringComparison.OrdinalIgnoreCase)); // Add only if it is not included if (included == false) { // folders.Add(new HtaccessFolder { SiteRootPath = siteRootPath, Path = virtualRoot + RelativePath(rootPath, subPath), ContentPath = subPath }); } } // Process nested virtual directories if any Array.ForEach(Directory.GetDirectories(subPath), (x) => { GetDirectoriesWithHtaccess(siteRootPath, virtualRoot, rootPath, x, folders); }); } } private static bool HasHtaccessInDirectory(string path) { return File.Exists(System.IO.Path.Combine(path, HTACCESS_FILE)); } private static string RelativePath(string basePath, string subPath) { if (string.Equals(basePath, subPath, StringComparison.OrdinalIgnoreCase)) { return "\\"; } if (subPath.StartsWith(subPath, StringComparison.OrdinalIgnoreCase)) { return subPath.Substring(basePath.Length); } throw new ArgumentException("Paths do not have a common base"); } public static HtaccessFolder CreateHtaccessFolder(string siteRootPath, string folderPath) { HtaccessFolder folder = new HtaccessFolder { SiteRootPath = siteRootPath, Path = folderPath, ContentPath = System.IO.Path.Combine(siteRootPath, folderPath) }; folder.ReadHtaccess(); return folder; } public static HtaccessFolder CreateHttpdConfFolder(string path) { HtaccessFolder folder = new HtaccessFolder { ContentPath = path, Path = HTTPD_CONF_FILE }; folder.ReadHttpdConf(); return folder; } public static string ReadFile(string path) { string result = string.Empty; if (!File.Exists(path)) return result; using (StreamReader reader = new StreamReader(path)) { result = reader.ReadToEnd(); reader.Close(); } return result; } public static List<string> ReadLinesFile(string path) { List<string> lines = new List<string>(); string content = ReadFile(path); if (!string.IsNullOrEmpty(content)) { foreach (string line in Regex.Split(content, LinesSeparator)) { lines.Add(line); } } return lines; } public static void WriteFile(string path, string content) { // remove 'hidden' attribute FileAttributes fileAttributes = FileAttributes.Normal; if (File.Exists(path)) { fileAttributes = File.GetAttributes(path); if ((fileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden) { fileAttributes &= ~FileAttributes.Hidden; File.SetAttributes(path, fileAttributes); } } // check if folder exists string folder = System.IO.Path.GetDirectoryName(path); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); // write file using (StreamWriter writer = new StreamWriter(path)) { writer.WriteLine(content); writer.Close(); } // set 'hidden' attribute fileAttributes = File.GetAttributes(path); fileAttributes |= FileAttributes.Hidden; File.SetAttributes(path, fileAttributes); } public static void WriteLinesFile(string path, List<string> lines) { StringBuilder content = new StringBuilder(); foreach (string line in lines) { if (!string.IsNullOrEmpty(line)) { content.AppendLine(line); } } WriteFile(path, content.ToString()); } #endregion } public class HtaccessUser : WebUser { public const string ENCODING_TYPE_APACHE_MD5 = "Apache MD5"; public const string ENCODING_TYPE_UNIX_CRYPT = "Unix Crypt"; public const string ENCODING_TYPE_SHA1 = "SHA1"; public static readonly string[] ENCODING_TYPES = new string[] { ENCODING_TYPE_APACHE_MD5, ENCODING_TYPE_UNIX_CRYPT, ENCODING_TYPE_SHA1 }; private string authType; private string encType; private string realm; public string AuthType { get { if (string.IsNullOrEmpty(authType)) { if (!string.IsNullOrEmpty(Password)) { authType = HtaccessFolder.RE_DIGEST_PASSWORD.IsMatch(Password) ? HtaccessFolder.AUTH_TYPE_DIGEST : HtaccessFolder.AUTH_TYPE_BASIC; } } return authType; } set { authType = value; } } public string EncType { get { if (string.IsNullOrEmpty(encType)) { if (HtaccessFolder.AUTH_TYPE_BASIC != AuthType) { encType = string.Empty; } else if (Password.StartsWith("{SHA")) { encType = ENCODING_TYPE_SHA1; } else if (Password.StartsWith("$apr1$")) { encType = ENCODING_TYPE_APACHE_MD5; } else { encType = ENCODING_TYPE_UNIX_CRYPT; } } return encType; } set { encType = value; } } public string Realm { get { return realm; } set { realm = value; } } } }
/* ==================================================================== */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Xml; using System.Text; using System.Reflection; using Oranikle.Report.Engine; namespace Oranikle.ReportDesigner { /// <summary> /// DialogFilterOperator: puts up a dialog that lets a user pick a Filter Operator /// </summary> public class DialogFilterOperator : System.Windows.Forms.Form { private Oranikle.Studio.Controls.StyledButton bOK; private Oranikle.Studio.Controls.StyledButton bCancel; private System.Windows.Forms.Label lOp; private Oranikle.Studio.Controls.StyledComboBox cbOperator; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal DialogFilterOperator(string op) { // // Required for Windows Form Designer support // InitializeComponent(); if (op != null && op.Length > 0) cbOperator.Text = op; return; } public string Operator { get {return this.cbOperator.Text; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.bOK = new Oranikle.Studio.Controls.StyledButton(); this.bCancel = new Oranikle.Studio.Controls.StyledButton(); this.lOp = new System.Windows.Forms.Label(); this.cbOperator = new Oranikle.Studio.Controls.StyledComboBox(); this.SuspendLayout(); // // bOK // this.bOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.bOK.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bOK.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bOK.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bOK.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.bOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bOK.Font = new System.Drawing.Font("Arial", 9F); this.bOK.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bOK.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bOK.Location = new System.Drawing.Point(88, 168); this.bOK.Name = "bOK"; this.bOK.OverriddenSize = null; this.bOK.Size = new System.Drawing.Size(75, 23); this.bOK.TabIndex = 3; this.bOK.Text = "OK"; this.bOK.UseVisualStyleBackColor = true; // // bCancel // this.bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.bCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bCancel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bCancel.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bCancel.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bCancel.CausesValidation = false; this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bCancel.Font = new System.Drawing.Font("Arial", 9F); this.bCancel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bCancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCancel.Location = new System.Drawing.Point(176, 168); this.bCancel.Name = "bCancel"; this.bCancel.OverriddenSize = null; this.bCancel.Size = new System.Drawing.Size(75, 23); this.bCancel.TabIndex = 4; this.bCancel.Text = "Cancel"; this.bCancel.UseVisualStyleBackColor = true; // // lOp // this.lOp.Location = new System.Drawing.Point(8, 8); this.lOp.Name = "lOp"; this.lOp.Size = new System.Drawing.Size(112, 16); this.lOp.TabIndex = 13; this.lOp.Text = "Select Filter Operator"; // // cbOperator // this.cbOperator.AutoAdjustItemHeight = false; this.cbOperator.BorderColor = System.Drawing.Color.LightGray; this.cbOperator.ConvertEnterToTabForDialogs = false; this.cbOperator.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.cbOperator.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple; this.cbOperator.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cbOperator.Items.AddRange(new object[] { "Equal", "Like", "NotEqual", "GreaterThan", "GreaterThanOrEqual", "LessThan", "LessThanOrEqual", "TopN", "BottomN", "TopPercent", "BottomPercent", "In", "Between"}); this.cbOperator.Location = new System.Drawing.Point(120, 8); this.cbOperator.Name = "cbOperator"; this.cbOperator.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.cbOperator.SeparatorMargin = 1; this.cbOperator.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid; this.cbOperator.SeparatorWidth = 1; this.cbOperator.Size = new System.Drawing.Size(128, 150); this.cbOperator.TabIndex = 14; this.cbOperator.Text = "Equal"; this.cbOperator.Validating += new System.ComponentModel.CancelEventHandler(this.DialogFilterOperator_Validating); // // DialogFilterOperator // this.AcceptButton = this.bOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(241)))), ((int)(((byte)(249))))); this.CancelButton = this.bCancel; this.ClientSize = new System.Drawing.Size(256, 198); this.Controls.Add(this.cbOperator); this.Controls.Add(this.lOp); this.Controls.Add(this.bCancel); this.Controls.Add(this.bOK); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DialogFilterOperator"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Pick Filter Operator"; this.Validating += new System.ComponentModel.CancelEventHandler(this.DialogFilterOperator_Validating); this.ResumeLayout(false); } #endregion private void DialogFilterOperator_Validating(object sender, System.ComponentModel.CancelEventArgs e) { foreach (string op in cbOperator.Items) { if (op == cbOperator.Text) return; } MessageBox.Show(string.Format("Operator '{0}' must be in the operator list", cbOperator.Text), "Pick Filter Operator"); e.Cancel = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; //test case for delegate Equals method. namespace DelegateTest { delegate bool booldelegate(); public class DelegateEquals { object starkWork; public static int Main() { DelegateEquals DelegateEquals = new DelegateEquals(); TestLibrary.TestFramework.BeginTestCase("DelegateEquals"); if (DelegateEquals.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 = PosTest6() && retVal; retVal = PosTest7() && retVal; return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest1() { bool retVal = true; //Type,target, method, and invocation list TestLibrary.TestFramework.BeginScenario("PosTest1: Use one delegate object to instance the other delegate object,then use equals method to compare"); try { DelegateEquals delctor = new DelegateEquals(); delctor.starkWork = new booldelegate(new TestClass(1).StartWork_Bool); booldelegate workDelegate = (booldelegate)delctor.starkWork; if(GetCompareResult(workDelegate ,(booldelegate)delctor.starkWork)) { if (!workDelegate.Equals((booldelegate)delctor.starkWork)) { TestLibrary.TestFramework.LogError("001", "Equals method return error "); retVal = false; } } else { TestLibrary.TestFramework.LogError("002", "compare condition is error "); retVal = false; } workDelegate(); ((booldelegate)delctor.starkWork)(); } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); retVal = false; } return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Use the same instance's same instance method to create two different delegate ,then use equals method to compare"); try { DelegateEquals delctor = new DelegateEquals(); TestClass tcInstance = new TestClass(2); delctor.starkWork = new booldelegate(tcInstance.StartWork_Bool); booldelegate workDelegate = new booldelegate(tcInstance.StartWork_Bool); if (GetCompareResult(workDelegate, (booldelegate)delctor.starkWork)) { if (!workDelegate.Equals((booldelegate)delctor.starkWork)) { TestLibrary.TestFramework.LogError("004", "Equals method return error "); retVal = false; } } else { TestLibrary.TestFramework.LogError("005", "compare condition is error "); retVal = false; } workDelegate(); ((booldelegate)delctor.starkWork)(); } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Use the same type's same static method to create two delegate ,then use equals method to compare"); try { DelegateEquals delctor = new DelegateEquals(); delctor.starkWork = new booldelegate(TestClass.Working_Bool); booldelegate workDelegate = new booldelegate(TestClass.Working_Bool); if (GetCompareResult(workDelegate, (booldelegate)delctor.starkWork)) { if (!workDelegate.Equals((booldelegate)delctor.starkWork)) { TestLibrary.TestFramework.LogError("007", "Equals method return error "); retVal = false; } } else { TestLibrary.TestFramework.LogError("008", "compare condition is error "); retVal = false; } workDelegate(); ((booldelegate)delctor.starkWork)(); } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e); retVal = false; } return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Use the same type's different static method to create two delegate ,then use equals method to compare"); try { DelegateEquals delctor = new DelegateEquals(); delctor.starkWork = new booldelegate(TestClass.Working_Bool); booldelegate workDelegate = new booldelegate(TestClass.Completed_Bool); if (workDelegate.Equals((booldelegate)delctor.starkWork)) { TestLibrary.TestFramework.LogError("010", "Equals method return error "); retVal = false; } workDelegate(); ((booldelegate)delctor.starkWork)(); } catch (Exception e) { TestLibrary.TestFramework.LogError("011", "Unexpected exception: " + e); retVal = false; } return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Use the different type's same static method to create two delegate ,then use equals method to compare"); try { DelegateEquals delctor = new DelegateEquals(); booldelegate workDelegate = new booldelegate(TestClass.Completed_Bool); booldelegate workDelegate1 = new booldelegate(TestClass1.Completed_Bool); if (workDelegate.Equals(workDelegate1)) { TestLibrary.TestFramework.LogError("014", "Equals method return error "); retVal = false; } workDelegate(); workDelegate1(); } catch (Exception e) { TestLibrary.TestFramework.LogError("015", "Unexpected exception: " + e); retVal = false; } return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Use the different instance's same instance method to create two delegate ,then use equals method to compare"); try { DelegateEquals delctor = new DelegateEquals(); booldelegate workDelegate = new booldelegate(new TestClass(1).StartWork_Bool); booldelegate workDelegate1 = new booldelegate(new TestClass1(2).StartWork_Bool ); if (workDelegate.Equals(workDelegate1)) { TestLibrary.TestFramework.LogError("016", "Equals method return error "); retVal = false; } workDelegate(); workDelegate1(); } catch (Exception e) { TestLibrary.TestFramework.LogError("017", "Unexpected exception: " + e); retVal = false; } return retVal; } //compare delegate's Type,target, method, and invocation list //two delegates have common Type,target, method, and invocation list //return true.otherwise return false private bool GetCompareResult(booldelegate del1, booldelegate del2) { if (!del1.GetType().Equals(del2.GetType())) { return false; } if (!del1.Equals(del2)) { return false; } return true; } } //create testclass for provding test method and test target. class TestClass { private int id; public TestClass(int id) { this.id = id; } public bool StartWork_Bool() { TestLibrary.TestFramework.LogInformation("TestClass's StartWork_Bool method is running. id="+this.id); return true; } public static bool Working_Bool() { TestLibrary.TestFramework.LogInformation("TestClass's Working_Bool method is running ."); return true; } public static bool Completed_Bool() { TestLibrary.TestFramework.LogInformation("TestClass's Completed_Bool method is running ."); return true; } } class TestClass1 { private int id; public TestClass1(int id) { this.id = id; } public bool StartWork_Bool() { TestLibrary.TestFramework.LogInformation("TestClass1's StartWork_Bool method is running. id="+ this.id ); return true; } public static bool Working_Bool() { TestLibrary.TestFramework.LogInformation("TestClass1's Working_Bool method is running ."); return true; } public static bool Completed_Bool() { TestLibrary.TestFramework.LogInformation("TestClass1's Completed_Bool method is running ."); return true; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace SoftLogik.Win.Data { /// <summary> /// Strongly-typed collection for the Master class. /// </summary> [Serializable] public partial class MasterCollection : ActiveList<Master, MasterCollection> { public MasterCollection() {} } /// <summary> /// This is an ActiveRecord class which wraps the SLMaster table. /// </summary> [Serializable] public partial class Master : ActiveRecord<Master> { #region .ctors and Default Settings public Master() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Master(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Master(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Master(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("SLMaster", TableType.Table, DataService.GetInstance("WinSubSonicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarMasterID = new TableSchema.TableColumn(schema); colvarMasterID.ColumnName = "MasterID"; colvarMasterID.DataType = DbType.Int64; colvarMasterID.MaxLength = 0; colvarMasterID.AutoIncrement = true; colvarMasterID.IsNullable = false; colvarMasterID.IsPrimaryKey = true; colvarMasterID.IsForeignKey = false; colvarMasterID.IsReadOnly = false; colvarMasterID.DefaultSetting = @""; colvarMasterID.ForeignKeyTableName = ""; schema.Columns.Add(colvarMasterID); TableSchema.TableColumn colvarName = new TableSchema.TableColumn(schema); colvarName.ColumnName = "Name"; colvarName.DataType = DbType.String; colvarName.MaxLength = 50; colvarName.AutoIncrement = false; colvarName.IsNullable = true; colvarName.IsPrimaryKey = false; colvarName.IsForeignKey = false; colvarName.IsReadOnly = false; colvarName.DefaultSetting = @""; colvarName.ForeignKeyTableName = ""; schema.Columns.Add(colvarName); TableSchema.TableColumn colvarNote = new TableSchema.TableColumn(schema); colvarNote.ColumnName = "Note"; colvarNote.DataType = DbType.String; colvarNote.MaxLength = 500; colvarNote.AutoIncrement = false; colvarNote.IsNullable = true; colvarNote.IsPrimaryKey = false; colvarNote.IsForeignKey = false; colvarNote.IsReadOnly = false; colvarNote.DefaultSetting = @""; colvarNote.ForeignKeyTableName = ""; schema.Columns.Add(colvarNote); TableSchema.TableColumn colvarGroupID = new TableSchema.TableColumn(schema); colvarGroupID.ColumnName = "GroupID"; colvarGroupID.DataType = DbType.String; colvarGroupID.MaxLength = 5; colvarGroupID.AutoIncrement = false; colvarGroupID.IsNullable = true; colvarGroupID.IsPrimaryKey = false; colvarGroupID.IsForeignKey = true; colvarGroupID.IsReadOnly = false; colvarGroupID.DefaultSetting = @""; colvarGroupID.ForeignKeyTableName = "SLMasterGroup"; schema.Columns.Add(colvarGroupID); TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema); colvarCreatedOn.ColumnName = "CreatedOn"; colvarCreatedOn.DataType = DbType.DateTime; colvarCreatedOn.MaxLength = 0; colvarCreatedOn.AutoIncrement = false; colvarCreatedOn.IsNullable = true; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @""; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "ModifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = true; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @""; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "ModifiedBy"; colvarModifiedBy.DataType = DbType.String; colvarModifiedBy.MaxLength = 50; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = true; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = false; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @""; colvarModifiedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedBy); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["WinSubSonicProvider"].AddSchema("SLMaster",schema); } } #endregion #region Props [XmlAttribute("MasterID")] public long MasterID { get { return GetColumnValue<long>("MasterID"); } set { SetColumnValue("MasterID", value); } } [XmlAttribute("Name")] public string Name { get { return GetColumnValue<string>("Name"); } set { SetColumnValue("Name", value); } } [XmlAttribute("Note")] public string Note { get { return GetColumnValue<string>("Note"); } set { SetColumnValue("Note", value); } } [XmlAttribute("GroupID")] public string GroupID { get { return GetColumnValue<string>("GroupID"); } set { SetColumnValue("GroupID", value); } } [XmlAttribute("CreatedOn")] public DateTime? CreatedOn { get { return GetColumnValue<DateTime?>("CreatedOn"); } set { SetColumnValue("CreatedOn", value); } } [XmlAttribute("ModifiedOn")] public DateTime? ModifiedOn { get { return GetColumnValue<DateTime?>("ModifiedOn"); } set { SetColumnValue("ModifiedOn", value); } } [XmlAttribute("ModifiedBy")] public string ModifiedBy { get { return GetColumnValue<string>("ModifiedBy"); } set { SetColumnValue("ModifiedBy", value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a MasterGroup ActiveRecord object related to this Master /// /// </summary> public SoftLogik.Win.Data.MasterGroup MasterGroup { get { return SoftLogik.Win.Data.MasterGroup.FetchByID(this.GroupID); } set { SetColumnValue("GroupID", value.GroupID); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varName,string varNote,string varGroupID,DateTime? varCreatedOn,DateTime? varModifiedOn,string varModifiedBy) { Master item = new Master(); item.Name = varName; item.Note = varNote; item.GroupID = varGroupID; item.CreatedOn = varCreatedOn; item.ModifiedOn = varModifiedOn; item.ModifiedBy = varModifiedBy; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(long varMasterID,string varName,string varNote,string varGroupID,DateTime? varCreatedOn,DateTime? varModifiedOn,string varModifiedBy) { Master item = new Master(); item.MasterID = varMasterID; item.Name = varName; item.Note = varNote; item.GroupID = varGroupID; item.CreatedOn = varCreatedOn; item.ModifiedOn = varModifiedOn; item.ModifiedBy = varModifiedBy; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Columns Struct public struct Columns { public static string MasterID = @"MasterID"; public static string Name = @"Name"; public static string Note = @"Note"; public static string GroupID = @"GroupID"; public static string CreatedOn = @"CreatedOn"; public static string ModifiedOn = @"ModifiedOn"; public static string ModifiedBy = @"ModifiedBy"; } #endregion } }
/* Generated SBE (Simple Binary Encoding) message codec */ #pragma warning disable 1591 // disable warning on missing comments using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.PerfTests.Bench.SBE.FIX { public sealed partial class MassQuote { public const ushort BlockLength = (ushort)62; public const ushort TemplateId = (ushort)105; public const ushort SchemaId = (ushort)2; public const ushort Schema_Version = (ushort)0; public const string SematicType = "i"; private readonly MassQuote _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public MassQuote() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = Schema_Version; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(value); _limit = value; } } public const int QuoteReqIDId = 131; public static string QuoteReqIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte QuoteReqIDNullValue = (byte)0; public const byte QuoteReqIDMinValue = (byte)32; public const byte QuoteReqIDMaxValue = (byte)126; public const int QuoteReqIDLength = 23; public byte GetQuoteReqID(int index) { if (index < 0 || index >= 23) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 0 + (index * 1)); } public void SetQuoteReqID(int index, byte value) { if (index < 0 || index >= 23) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 0 + (index * 1), value); } public const string QuoteReqIDCharacterEncoding = "UTF-8"; public int GetQuoteReqID(byte[] dst, int dstOffset) { const int length = 23; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 0, dst, dstOffset, length); return length; } public void SetQuoteReqID(byte[] src, int srcOffset) { const int length = 23; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 0, src, srcOffset, length); } public const int QuoteIDId = 117; public static string QuoteIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte QuoteIDNullValue = (byte)0; public const byte QuoteIDMinValue = (byte)32; public const byte QuoteIDMaxValue = (byte)126; public const int QuoteIDLength = 10; public byte GetQuoteID(int index) { if (index < 0 || index >= 10) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 23 + (index * 1)); } public void SetQuoteID(int index, byte value) { if (index < 0 || index >= 10) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 23 + (index * 1), value); } public const string QuoteIDCharacterEncoding = "UTF-8"; public int GetQuoteID(byte[] dst, int dstOffset) { const int length = 10; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 23, dst, dstOffset, length); return length; } public void SetQuoteID(byte[] src, int srcOffset) { const int length = 10; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 23, src, srcOffset, length); } public const int MMAccountId = 9771; public static string MMAccountMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte MMAccountNullValue = (byte)0; public const byte MMAccountMinValue = (byte)32; public const byte MMAccountMaxValue = (byte)126; public const int MMAccountLength = 12; public byte GetMMAccount(int index) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 33 + (index * 1)); } public void SetMMAccount(int index, byte value) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 33 + (index * 1), value); } public const string MMAccountCharacterEncoding = "UTF-8"; public int GetMMAccount(byte[] dst, int dstOffset) { const int length = 12; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 33, dst, dstOffset, length); return length; } public void SetMMAccount(byte[] src, int srcOffset) { const int length = 12; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 33, src, srcOffset, length); } public const int ManualOrderIndicatorId = 1028; public static string ManualOrderIndicatorMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public BooleanType ManualOrderIndicator { get { return (BooleanType)_buffer.Uint8Get(_offset + 45); } set { _buffer.Uint8Put(_offset + 45, (byte)value); } } public const int CustOrderHandlingInstId = 1031; public static string CustOrderHandlingInstMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "char"; } return ""; } public CustOrderHandlingInst CustOrderHandlingInst { get { return (CustOrderHandlingInst)_buffer.CharGet(_offset + 46); } set { _buffer.CharPut(_offset + 46, (byte)value); } } public const int CustomerOrFirmId = 204; public static string CustomerOrFirmMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public CustomerOrFirm CustomerOrFirm { get { return (CustomerOrFirm)_buffer.Uint8Get(_offset + 47); } set { _buffer.Uint8Put(_offset + 47, (byte)value); } } public const int SelfMatchPreventionIDId = 7928; public static string SelfMatchPreventionIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SelfMatchPreventionIDNullValue = (byte)0; public const byte SelfMatchPreventionIDMinValue = (byte)32; public const byte SelfMatchPreventionIDMaxValue = (byte)126; public const int SelfMatchPreventionIDLength = 12; public byte GetSelfMatchPreventionID(int index) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 48 + (index * 1)); } public void SetSelfMatchPreventionID(int index, byte value) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 48 + (index * 1), value); } public const string SelfMatchPreventionIDCharacterEncoding = "UTF-8"; public int GetSelfMatchPreventionID(byte[] dst, int dstOffset) { const int length = 12; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 48, dst, dstOffset, length); return length; } public void SetSelfMatchPreventionID(byte[] src, int srcOffset) { const int length = 12; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 48, src, srcOffset, length); } public const int CtiCodeId = 9702; public static string CtiCodeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public CtiCode CtiCode { get { return (CtiCode)_buffer.CharGet(_offset + 60); } set { _buffer.CharPut(_offset + 60, (byte)value); } } public const int MMProtectionResetId = 9773; public static string MMProtectionResetMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public MMProtectionReset MMProtectionReset { get { return (MMProtectionReset)_buffer.CharGet(_offset + 61); } set { _buffer.CharPut(_offset + 61, (byte)value); } } private readonly QuoteSetsGroup _quoteSets = new QuoteSetsGroup(); public const long QuoteSetsId = 296; public QuoteSetsGroup QuoteSets { get { _quoteSets.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _quoteSets; } } public QuoteSetsGroup QuoteSetsCount(int count) { _quoteSets.WrapForEncode(_parentMessage, _buffer, count); return _quoteSets; } public sealed partial class QuoteSetsGroup { private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding(); private MassQuote _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(MassQuote parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _blockLength = _dimensions.BlockLength; _count = _dimensions.NumInGroup; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + SbeHeaderSize; } public void WrapForEncode(MassQuote parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.BlockLength = (ushort)24; _dimensions.NumInGroup = (byte)count; _index = -1; _count = count; _blockLength = 24; parentMessage.Limit = parentMessage.Limit + SbeHeaderSize; } public const int SbeBlockLength = 24; public const int SbeHeaderSize = 3; public int ActingBlockLength { get { return _blockLength; } } public int Count { get { return _count; } } public bool HasNext { get { return (_index + 1) < _count; } } public QuoteSetsGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int QuoteSetIDId = 302; public static string QuoteSetIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte QuoteSetIDNullValue = (byte)0; public const byte QuoteSetIDMinValue = (byte)32; public const byte QuoteSetIDMaxValue = (byte)126; public const int QuoteSetIDLength = 3; public byte GetQuoteSetID(int index) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 0 + (index * 1)); } public void SetQuoteSetID(int index, byte value) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 0 + (index * 1), value); } public const string QuoteSetIDCharacterEncoding = "UTF-8"; public int GetQuoteSetID(byte[] dst, int dstOffset) { const int length = 3; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 0, dst, dstOffset, length); return length; } public void SetQuoteSetID(byte[] src, int srcOffset) { const int length = 3; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 0, src, srcOffset, length); } public const int UnderlyingSecurityDescId = 307; public static string UnderlyingSecurityDescMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte UnderlyingSecurityDescNullValue = (byte)0; public const byte UnderlyingSecurityDescMinValue = (byte)32; public const byte UnderlyingSecurityDescMaxValue = (byte)126; public const int UnderlyingSecurityDescLength = 20; public byte GetUnderlyingSecurityDesc(int index) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 3 + (index * 1)); } public void SetUnderlyingSecurityDesc(int index, byte value) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 3 + (index * 1), value); } public const string UnderlyingSecurityDescCharacterEncoding = "UTF-8"; public int GetUnderlyingSecurityDesc(byte[] dst, int dstOffset) { const int length = 20; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 3, dst, dstOffset, length); return length; } public void SetUnderlyingSecurityDesc(byte[] src, int srcOffset) { const int length = 20; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 3, src, srcOffset, length); } public const int TotQuoteEntriesId = 304; public static string TotQuoteEntriesMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const byte TotQuoteEntriesNullValue = (byte)255; public const byte TotQuoteEntriesMinValue = (byte)0; public const byte TotQuoteEntriesMaxValue = (byte)254; public byte TotQuoteEntries { get { return _buffer.Uint8Get(_offset + 23); } set { _buffer.Uint8Put(_offset + 23, value); } } private readonly QuoteEntriesGroup _quoteEntries = new QuoteEntriesGroup(); public const long QuoteEntriesId = 295; public QuoteEntriesGroup QuoteEntries { get { _quoteEntries.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _quoteEntries; } } public QuoteEntriesGroup QuoteEntriesCount(int count) { _quoteEntries.WrapForEncode(_parentMessage, _buffer, count); return _quoteEntries; } public sealed partial class QuoteEntriesGroup { private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding(); private MassQuote _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(MassQuote parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _blockLength = _dimensions.BlockLength; _count = _dimensions.NumInGroup; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + SbeHeaderSize; } public void WrapForEncode(MassQuote parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.BlockLength = (ushort)90; _dimensions.NumInGroup = (byte)count; _index = -1; _count = count; _blockLength = 90; parentMessage.Limit = parentMessage.Limit + SbeHeaderSize; } public const int SbeBlockLength = 90; public const int SbeHeaderSize = 3; public int ActingBlockLength { get { return _blockLength; } } public int Count { get { return _count; } } public bool HasNext { get { return (_index + 1) < _count; } } public QuoteEntriesGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int QuoteEntryIDId = 299; public static string QuoteEntryIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte QuoteEntryIDNullValue = (byte)0; public const byte QuoteEntryIDMinValue = (byte)32; public const byte QuoteEntryIDMaxValue = (byte)126; public const int QuoteEntryIDLength = 10; public byte GetQuoteEntryID(int index) { if (index < 0 || index >= 10) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 0 + (index * 1)); } public void SetQuoteEntryID(int index, byte value) { if (index < 0 || index >= 10) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 0 + (index * 1), value); } public const string QuoteEntryIDCharacterEncoding = "UTF-8"; public int GetQuoteEntryID(byte[] dst, int dstOffset) { const int length = 10; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 0, dst, dstOffset, length); return length; } public void SetQuoteEntryID(byte[] src, int srcOffset) { const int length = 10; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 0, src, srcOffset, length); } public const int SymbolId = 55; public static string SymbolMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SymbolNullValue = (byte)0; public const byte SymbolMinValue = (byte)32; public const byte SymbolMaxValue = (byte)126; public const int SymbolLength = 6; public byte GetSymbol(int index) { if (index < 0 || index >= 6) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 10 + (index * 1)); } public void SetSymbol(int index, byte value) { if (index < 0 || index >= 6) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 10 + (index * 1), value); } public const string SymbolCharacterEncoding = "UTF-8"; public int GetSymbol(byte[] dst, int dstOffset) { const int length = 6; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 10, dst, dstOffset, length); return length; } public void SetSymbol(byte[] src, int srcOffset) { const int length = 6; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 10, src, srcOffset, length); } public const int SecurityDescId = 107; public static string SecurityDescMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SecurityDescNullValue = (byte)0; public const byte SecurityDescMinValue = (byte)32; public const byte SecurityDescMaxValue = (byte)126; public const int SecurityDescLength = 20; public byte GetSecurityDesc(int index) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 16 + (index * 1)); } public void SetSecurityDesc(int index, byte value) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 16 + (index * 1), value); } public const string SecurityDescCharacterEncoding = "UTF-8"; public int GetSecurityDesc(byte[] dst, int dstOffset) { const int length = 20; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 16, dst, dstOffset, length); return length; } public void SetSecurityDesc(byte[] src, int srcOffset) { const int length = 20; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 16, src, srcOffset, length); } public const int SecurityTypeId = 167; public static string SecurityTypeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SecurityTypeNullValue = (byte)0; public const byte SecurityTypeMinValue = (byte)32; public const byte SecurityTypeMaxValue = (byte)126; public const int SecurityTypeLength = 3; public byte GetSecurityType(int index) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 36 + (index * 1)); } public void SetSecurityType(int index, byte value) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 36 + (index * 1), value); } public const string SecurityTypeCharacterEncoding = "UTF-8"; public int GetSecurityType(byte[] dst, int dstOffset) { const int length = 3; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 36, dst, dstOffset, length); return length; } public void SetSecurityType(byte[] src, int srcOffset) { const int length = 3; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 36, src, srcOffset, length); } public const int SecurityIDId = 48; public static string SecurityIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const long SecurityIDNullValue = -9223372036854775808L; public const long SecurityIDMinValue = -9223372036854775807L; public const long SecurityIDMaxValue = 9223372036854775807L; public long SecurityID { get { return _buffer.Int64GetLittleEndian(_offset + 39); } set { _buffer.Int64PutLittleEndian(_offset + 39, value); } } public const int SecurityIDSourceId = 22; public static string SecurityIDSourceMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public SecurityIDSource SecurityIDSource { get { return (SecurityIDSource)_buffer.CharGet(_offset + 47); } set { _buffer.CharPut(_offset + 47, (byte)value); } } public const int TransactTimeId = 60; public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "UTCTimestamp"; } return ""; } public const ulong TransactTimeNullValue = 0xffffffffffffffffUL; public const ulong TransactTimeMinValue = 0x0UL; public const ulong TransactTimeMaxValue = 0xfffffffffffffffeUL; public ulong TransactTime { get { return _buffer.Uint64GetLittleEndian(_offset + 48); } set { _buffer.Uint64PutLittleEndian(_offset + 48, value); } } public const int BidPxId = 132; public static string BidPxMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "Price"; } return ""; } private readonly OptionalPrice _bidPx = new OptionalPrice(); public OptionalPrice BidPx { get { _bidPx.Wrap(_buffer, _offset + 56, _actingVersion); return _bidPx; } } public const int BidSizeId = 134; public static string BidSizeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const long BidSizeNullValue = -9223372036854775808L; public const long BidSizeMinValue = -9223372036854775807L; public const long BidSizeMaxValue = 9223372036854775807L; public long BidSize { get { return _buffer.Int64GetLittleEndian(_offset + 65); } set { _buffer.Int64PutLittleEndian(_offset + 65, value); } } public const int OfferPxId = 133; public static string OfferPxMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "Price"; } return ""; } private readonly OptionalPrice _offerPx = new OptionalPrice(); public OptionalPrice OfferPx { get { _offerPx.Wrap(_buffer, _offset + 73, _actingVersion); return _offerPx; } } public const int OfferSizeId = 135; public static string OfferSizeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const long OfferSizeNullValue = -9223372036854775808L; public const long OfferSizeMinValue = -9223372036854775807L; public const long OfferSizeMaxValue = 9223372036854775807L; public long OfferSize { get { return _buffer.Int64GetLittleEndian(_offset + 82); } set { _buffer.Int64PutLittleEndian(_offset + 82, value); } } } } } }
namespace AngleSharp.Core.Tests.Html { using AngleSharp.Html.Dom; using NUnit.Framework; /// <summary> /// Tests generated according to the W3C-Test.org page: /// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-validity-rangeOverflow.html /// </summary> [TestFixture] public class ValidityRangeOverflowTests { [Test] public void TestRangeoverflowInputDatetime1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", ""); element.Value = "2000-01-01T12:00:00Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T12:00:00Z"); element.Value = ""; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01 12:00:00Z"); element.Value = "2001-01-01T12:00:00Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T12:00:00Z"); element.Value = "2000-01-01T11:00:00Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T23:59:59Z"); element.Value = "2001-01-01T24:00:00Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime6() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "1970-01-01T12:00Z"); element.Value = "80-01-01T12:00Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime7() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T12:00:00Z"); element.Value = "2001-01-01T13:00:00Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime8() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T12:00:00.1Z"); element.Value = "2000-01-01T12:00:00.2Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime9() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T12:00:00.01Z"); element.Value = "2000-01-01T12:00:00.02Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime10() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T12:00:00.001Z"); element.Value = "2000-01-01T12:00:00.002Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime11() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T12:00:00"); element.Value = "9999-01-01T12:00:00"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDatetime12() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "8592-01-01T02:09+02:09"); element.Value = "8593-01-01T02:09+02:09"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", ""); element.Value = "2000-01-01"; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01"); element.Value = ""; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000/01/01"); element.Value = "2002-01-01"; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01"); element.Value = "2000-2-2"; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "987-01-01"); element.Value = "988-01-01"; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate6() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01"); element.Value = "2000-13-01"; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate7() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01"); element.Value = "2000-02-30"; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate8() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-12-01"); element.Value = "2000-01-01"; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate9() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-12-01"); element.Value = "2001-01-01"; Assert.AreEqual("date", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputDate10() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "9999-01-01"); element.Value = "9999-01-02"; Assert.AreEqual("date", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputMonth1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", ""); element.Value = "2000-01"; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputMonth2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01"); element.Value = ""; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputMonth3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000/01"); element.Value = "2001-02"; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputMonth4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01"); element.Value = "2000-1"; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputMonth5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "987-01"); element.Value = "988-01"; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputMonth6() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01"); element.Value = "2000-13"; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputMonth7() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-12"); element.Value = "2000-01"; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputMonth8() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01"); element.Value = "2000-12"; Assert.AreEqual("month", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputMonth9() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "9999-01"); element.Value = "9999-02"; Assert.AreEqual("month", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", ""); element.Value = "2000-W01"; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-W01"); element.Value = ""; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000/W01"); element.Value = "2001-W02"; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-W01"); element.Value = "2000-W2"; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-W01"); element.Value = "2000-w02"; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek6() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "987-W01"); element.Value = "988-W01"; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek7() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-W01"); element.Value = "2000-W57"; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek8() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-W12"); element.Value = "2000-W01"; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek9() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-W01"); element.Value = "2000-W12"; Assert.AreEqual("week", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputWeek10() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "9999-W01"); element.Value = "9999-W02"; Assert.AreEqual("week", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", ""); element.Value = "12:00:00"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00"); element.Value = ""; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12.00.00"); element.Value = "12:00:01"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00"); element.Value = "12.00.01"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "23:59:59"); element.Value = "24:00:00"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime6() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "23:59:59"); element.Value = "23:60:00"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime7() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "23:59:59"); element.Value = "23:59:60"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime8() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "13:00:00"); element.Value = "12:00:00"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime9() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00"); element.Value = "13"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime10() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00"); element.Value = "12:00:02"; Assert.AreEqual("time", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime11() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00.1"); element.Value = "12:00:00.2"; Assert.AreEqual("time", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime12() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00.01"); element.Value = "12:00:00.02"; Assert.AreEqual("time", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime13() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00.001"); element.Value = "12:00:00.002"; Assert.AreEqual("time", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputTime14() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00"); element.Value = "12:01"; Assert.AreEqual("time", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputNumber1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", ""); element.Value = "10"; Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputNumber2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "5"); element.Value = ""; Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputNumber3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "5"); element.Value = "4"; Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputNumber4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "-5.5"); element.Value = "-5.6"; Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputNumber5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "-0"); element.Value = "0"; Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputNumber6() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "5"); element.Value = "1abc"; Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputNumber7() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "5"); element.Value = "6"; Assert.AreEqual("number", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] [SetCulture("ru")] public void TestRangeoverflowInputNumber8InRussia() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "-5.5"); element.Value = "-5.4"; Assert.AreEqual("number", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputNumber8() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "-5.5"); element.Value = "-5.4"; Assert.AreEqual("number", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } [Test] public void TestRangeoverflowInputNumber9() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "-5e-1"); element.Value = "5e+2"; Assert.AreEqual("number", element.Type); Assert.AreEqual(true, element.Validity.IsRangeOverflow); } } }
// // DatabaseTest.cs // // Copyright (c) 2017 Couchbase, Inc 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. // using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Couchbase.Lite; using FluentAssertions; using LiteCore.Interop; #if !WINDOWS_UWP using Xunit; using Xunit.Abstractions; #else using Fact = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; #endif namespace LiteCore.Tests { #if WINDOWS_UWP [Microsoft.VisualStudio.TestTools.UnitTesting.TestClass] #endif public unsafe class DatabaseTest : Test { #if !WINDOWS_UWP public DatabaseTest(ITestOutputHelper output) : base(output) { } #endif /// <summary> /// File exists /// </summary> public static readonly int EEXIST = 17; private void SetupAllDocs() { CreateNumberedDocs(99); // Add a deleted doc to make sure it's skipped by default: CreateRev("doc-005DEL", RevID, FLSlice.Null, C4RevisionFlags.Deleted); } private void AssertMessage(C4ErrorDomain domain, int code, string expected) { var msg = Native.c4error_getMessage(new C4Error(domain, code)); msg.Should().Be(expected, "because the error message should match the code"); } [Fact] public void TestAllDocs() { RunTestVariants(() => { SetupAllDocs(); Native.c4db_getDocumentCount(Db).Should().Be(99UL, "because there are 99 non-deleted documents"); // No start or end ID: var options = C4EnumeratorOptions.Default; options.flags &= ~C4EnumeratorFlags.IncludeBodies; var e = (C4DocEnumerator *)LiteCoreBridge.Check(err => { var localOpts = options; return Native.c4db_enumerateAllDocs(Db, &localOpts, err); }); int i = 1; C4Error error; while(Native.c4enum_next(e, &error)) { var doc = (C4Document *)LiteCoreBridge.Check(err => Native.c4enum_getDocument(e, err)); var docID = $"doc-{i:D3}"; doc->docID.CreateString().Should().Be(docID, "because the doc should have the correct doc ID"); doc->revID.Equals(RevID).Should().BeTrue("because the doc should have the current revID"); doc->selectedRev.revID.Equals(RevID).Should().BeTrue("because the selected rev should have the correct rev ID"); doc->selectedRev.sequence.Should().Be((ulong)i, "because the sequences should come in order"); Native.c4doc_hasRevisionBody(doc).Should().BeFalse("because the body is not loaded yet"); LiteCoreBridge.Check(err => Native.c4doc_loadRevisionBody(doc, err)); NativeRaw.c4doc_getRevisionBody(doc).Equals(FleeceBody).Should().BeTrue("because the loaded body should be correct"); C4DocumentInfo info; Native.c4enum_getDocumentInfo(e, &info).Should().BeTrue("because otherwise the doc info load failed"); info.docID.CreateString().Should().Be(docID, "because the doc info should have the correct doc ID"); info.revID.Equals(RevID).Should().BeTrue("because the doc info should have the correct rev ID"); info.bodySize.Should().BeGreaterOrEqualTo(11).And .BeLessOrEqualTo(40, "because the body should have some data"); Native.c4doc_release(doc); i++; } Native.c4enum_free(e); i.Should().Be(100); }); } [Fact] public void TestAllDocsInfo() { RunTestVariants(() => { SetupAllDocs(); var options = C4EnumeratorOptions.Default; var e = (C4DocEnumerator *)LiteCoreBridge.Check(err => { var localOpts = options; return Native.c4db_enumerateAllDocs(Db, &localOpts, err); }); int i = 1; C4Error error; while(Native.c4enum_next(e, &error)) { C4DocumentInfo doc; Native.c4enum_getDocumentInfo(e, &doc).Should().BeTrue("because otherwise getting the doc info failed"); var docID = $"doc-{i:D3}"; doc.docID.CreateString().Should().Be(docID, "because the doc info should have the correct doc ID"); doc.revID.Equals(RevID).Should().BeTrue("because the doc info should have the correct rev ID"); doc.sequence.Should().Be((ulong)i, "because the doc info should have the correct sequence"); doc.flags.Should().Be(C4DocumentFlags.DocExists, "because the doc info should have the correct flags"); doc.bodySize.Should().BeGreaterOrEqualTo(11).And .BeLessOrEqualTo(40, "because the body should have some data"); i++; } Native.c4enum_free(e); error.code.Should().Be(0, "because otherwise an error occurred somewhere"); i.Should().Be(100, "because all docs should be iterated, even deleted ones"); }); } [Fact] public void TestCancelExpire() { RunTestVariants(() => { var docID = "expire_me"; CreateRev(docID, RevID, FleeceBody); var expire = Native.c4_now() + 2000; C4Error err; Native.c4doc_setExpiration(Db, docID, expire, &err).Should().BeTrue(); Native.c4doc_getExpiration(Db, docID, null).Should().Be(expire); Native.c4db_nextDocExpiration(Db).Should().Be(expire); Native.c4doc_setExpiration(Db, docID, 0, &err).Should().BeTrue(); Native.c4doc_getExpiration(Db, docID, null).Should().Be(0); Native.c4db_nextDocExpiration(Db).Should().Be(0); }); } [Fact] public void TestChanges() { RunTestVariants(() => { CreateNumberedDocs(99); // Since start: var options = C4EnumeratorOptions.Default; options.flags &= ~C4EnumeratorFlags.IncludeBodies; var e = (C4DocEnumerator *)LiteCoreBridge.Check(err => { var localOpts = options; return Native.c4db_enumerateChanges(Db, 0, &localOpts, err); }); var seq = 1UL; C4Document* doc; C4Error error; while(null != (doc = c4enum_nextDocument(e, &error))) { doc->selectedRev.sequence.Should().Be(seq, "because the sequence numbers should be ascending"); var docID = $"doc-{seq:D3}"; doc->docID.CreateString().Should().Be(docID, "because the doc should have the correct doc ID"); Native.c4doc_release(doc); seq++; } Native.c4enum_free(e); // Since 6: e = (C4DocEnumerator *)LiteCoreBridge.Check(err => { var localOpts = options; return Native.c4db_enumerateChanges(Db, 6, &localOpts, err); }); seq = 7; while(null != (doc = c4enum_nextDocument(e, &error))) { doc->selectedRev.sequence.Should().Be(seq, "because the sequence numbers should be ascending"); var docID = $"doc-{seq:D3}"; doc->docID.CreateString().Should().Be(docID, "because the doc should have the correct doc ID"); Native.c4doc_release(doc); seq++; } Native.c4enum_free(e); seq.Should().Be(100UL, "because that is the highest sequence in the DB"); }); } [Fact] public void TestCreateRawDoc() { RunTestVariants(() => { var key = FLSlice.Constant("key"); var meta = FLSlice.Constant("meta"); LiteCoreBridge.Check(err => Native.c4db_beginTransaction(Db, err)); LiteCoreBridge.Check(err => NativeRaw.c4raw_put(Db, FLSlice.Constant("test"), key, meta, FleeceBody, err)); LiteCoreBridge.Check(err => Native.c4db_endTransaction(Db, true, err)); var doc = (C4RawDocument *)LiteCoreBridge.Check(err => NativeRaw.c4raw_get(Db, FLSlice.Constant("test"), key, err)); doc->key.Equals(key).Should().BeTrue("because the key should not change"); doc->meta.Equals(meta).Should().BeTrue("because the meta should not change"); doc->body.Equals(FleeceBody).Should().BeTrue("because the body should not change"); Native.c4raw_free(doc); // Nonexistent: C4Error error; ((long)Native.c4raw_get(Db, "test", "bogus", &error)).Should().Be(0, "because the document does not exist"); error.domain.Should().Be(C4ErrorDomain.LiteCoreDomain, "because that is the correct domain"); error.code.Should().Be((int)C4ErrorCode.NotFound, "because that is the correct error code"); }); } [Fact] public void TestDatabaseBlobStore() { RunTestVariants(() => { LiteCoreBridge.Check(err => Native.c4db_getBlobStore(Db, err)); }); } [Fact] public void TestDatabaseCompact() { RunTestVariants(() => { var doc1ID = FLSlice.Constant("doc001"); var doc2ID = FLSlice.Constant("doc002"); var doc3ID = FLSlice.Constant("doc003"); var content1 = "This is the first attachment"; var content2 = "This is the second attachment"; var atts = new List<string>(); C4BlobKey key1, key2; atts.Add(content1); LiteCoreBridge.Check(err => Native.c4db_beginTransaction(Db, err)); try { key1 = AddDocWithAttachments(doc1ID, atts, "text/plain")[0]; atts.Clear(); atts.Add(content2); key2 = AddDocWithAttachments(doc2ID, atts, "text/plain")[0]; AddDocWithAttachments(doc3ID, atts, "text/plain"); } finally { LiteCoreBridge.Check(err => Native.c4db_endTransaction(Db, true, err)); } var store = (C4BlobStore*) LiteCoreBridge.Check(err => Native.c4db_getBlobStore(Db, err)); LiteCoreBridge.Check(err => Native.c4db_maintenance(Db, C4MaintenanceType.Compact, err)); Native.c4blob_getSize(store, key1).Should() .BeGreaterThan(0, "because the attachment should survive the first compact"); Native.c4blob_getSize(store, key2).Should() .BeGreaterThan(0, "because the attachment should survive the first compact"); CreateRev("doc001", Rev2ID, FLSlice.Null, C4RevisionFlags.Deleted); LiteCoreBridge.Check(err => Native.c4db_maintenance(Db, C4MaintenanceType.Compact, err)); Native.c4blob_getSize(store, key1).Should().Be(-1, "because the attachment should be collected in the second compact"); Native.c4blob_getSize(store, key2).Should() .BeGreaterThan(0, "because the attachment should survive the second compact"); CreateRev("doc002", Rev2ID, FLSlice.Null, C4RevisionFlags.Deleted); LiteCoreBridge.Check(err => Native.c4db_maintenance(Db, C4MaintenanceType.Compact, err)); Native.c4blob_getSize(store, key1).Should().Be(-1, "because the attachment should still be gone in the third compact"); Native.c4blob_getSize(store, key2).Should() .BeGreaterThan(0, "because the attachment should survive the third compact"); CreateRev("doc003", Rev2ID, FLSlice.Null, C4RevisionFlags.Deleted); LiteCoreBridge.Check(err => Native.c4db_maintenance(Db, C4MaintenanceType.Compact, err)); Native.c4blob_getSize(store, key1).Should().Be(-1, "because the attachment should still be gone in the fourth compact"); Native.c4blob_getSize(store, key2).Should().Be(-1, "because the attachment should be collected in the fourth compact"); }); } [Fact] public void TestDeletionLock() { RunTestVariants(() => { C4Error err; Native.c4db_deleteNamed(DBName, TestDir, &err).Should().BeFalse("because the database is open"); err.domain.Should().Be(C4ErrorDomain.LiteCoreDomain); err.code.Should().Be((int) C4ErrorCode.Busy); var equivalentPath = TestDir + Path.DirectorySeparatorChar; Native.c4db_deleteNamed(DBName, equivalentPath, &err).Should().BeFalse("because the database is open"); err.domain.Should().Be(C4ErrorDomain.LiteCoreDomain); err.code.Should().Be((int) C4ErrorCode.Busy); }); } [Fact] public void TestDatabaseInfo() { RunTestVariants(() => { Native.c4db_getDocumentCount(Db).Should().Be(0, "because the database is empty"); Native.c4db_getLastSequence(Db).Should().Be(0, "because the database is empty"); var publicID = new C4UUID(); var privateID = new C4UUID(); C4Error err; var uuidSuccess = Native.c4db_getUUIDs(Db, &publicID, &privateID, &err); if (!uuidSuccess) { throw CouchbaseException.Create(err); } var p1 = publicID; var p2 = privateID; var match = true; for (int i = 0; i < C4UUID.Size; i++) { if (publicID.bytes[i] != privateID.bytes[i]) { match = false; break; } } match.Should().BeFalse("because public UUID and private UUID should differ"); (p1.bytes[6] & 0xF0).Should().Be(0x40, "because otherwise the UUID is non-conformant"); (p1.bytes[8] & 0xC0).Should().Be(0x80, "because otherwise the UUID is non-conformant"); (p2.bytes[6] & 0xF0).Should().Be(0x40, "because otherwise the UUID is non-conformant"); (p2.bytes[8] & 0xC0).Should().Be(0x80, "because otherwise the UUID is non-conformant"); // Make sure the UUIDs are persistent ReopenDB(); var publicID2 = new C4UUID(); var privateID2 = new C4UUID(); uuidSuccess = Native.c4db_getUUIDs(Db, &publicID2, &privateID2, &err); if (!uuidSuccess) { throw CouchbaseException.Create(err); } for (int i = 0; i < C4UUID.Size; i++) { publicID2.bytes[i].Should().Be(publicID.bytes[i]); privateID2.bytes[i].Should().Be(privateID.bytes[i]); } }); } [Fact] public void TestErrorMessages() { var msg = Native.c4error_getMessage(new C4Error(C4ErrorDomain.LiteCoreDomain, 0)); msg.Should().BeNull("because there was no error"); AssertMessage(C4ErrorDomain.SQLiteDomain, (int)SQLiteStatus.Corrupt, "database disk image is malformed"); AssertMessage(C4ErrorDomain.LiteCoreDomain, (int)C4ErrorCode.InvalidParameter, "invalid parameter"); AssertMessage(C4ErrorDomain.LiteCoreDomain, (int)C4ErrorCode.TransactionNotClosed, "transaction not closed"); AssertMessage(C4ErrorDomain.SQLiteDomain, -1234, "unknown error (-1234)"); AssertMessage((C4ErrorDomain)Byte.MaxValue, -1234, "invalid C4Error (unknown domain)"); } [Fact] public void TestExpired() { RunTestVariants(() => { C4Error err; Native.c4db_nextDocExpiration(Db).Should().Be(0L); var docID = "expire_me"; CreateRev(docID, RevID, FleeceBody); var expire = Native.c4_now() + 1000; //1000ms = 1 sec; Native.c4doc_setExpiration(Db, docID, expire, &err).Should() .BeTrue("because otherwise the 1 second expiration failed to set"); expire = Native.c4_now() + 2000; Native.c4doc_setExpiration(Db, docID, expire, &err).Should() .BeTrue("because otherwise the 2 second expiration failed to set"); Native.c4doc_setExpiration(Db, docID, expire, &err).Should() .BeTrue("because setting to the same time twice should also work"); var docID2 = "expire_me_too"; CreateRev(docID2, RevID, FleeceBody); Native.c4doc_setExpiration(Db, docID2, expire, &err).Should() .BeTrue("because otherwise the 2 second expiration failed to set"); var docID3 = "dont_expire_me"; CreateRev(docID3, RevID, FleeceBody); var docID4 = "expire_me_later"; CreateRev(docID4, RevID, FleeceBody); Native.c4doc_setExpiration(Db, docID4, expire + 100_000, &err).Should() .BeTrue("because otherwise the 100 second expiration failed to set"); Native.c4doc_setExpiration(Db, "nonexistent", expire + 50_000, &err).Should() .BeFalse("because the document is nonexistent"); err.domain.Should().Be(C4ErrorDomain.LiteCoreDomain); err.code.Should().Be((int) C4ErrorCode.NotFound); Native.c4doc_getExpiration(Db, docID, null).Should().Be(expire); Native.c4doc_getExpiration(Db, docID2, null).Should().Be(expire); Native.c4doc_getExpiration(Db, docID3, null).Should().Be(0L); Native.c4doc_getExpiration(Db, docID4, null).Should().Be(expire + 100_000); Native.c4doc_getExpiration(Db, "nonexistent", null).Should().Be(0L); Native.c4db_nextDocExpiration(Db).Should().Be(expire); WriteLine("--- Wait till expiration time..."); Thread.Sleep(TimeSpan.FromSeconds(2)); Native.c4_now().Should().BeGreaterOrEqualTo(expire); }); } [Fact] public void TestExpiredMultipleInstances() { RunTestVariants(() => { C4Error error; var db2 = Native.c4db_openNamed(DBName, Native.c4db_getConfig2(Db), &error); ((long) db2).Should().NotBe(0); Native.c4db_nextDocExpiration(Db).Should().Be(0); Native.c4db_nextDocExpiration(db2).Should().Be(0); var docID = "expire_me"; CreateRev(docID, RevID, FleeceBody); var expire = Native.c4_now() + 1000; Native.c4doc_setExpiration(Db, docID, expire, &error); Native.c4db_nextDocExpiration(db2).Should().Be(expire); Native.c4db_release(db2); }); } [Fact] public void TestOpenBundle() { RunTestVariants(() => { string bundleDBName = "cbl_core_test_bundle"; var config2 = C4DatabaseConfig2.Clone(Native.c4db_getConfig2(Db)); var tmp = config2; var bundlePath = Path.Combine(TestDir, $"{bundleDBName}.cblite2{Path.DirectorySeparatorChar}"); Native.c4db_deleteNamed(bundleDBName, TestDir, null); var bundle = (C4Database *)LiteCoreBridge.Check(err => { var localConfig = tmp; return Native.c4db_openNamed(bundleDBName, &localConfig, err); }); var path = Native.c4db_getPath(bundle); path.Should().Be(bundlePath, "because the database should store the correct path"); LiteCoreBridge.Check(err => Native.c4db_close(bundle, err)); Native.c4db_release(bundle); // Reopen without the 'create' flag: config2.flags &= ~C4DatabaseFlags.Create; tmp = config2; bundle = (C4Database *)LiteCoreBridge.Check(err => { var localConfig = tmp; return Native.c4db_openNamed(bundleDBName, &localConfig, err); }); LiteCoreBridge.Check(err => Native.c4db_close(bundle, err)); Native.c4db_release(bundle); // Open nonexistent bundle ((long)Native.c4db_openNamed($"no_such_bundle{Path.DirectorySeparatorChar}", &config2, null)).Should().Be(0, "because the bundle does not exist"); NativePrivate.c4log_warnOnErrors(true); }); } [Fact] public void TestReadonlyUUIDs() { RunTestVariants(() => { ReopenDBReadOnly(); C4Error err; C4UUID publicUUID, privateUUID; Native.c4db_getUUIDs(Db, &publicUUID, &privateUUID, &err).Should() .BeTrue("because the UUID should still be available in a read-only db"); }); } struct TestString { string _testStr; public string TestStr { get => _testStr; set { _testStr = value; } } } [Fact] public void TestDatabaseCopy() { RunTestVariants(() => { string nuDBName = "nudb"; var doc1ID = "doc001"; var doc2ID = "doc002"; CreateRev(doc1ID, RevID, FleeceBody); CreateRev(doc2ID, RevID, FleeceBody); var srcPath = Native.c4db_getPath(Db); C4Error error; var config = DBConfig2; if (!Native.c4db_deleteNamed(nuDBName, config.ParentDirectory, &error)) { error.code.Should().Be(0); } LiteCoreBridge.Check(err => { var localConfig = config; return Native.c4db_copyNamed(srcPath, nuDBName, &localConfig, err); }); var nudb = (C4Database*)LiteCoreBridge.Check(err => { var localConfig = config; return Native.c4db_openNamed(nuDBName, &localConfig, err); }); try { Native.c4db_getDocumentCount(nudb).Should().Be(2L, "because the database was seeded"); LiteCoreBridge.Check(err => Native.c4db_delete(nudb, err)); } finally { Native.c4db_release(nudb); } nudb = (C4Database*)LiteCoreBridge.Check(err => { var localConfig = config; return Native.c4db_openNamed(nuDBName, &localConfig, err); }); try { CreateRev(nudb, doc1ID, RevID, FleeceBody); Native.c4db_getDocumentCount(nudb).Should().Be(1L, "because a document was inserted"); } finally { Native.c4db_release(nudb); } var bogusPath = $"{TestDir}bogus{Path.DirectorySeparatorChar}bogus"; C4DatabaseConfig2 bogusConfig = C4DatabaseConfig2.Clone(Native.c4db_getConfig2(Db)); bogusConfig.ParentDirectory = bogusPath; Action a = () => LiteCoreBridge.Check(err => { var localConfig = bogusConfig; return Native.c4db_copyNamed(srcPath, nuDBName, &localConfig, err); }); a.Should().Throw<CouchbaseLiteException>().Where(e => e.Error == CouchbaseLiteError.NotFound && e.Domain == CouchbaseLiteErrorType.CouchbaseLite); DBConfig2 = *(Native.c4db_getConfig2(Db)); nudb = (C4Database*)LiteCoreBridge.Check(err => { var localConfig = DBConfig2; return Native.c4db_openNamed(nuDBName, &localConfig, err); }); try { Native.c4db_getDocumentCount(nudb).Should().Be(1L, "because the original database should remain"); } finally { Native.c4db_release(nudb); } var originalSrc = srcPath; srcPath = $"{srcPath}bogus{Path.DirectorySeparatorChar}"; a = () => LiteCoreBridge.Check(err => { var localConfig = DBConfig2; return Native.c4db_copyNamed(srcPath, nuDBName, &localConfig, err); }); a.Should().Throw<CouchbaseLiteException>().Where(e => e.Error == CouchbaseLiteError.NotFound && e.Domain == CouchbaseLiteErrorType.CouchbaseLite); nudb = (C4Database*)LiteCoreBridge.Check(err => { var localConfig = DBConfig2; return Native.c4db_openNamed(nuDBName, &localConfig, err); }); try { Native.c4db_getDocumentCount(nudb).Should().Be(1L, "because the original database should remain"); } finally { Native.c4db_release(nudb); } srcPath = originalSrc; a.Should().Throw<CouchbasePosixException>().Where(e => e.Error == EEXIST && e.Domain == CouchbaseLiteErrorType.POSIX); nudb = (C4Database*)LiteCoreBridge.Check(err => { var localConfig = DBConfig2; return Native.c4db_openNamed(nuDBName, &localConfig, err); }); try { Native.c4db_getDocumentCount(nudb).Should().Be(1L, "because the database copy failed"); LiteCoreBridge.Check(err => Native.c4db_delete(nudb, err)); } finally { Native.c4db_release(nudb); } }); } #if COUCHBASE_ENTERPRISE [Fact] public void TestDatabaseRekey() { RunTestVariants(() => { CreateNumberedDocs(99); // Add blob to the store: var blobToStore = FLSlice.Constant("This is a blob to store in the store!"); var blobKey = new C4BlobKey(); var blobStore = (C4BlobStore*)LiteCoreBridge.Check(err => Native.c4db_getBlobStore(Db, err)); LiteCoreBridge.Check(err => { C4BlobKey local; var retVal = NativeRaw.c4blob_create(blobStore, blobToStore, null, &local, err); blobKey = local; return retVal; }); C4Error error; var blobResult = NativeRaw.c4blob_getContents(blobStore, blobKey, &error); ((FLSlice)blobResult).Should().Be(blobToStore); Native.FLSliceResult_Release(blobResult); // If we're on the unexcrypted pass, encrypt the db. Otherwise, decrypt it: var newKey = new C4EncryptionKey(); if (Native.c4db_getConfig2(Db)->encryptionKey.algorithm == C4EncryptionAlgorithm.None) { newKey.algorithm = C4EncryptionAlgorithm.AES256; var keyBytes = Encoding.ASCII.GetBytes("a different key than default...."); Marshal.Copy(keyBytes, 0, (IntPtr) newKey.bytes, 32); var tmp = newKey; LiteCoreBridge.Check(err => { var local = tmp; return Native.c4db_rekey(Db, &local, err); }); } else { LiteCoreBridge.Check(err => { return Native.c4db_rekey(Db, null, err); }); } // Verify the db works: Native.c4db_getDocumentCount(Db).Should().Be(99); ((IntPtr)blobStore).Should().NotBe(IntPtr.Zero); blobResult = NativeRaw.c4blob_getContents(blobStore, blobKey, &error); ((FLSlice)blobResult).Should().Be(blobToStore); Native.FLSliceResult_Release(blobResult); // Check that db can be reopened with the new key: Native.c4db_getConfig2(Db)->encryptionKey.algorithm.Should().Be(newKey.algorithm); for(int i = 0; i < 32; i++) { Native.c4db_getConfig2(Db)->encryptionKey.bytes[i].Should().Be(newKey.bytes[i]); } ReopenDB(); }); } #endif } }
#if !UNITY_2018_2_OR_NEWER // Unity has deprecated Www using System; using System.Collections; using System.IO; using PlayFab.Json; using PlayFab.SharedModels; using UnityEngine; #if UNITY_5_4_OR_NEWER using UnityEngine.Networking; #else using UnityEngine.Experimental.Networking; #endif namespace PlayFab.Internal { public class PlayFabWww : ITransportPlugin { private bool _isInitialized = false; private int _pendingWwwMessages = 0; public bool IsInitialized { get { return _isInitialized; } } public void Initialize() { _isInitialized = true; } public void Update() { } public void OnDestroy() { } public void SimpleGetCall(string fullUrl, Action<byte[]> successCallback, Action<string> errorCallback) { PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine("get", fullUrl, null, successCallback, errorCallback)); } public void SimplePutCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback) { PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine("put", fullUrl, payload, successCallback, errorCallback)); } public void SimplePostCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback) { PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine("post", fullUrl, payload, successCallback, errorCallback)); } private static IEnumerator SimpleCallCoroutine(string method, string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback) { if (payload == null) { var www = new WWW(fullUrl); yield return www; if (!string.IsNullOrEmpty(www.error)) errorCallback(www.error); else successCallback(www.bytes); } else { UnityWebRequest request; if (method == "put") { request = UnityWebRequest.Put(fullUrl, payload); } else { var strPayload = System.Text.Encoding.UTF8.GetString(payload, 0, payload.Length); request = UnityWebRequest.Post(fullUrl, strPayload); } #if UNITY_2017_2_OR_NEWER request.chunkedTransfer = false; // can be removed after Unity's PUT will be more stable request.SendWebRequest(); #else request.Send(); #endif #if !UNITY_WEBGL while (request.uploadProgress < 1 || request.downloadProgress < 1) { yield return 1; } #else while (!request.isDone) { yield return 1; } #endif if (!string.IsNullOrEmpty(request.error)) errorCallback(request.error); else successCallback(request.downloadHandler.data); } } public void MakeApiCall(object reqContainerObj) { CallRequestContainer reqContainer = (CallRequestContainer)reqContainerObj; reqContainer.RequestHeaders["Content-Type"] = "application/json"; //Debug.LogFormat("Posting {0} to Url: {1}", req.Trim(), url); var www = new WWW(reqContainer.FullUrl, reqContainer.Payload, reqContainer.RequestHeaders); #if PLAYFAB_REQUEST_TIMING var stopwatch = System.Diagnostics.Stopwatch.StartNew(); #endif // Start the www corouting to Post, and get a response or error which is then passed to the callbacks. Action<string> wwwSuccessCallback = (response) => { try { #if PLAYFAB_REQUEST_TIMING var startTime = DateTime.UtcNow; #endif var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer); var httpResult = serializer.DeserializeObject<HttpResponseObject>(response); if (httpResult.code == 200) { // We have a good response from the server reqContainer.JsonResponse = serializer.SerializeObject(httpResult.data); reqContainer.DeserializeResultJson(); reqContainer.ApiResult.Request = reqContainer.ApiRequest; reqContainer.ApiResult.CustomData = reqContainer.CustomData; PlayFabHttp.instance.OnPlayFabApiResult(reqContainer); #if !DISABLE_PLAYFABCLIENT_API PlayFabDeviceUtil.OnPlayFabLogin(reqContainer.ApiResult, reqContainer.settings, reqContainer.instanceApi); #endif try { PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post); } catch (Exception e) { Debug.LogException(e); } #if PLAYFAB_REQUEST_TIMING stopwatch.Stop(); var timing = new PlayFabHttp.RequestTiming { StartTimeUtc = startTime, ApiEndpoint = reqContainer.ApiEndpoint, WorkerRequestMs = (int)stopwatch.ElapsedMilliseconds, MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds }; PlayFabHttp.SendRequestTiming(timing); #endif try { reqContainer.InvokeSuccessCallback(); } catch (Exception e) { Debug.LogException(e); } } else { if (reqContainer.ErrorCallback != null) { reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, response, reqContainer.CustomData); PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error); reqContainer.ErrorCallback(reqContainer.Error); } } } catch (Exception e) { Debug.LogException(e); } }; Action<string> wwwErrorCallback = (errorCb) => { reqContainer.JsonResponse = errorCb; if (reqContainer.ErrorCallback != null) { reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, reqContainer.JsonResponse, reqContainer.CustomData); PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error); reqContainer.ErrorCallback(reqContainer.Error); } }; PlayFabHttp.instance.StartCoroutine(PostPlayFabApiCall(www, wwwSuccessCallback, wwwErrorCallback)); } private IEnumerator PostPlayFabApiCall(WWW www, Action<string> wwwSuccessCallback, Action<string> wwwErrorCallback) { yield return www; if (!string.IsNullOrEmpty(www.error)) { wwwErrorCallback(www.error); } else { try { byte[] responseBytes = www.bytes; string responseText = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length); wwwSuccessCallback(responseText); } catch (Exception e) { wwwErrorCallback("Unhandled error in PlayFabWWW: " + e); } } www.Dispose(); } public int GetPendingMessages() { return _pendingWwwMessages; } } } #endif
using System.Collections.Generic; using FluentAssertions; using Nest; using Tests.Framework.ManagedElasticsearch.Nodes; using Tests.Framework.MockData; namespace Tests.Framework.ManagedElasticsearch.NodeSeeders { public class DefaultSeeder { public const string TestsIndexTemplateName = "nest_tests"; public const string ProjectsAliasName = "projects-alias"; private IElasticClient Client { get; } private readonly IIndexSettings _defaultIndexSettings = new IndexSettings { NumberOfShards = 2, NumberOfReplicas = 0 }; private IIndexSettings IndexSettings { get; } public DefaultSeeder(ElasticsearchNode node, IIndexSettings indexSettings) { this.Client = node.Client; this.IndexSettings = indexSettings ?? _defaultIndexSettings; } public DefaultSeeder(ElasticsearchNode node) : this(node, null) { } public void SeedNode() { if (!TestClient.Configuration.ForceReseed && AlreadySeeded()) return; // Ensure a clean slate by deleting everything regardless of whether they may already exist this.DeleteIndicesAndTemplates(); // and now recreate everything this.CreateIndicesAndSeedIndexData(); } // Sometimes we run against an manually started elasticsearch when // writing tests to cut down on cluster startup times. // If raw_fields exists assume this cluster is already seeded. private bool AlreadySeeded() => this.Client.IndexTemplateExists(TestsIndexTemplateName).Exists; public void DeleteIndicesAndTemplates() { if (this.Client.IndexTemplateExists(TestsIndexTemplateName).Exists) this.Client.DeleteIndexTemplate(TestsIndexTemplateName); if (this.Client.IndexExists(Infer.Indices<Project>()).Exists) this.Client.DeleteIndex(typeof(Project)); if (this.Client.IndexExists(Infer.Indices<Developer>()).Exists) this.Client.DeleteIndex(typeof(Developer)); if (this.Client.IndexExists(Infer.Indices<PercolatedQuery>()).Exists) this.Client.DeleteIndex(typeof(PercolatedQuery)); } public void CreateIndices() { CreateIndexTemplate(); CreateProjectIndex(); CreateDeveloperIndex(); CreatePercolatorIndex(); } private void SeedIndexData() { this.Client.IndexMany(Project.Projects); this.Client.IndexMany(Developer.Developers); this.Client.Index(new PercolatedQuery { Id = "1", Query = new MatchAllQuery() }); this.Client.Bulk(b => b .IndexMany( CommitActivity.CommitActivities, (d, c) => d.Document(c).Parent(c.ProjectName) ) ); this.Client.Refresh(Nest.Indices.Index(typeof(Project), typeof(Developer), typeof(PercolatedQuery))); } private void CreateIndicesAndSeedIndexData() { this.CreateIndices(); this.SeedIndexData(); } private void CreateIndexTemplate() { var putTemplateResult = this.Client.PutIndexTemplate(new PutIndexTemplateRequest(TestsIndexTemplateName) { Template = "*", Settings = this.IndexSettings }); putTemplateResult.IsValid.Should().BeTrue(); } private void CreateDeveloperIndex() { var createDeveloperIndex = this.Client.CreateIndex(Infer.Index<Developer>(), c => c .Mappings(map => map .Map<Developer>(m => m .AutoMap() .Properties(DeveloperProperties) ) ) ); createDeveloperIndex.IsValid.Should().BeTrue(); } private void CreateProjectIndex() { var createProjectIndex = this.Client.CreateIndex(typeof(Project), c => c .Settings(settings => settings .Analysis(ProjectAnalysisSettings) ) .Aliases(a => a .Alias(ProjectsAliasName) ) .Mappings(map => map .Map<Project>(m => m .AutoMap() .Properties(ProjectProperties) ) .Map<CommitActivity>(m => m .AutoMap() .Parent<Project>() .Properties(props => props .Object<Developer>(o => o .AutoMap() .Name(p => p.Committer) .Properties(DeveloperProperties) ) .Text(t => t .Name(p => p.ProjectName) .Index(false) ) ) ) ) ); createProjectIndex.IsValid.Should().BeTrue(); } public static IAnalysis ProjectAnalysisSettings(AnalysisDescriptor analysis) { analysis .TokenFilters(tokenFilters => tokenFilters .Shingle("shingle", shingle => shingle .MinShingleSize(2) .MaxShingleSize(4) ) ) .Analyzers(analyzers => analyzers .Custom("shingle", shingle => shingle .Filters("standard", "shingle") .Tokenizer("standard") ) ); //normalizers are a new feature since 5.2.0 if (TestClient.VersionUnderTestSatisfiedBy(">=5.2.0")) analysis.Normalizers(analyzers => analyzers .Custom("my_normalizer", n => n .Filters("lowercase", "asciifolding") ) ); return analysis; } private void CreatePercolatorIndex() { var createPercolatedIndex = this.Client.CreateIndex(typeof(PercolatedQuery), c => c .Settings(s => s .AutoExpandReplicas("0-all") ) .Mappings(map => map .Map<PercolatedQuery>(m => m .AutoMap() .Properties(PercolatedQueryProperties) ) ) ); createPercolatedIndex.IsValid.Should().BeTrue(); } public static PropertiesDescriptor<Project> ProjectProperties(PropertiesDescriptor<Project> props) => props .Keyword(s => s .Name(p => p.Name) .Store() .Fields(fs => fs .Text(ss => ss .Name("standard") .Analyzer("standard") ) .Completion(cm => cm .Name("suggest") ) ) ) .Text(s => s .Name(p => p.Description) .Fielddata() .Fields(f => f .Text(t => t .Name("shingle") .Analyzer("shingle") ) ) ) .Date(d => d .Store() .Name(p => p.StartedOn) ) .Text(d => d .Store() .Name(p => p.DateString) ) .Keyword(d => d .Name(p => p.State) .Fields(fs => fs .Text(st => st .Name("offsets") .IndexOptions(IndexOptions.Offsets) ) .Keyword(sk => sk .Name("keyword") ) ) ) .Nested<Tag>(mo => mo .AutoMap() .Name(p => p.Tags) .Properties(TagProperties) ) .Object<Developer>(o => o .AutoMap() .Name(p => p.LeadDeveloper) .Properties(DeveloperProperties) ) .GeoPoint(g => g .Name(p => p.Location) ) .Completion(cm => cm .Name(p => p.Suggest) .Contexts(cx => cx .Category(c => c .Name("color") ) ) ) .Number(n => n .Name(p => p.NumberOfCommits) .Store() ) .Object<Dictionary<string, Metadata>>(o => o .Name(p => p.Metadata) ); private static PropertiesDescriptor<Tag> TagProperties(PropertiesDescriptor<Tag> props) => props .Keyword(s => s .Name(p => p.Name) .Fields(f => f .Text(st => st .Name("vectors") .TermVector(TermVectorOption.WithPositionsOffsetsPayloads) ) ) ); private static PropertiesDescriptor<Developer> DeveloperProperties(PropertiesDescriptor<Developer> props) => props .Keyword(s => s .Name(p => p.OnlineHandle) ) .Keyword(s => s .Name(p => p.Gender) ) .Text(s => s .Name(p => p.FirstName) .TermVector(TermVectorOption.WithPositionsOffsetsPayloads) ) .Ip(s => s .Name(p => p.IPAddress) ) .GeoPoint(g => g .Name(p => p.Location) ) .Object<GeoIp>(o => o .Name(p => p.GeoIp) ); public static PropertiesDescriptor<PercolatedQuery> PercolatedQueryProperties(PropertiesDescriptor<PercolatedQuery> props) => props .Percolator(pp => pp .Name(n => n.Query) ); } }
using NUnit.Framework; namespace WhippedCream { [TestFixture] public class DefaultUrlServiceTests { [Test] public void Constructor_NullBaseUri() { try { new DefaultUrlService(null, null); Assert.Fail("We expect a System.ArgumentNullException when we pass in a null value for the baseUri parameter."); } catch (System.ArgumentNullException) { } } [Test] public void Constructor_BaseUrlReturnsCorrectValue() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual(baseUri.ToString(), service.BaseUrl, @" The BaseUrl property should return the value of the uri that was passed to the constructor. "); } [Test] public void Constructor_BaseUriReturnsCorrectValue() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual(baseUri, service.BaseUri, @" The BaseUri property should return the value of the uri that was passed to the constructor. "); } //GetUrl //---------------------------------------------------------- [Test] public void GetUrl_NoPreceedingSlash() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual("http://www.google.com/RelativePath/Path", service.GetUrl("RelativePath/Path"), @" The GetUrl method should take in a path and append it to the end of the base Url. If the path has a preceeding slash or not, it shouldn't matter. "); } [Test] public void GetUrl_PreceedingSlash() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual("http://www.google.com/RelativePath/Path", service.GetUrl("/RelativePath/Path"), @" The GetUrl method should take in a path and append it to the end of the base Url. If the path has a preceeding slash or not, it shouldn't matter. "); } [Test] public void GetUrl_WhiteSpaceAllOver() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual("http://www.google.com/RelativePath/Path", service.GetUrl(" RelativePath/Path "), @" The GetUrl method should take in a path and append it to the end of the base Url. All whitespace should be trimmed off of the path. "); } [Test] public void GetUrl_NullPath() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual(baseUri.ToString(), service.GetUrl(null), @" The GetUrl method should take in a path and append it to the end of the base Url. If null is passed for the path, then the base url should be returned. "); } //GetUri //------------------------------------------------------- [Test] public void GetUri_NoPreceedingSlash() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual(new System.Uri("http://www.google.com/RelativePath/Path"), service.GetUri("RelativePath/Path"), @" The GetUri method should take in a path and append it to the end of the base Url. If the path has a preceeding slash or not, it shouldn't matter. "); } [Test] public void GetUri_PreceedingSlash() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual(new System.Uri("http://www.google.com/RelativePath/Path"), service.GetUri("/RelativePath/Path"), @" The GetUri method should take in a path and append it to the end of the base Url. If the path has a preceeding slash or not, it shouldn't matter. "); } [Test] public void GetUri_WhiteSpaceAllOver() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual(new System.Uri("http://www.google.com/RelativePath/Path"), service.GetUri(" RelativePath/Path "), @" The GetUri method should take in a path and append it to the end of the base Url. If the path has a preceeding slash or not, it shouldn't matter. "); } [Test] public void GetUri_NullPath() { System.Uri baseUri = new System.Uri("http://www.google.com"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual(new System.Uri("http://www.google.com"), service.GetUri(null), @" The GetUri method should take in a path and append it to the end of the base Url. If null is passed in for the path, then the Base Uri should be returned. "); } //GetServiceUrl //---------------------------------------------------- [Test] public void GetServiceUrl_ServicePrefixPreceedingSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "/api"); Assert.AreEqual("https://www.cnn.gov/api/RelativeServicePath/PathAgain", service.GetServiceUrl("RelativeServicePath/PathAgain"), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. Having a preceeding slash before the service prefix should not prevent the service from creating a valid url. "); } [Test] public void GetServiceUrl_ServicePrefixNoPreceedingSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual("https://www.cnn.gov/api/RelativeServicePath/PathAgain", service.GetServiceUrl("RelativeServicePath/PathAgain"), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. "); } [Test] public void GetServiceUrl_ServicePrefixPostSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api/"); Assert.AreEqual("https://www.cnn.gov/api/RelativeServicePath/PathAgain", service.GetServiceUrl("RelativeServicePath/PathAgain"), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. Having a preceeding slash before the service prefix should not prevent the service from creating a valid url. "); } [Test] public void GetServiceUrl_ServicePrefixNoPostSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual("https://www.cnn.gov/api/RelativeServicePath/PathAgain", service.GetServiceUrl("RelativeServicePath/PathAgain"), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. "); } [Test] public void GetServiceUrl_ServicePrefixWhiteSpaceAllOver() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, " api "); Assert.AreEqual("https://www.cnn.gov/api/RelativeServicePath/PathAgain", service.GetServiceUrl("RelativeServicePath/PathAgain"), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. All whitespace should be trimmed off of the prefix before it is used. "); } [Test] public void GetServiceUrl_ServicePrefixEmpty() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, string.Empty); Assert.AreEqual("https://www.cnn.gov/RelativeServicePath/PathAgain", service.GetServiceUrl("RelativeServicePath/PathAgain"), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. If the service prefix is empty, then it should be ignored. "); } [Test] public void GetServiceUrl_ServicePrefixNull() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual("https://www.cnn.gov/RelativeServicePath/PathAgain", service.GetServiceUrl("RelativeServicePath/PathAgain"), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. If we pass null in for the service prefix, then it should be ignored. "); } [Test] public void GetServiceUrl_PathPreceedingSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "/api"); Assert.AreEqual("https://www.cnn.gov/api/RelativeServicePath/PathAgain", service.GetServiceUrl("/RelativeServicePath/PathAgain"), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. Having a preceeding slash before the path should not prevent the service from creating a valid url. "); } [Test] public void GetServiceUrl_PathNoPreceedingSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual("https://www.cnn.gov/api/RelativeServicePath/PathAgain", service.GetServiceUrl("RelativeServicePath/PathAgain"), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. "); } [Test] public void GetServiceUrl_PathWhiteSpaceAllOver() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual("https://www.cnn.gov/api/RelativeServicePath/PathAgain", service.GetServiceUrl(" RelativeServicePath/PathAgain "), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. All whitespace should be trimmed off of the path before it is used. "); } [Test] public void GetServiceUrl_PathEmpty() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual("https://www.cnn.gov/api", service.GetServiceUrl(""), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. If the path is empty, then it should be ignored. "); } [Test] public void GetServiceUrl_PathNull() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual("https://www.cnn.gov/api", service.GetServiceUrl(null), @" The GetServiceUrl should take in a path and append the service prefix to the base url, then append the path to the result of that. If we pass null in for the path, then it should be ignored. "); } //GetServiceUri //--------------------------------------------------------- [Test] public void GetServiceUri_ServicePrefixPreceedingSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "/api"); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api/RelativeServicePath/PathAgain"), service.GetServiceUri("RelativeServicePath/PathAgain"), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. Having a preceeding slash before the service prefix should not prevent the service from creating a valid url. "); } [Test] public void GetServiceUri_ServicePrefixNoPreceedingSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api/RelativeServicePath/PathAgain"), service.GetServiceUri("RelativeServicePath/PathAgain"), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. "); } [Test] public void GetServiceUri_ServicePrefixPostSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api/"); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api/RelativeServicePath/PathAgain"), service.GetServiceUri("RelativeServicePath/PathAgain"), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. Having a preceeding slash before the service prefix should not prevent the service from creating a valid url. "); } [Test] public void GetServiceUri_ServicePrefixNoPostSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api/RelativeServicePath/PathAgain"), service.GetServiceUri("RelativeServicePath/PathAgain"), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. "); } [Test] public void GetServiceUri_ServicePrefixWhiteSpaceAllOver() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, " api "); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api/RelativeServicePath/PathAgain"), service.GetServiceUri("RelativeServicePath/PathAgain"), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. All whitespace should be trimmed off of the prefix before it is used. "); } [Test] public void GetServiceUri_ServicePrefixEmpty() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, string.Empty); Assert.AreEqual(new System.Uri("https://www.cnn.gov/RelativeServicePath/PathAgain"), service.GetServiceUri("RelativeServicePath/PathAgain"), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. If the service prefix is empty, then it should be ignored. "); } [Test] public void GetServiceUri_ServicePrefixNull() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, null); Assert.AreEqual(new System.Uri("https://www.cnn.gov/RelativeServicePath/PathAgain"), service.GetServiceUri("RelativeServicePath/PathAgain"), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. If we pass null in for the service prefix, then it should be ignored. "); } [Test] public void GetServiceUri_PathPreceedingSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "/api"); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api/RelativeServicePath/PathAgain"), service.GetServiceUri("/RelativeServicePath/PathAgain"), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. Having a preceeding slash before the path should not prevent the service from creating a valid url. "); } [Test] public void GetServiceUri_PathNoPreceedingSlash() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api/RelativeServicePath/PathAgain"), service.GetServiceUri("RelativeServicePath/PathAgain"), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. "); } [Test] public void GetServiceUri_PathWhiteSpaceAllOver() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api/RelativeServicePath/PathAgain"), service.GetServiceUri(" RelativeServicePath/PathAgain "), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. All whitespace should be trimmed off of the path before it is used. "); } [Test] public void GetServiceUri_PathEmpty() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api"), service.GetServiceUri(""), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. If the path is empty, then it should be ignored. "); } [Test] public void GetServiceUri_PathNull() { System.Uri baseUri = new System.Uri("https://www.cnn.gov"); IUrlService service = new DefaultUrlService(baseUri, "api"); Assert.AreEqual(new System.Uri("https://www.cnn.gov/api"), service.GetServiceUri(null), @" The GetServiceUri should take in a path and append the service prefix to the base url, then append the path to the result of that. If we pass null in for the path, then it should be ignored. "); } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Threading; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Options for calls made by client. /// </summary> public struct CallOptions { Metadata headers; DateTime? deadline; CancellationToken cancellationToken; WriteOptions writeOptions; ContextPropagationToken propagationToken; CallCredentials credentials; /// <summary> /// Creates a new instance of <c>CallOptions</c> struct. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> /// <param name="writeOptions">Write options that will be used for this call.</param> /// <param name="propagationToken">Context propagation token obtained from <see cref="ServerCallContext"/>.</param> /// <param name="credentials">Credentials to use for this call.</param> public CallOptions(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken), WriteOptions writeOptions = null, ContextPropagationToken propagationToken = null, CallCredentials credentials = null) { this.headers = headers; this.deadline = deadline; this.cancellationToken = cancellationToken; this.writeOptions = writeOptions; this.propagationToken = propagationToken; this.credentials = credentials; } /// <summary> /// Headers to send at the beginning of the call. /// </summary> public Metadata Headers { get { return headers; } } /// <summary> /// Call deadline. /// </summary> public DateTime? Deadline { get { return deadline; } } /// <summary> /// Token that can be used for cancelling the call. /// </summary> public CancellationToken CancellationToken { get { return cancellationToken; } } /// <summary> /// Write options that will be used for this call. /// </summary> public WriteOptions WriteOptions { get { return this.writeOptions; } } /// <summary> /// Token for propagating parent call context. /// </summary> public ContextPropagationToken PropagationToken { get { return this.propagationToken; } } /// <summary> /// Credentials to use for this call. /// </summary> public CallCredentials Credentials { get { return this.credentials; } } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Headers</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="headers">The headers.</param> public CallOptions WithHeaders(Metadata headers) { var newOptions = this; newOptions.headers = headers; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Deadline</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="deadline">The deadline.</param> public CallOptions WithDeadline(DateTime deadline) { var newOptions = this; newOptions.deadline = deadline; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>CancellationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> public CallOptions WithCancellationToken(CancellationToken cancellationToken) { var newOptions = this; newOptions.cancellationToken = cancellationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>WriteOptions</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="writeOptions">The write options.</param> public CallOptions WithWriteOptions(WriteOptions writeOptions) { var newOptions = this; newOptions.writeOptions = writeOptions; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>PropagationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="propagationToken">The context propagation token.</param> public CallOptions WithPropagationToken(ContextPropagationToken propagationToken) { var newOptions = this; newOptions.propagationToken = propagationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Credentials</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="credentials">The call credentials.</param> public CallOptions WithCredentials(CallCredentials credentials) { var newOptions = this; newOptions.credentials = credentials; return newOptions; } /// <summary> /// Returns a new instance of <see cref="CallOptions"/> with /// all previously unset values set to their defaults and deadline and cancellation /// token propagated when appropriate. /// </summary> internal CallOptions Normalize() { var newOptions = this; if (propagationToken != null) { if (propagationToken.Options.IsPropagateDeadline) { GrpcPreconditions.CheckArgument(!newOptions.deadline.HasValue, "Cannot propagate deadline from parent call. The deadline has already been set explicitly."); newOptions.deadline = propagationToken.ParentDeadline; } if (propagationToken.Options.IsPropagateCancellation) { GrpcPreconditions.CheckArgument(!newOptions.cancellationToken.CanBeCanceled, "Cannot propagate cancellation token from parent call. The cancellation token has already been set to a non-default value."); newOptions.cancellationToken = propagationToken.ParentCancellationToken; } } newOptions.headers = newOptions.headers ?? Metadata.Empty; newOptions.deadline = newOptions.deadline ?? DateTime.MaxValue; return newOptions; } } }
//! \file ArcKaguya.cs //! \date Mon Jun 01 07:03:03 2015 //! \brief KaGuYa archive format. // // Copyright (C) 2015 by morkt // // 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.ComponentModel.Composition; using System.IO; using GameRes.Utility; namespace GameRes.Formats.Kaguya { internal class AriEntry : PackedEntry { public ushort Mode; } [Export(typeof(ArchiveFormat))] public class ArcOpener : ArchiveFormat { public override string Tag { get { return "ARI"; } } public override string Description { get { return "KaGuYa script engine resource archive"; } } public override uint Signature { get { return 0x314c4657; } } // 'WFL1' public override bool IsHierarchic { get { return false; } } public override bool CanCreate { get { return false; } } public ArcOpener () { Extensions = new string[] { "arc" }; } public override ArcFile TryOpen (ArcView file) { var reader = new IndexReader(); var dir = reader.ReadIndex (file); if (null == dir || 0 == dir.Count) return null; return new ArcFile (file, this, dir); } public override Stream OpenEntry (ArcFile arc, Entry entry) { var packed_entry = entry as PackedEntry; if (null == packed_entry || !packed_entry.IsPacked) return arc.File.CreateStream (entry.Offset, entry.Size); if (0 == packed_entry.UnpackedSize) packed_entry.UnpackedSize = arc.File.View.ReadUInt32 (entry.Offset-4); using (var input = arc.File.CreateStream (entry.Offset, entry.Size)) using (var reader = new LzReader (input, entry.Size, packed_entry.UnpackedSize)) { reader.Unpack(); return new MemoryStream (reader.Data); } } } internal class IndexReader { byte[] m_name_buf = new byte[0x20]; List<Entry> m_dir = new List<Entry>(); public List<Entry> ReadIndex (ArcView file) { string ari_name = Path.ChangeExtension (file.Name, "ari"); List<Entry> dir = null; if (file.Name != ari_name && VFS.FileExists (ari_name)) dir = ReadAriIndex (file, ari_name); if (null == dir || 0 == dir.Count) dir = BuildIndex (file); return dir; } List<Entry> ReadAriIndex (ArcView file, string ari_name) { long arc_offset = 4; using (var ari = VFS.OpenView (ari_name)) { long index_offset = 0; while (index_offset+4 < ari.MaxOffset) { int name_len = ari.View.ReadInt32 (index_offset); var name = ReadName (ari, index_offset+4, name_len); if (null == name) return null; var entry = new AriEntry { Name = name }; index_offset += name_len + 4; entry.Mode = ari.View.ReadUInt16 (index_offset); entry.Size = ari.View.ReadUInt32 (index_offset+2); entry.UnpackedSize = 0; SetType (entry); index_offset += 6; arc_offset += name_len + 10; if (1 == entry.Mode) { entry.IsPacked = true; arc_offset += 4; } entry.Offset = arc_offset; if (!entry.CheckPlacement (file.MaxOffset)) return null; arc_offset += entry.Size; m_dir.Add (entry); } } return m_dir; } List<Entry> BuildIndex (ArcView file) { long arc_offset = 4; while (arc_offset+4 < file.MaxOffset) { int name_len = file.View.ReadInt32 (arc_offset); var name = ReadName (file, arc_offset+4, name_len); if (null == name) return null; var entry = new AriEntry { Name = name }; arc_offset += name_len + 4; entry.Mode = file.View.ReadUInt16 (arc_offset); entry.Size = file.View.ReadUInt32 (arc_offset+2); SetType (entry); arc_offset += 6; if (1 == entry.Mode) { entry.IsPacked = true; entry.UnpackedSize = file.View.ReadUInt32 (arc_offset); arc_offset += 4; } entry.Offset = arc_offset; if (!entry.CheckPlacement (file.MaxOffset)) return null; arc_offset += entry.Size; m_dir.Add (entry); } return m_dir; } void SetType (AriEntry entry) { if (2 == entry.Mode) entry.Type = "audio"; else if (1 == entry.Mode) entry.Type = "image"; else entry.Type = FormatCatalog.Instance.GetTypeFromName (entry.Name); } string ReadName (ArcView file, long offset, int name_len) { if (name_len <= 0 || offset+name_len+6 > file.MaxOffset || name_len > 0x100) return null; if (name_len > m_name_buf.Length) m_name_buf = new byte[name_len]; file.View.Read (offset, m_name_buf, 0, (uint)name_len); return DecryptName (m_name_buf, name_len); } string DecryptName (byte[] name_buf, int name_len) { for (int i = 0; i < name_len; ++i) name_buf[i] ^= 0xff; return Encodings.cp932.GetString (name_buf, 0, name_len); } } internal sealed class LzReader : IDisposable, IDataUnpacker { MsbBitStream m_input; byte[] m_output; public byte[] Data { get { return m_output; } } public LzReader (Stream input, uint packed_size, uint unpacked_size) { m_input = new MsbBitStream (input, true); m_output = new byte[unpacked_size]; } public void Unpack () { int dst = 0; int frame_pos = 1; byte[] frame = new byte[4096]; int frame_mask = frame.Length - 1; while (dst < m_output.Length) { int bit = m_input.GetNextBit(); if (-1 == bit) break; if (0 != bit) { int data = m_input.GetBits (8); m_output[dst++] = (byte)data; frame[frame_pos++] = (byte)data; frame_pos &= frame_mask; } else { int win_offset = m_input.GetBits (12); if (-1 == win_offset || 0 == win_offset) break; int count = m_input.GetBits(4) + 2; for (int i = 0; i < count; i++) { byte data = frame[(win_offset + i) & frame_mask]; m_output[dst++] = data; frame[frame_pos++] = data; frame_pos &= frame_mask; } } } } #region IDisposable Members bool _disposed = false; public void Dispose () { if (!_disposed) { m_input.Dispose(); _disposed = true; } } #endregion } }
// // BinaryXmlReader.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Text; using System.IO; namespace Mono.Addins.Serialization { internal class BinaryXmlReader { BinaryReader reader; internal const byte TagEndOfFile = 0; internal const byte TagBeginElement = 1; internal const byte TagEndElement = 2; internal const byte TagValue = 4; internal const byte TagObject = 5; internal const byte TagObjectArray = 6; internal const byte TagObjectDictionary = 7; internal const byte TagObjectNull = 8; byte currentType; string currentName; ArrayList stringTable = new ArrayList (); BinaryXmlTypeMap typeMap; object contextData; bool ignoreDesc; public BinaryXmlReader (Stream stream, BinaryXmlTypeMap typeMap) { reader = new BinaryReader (stream); this.typeMap = typeMap; ReadNext (); } public BinaryXmlTypeMap TypeMap { get { return typeMap; } set { typeMap = value; } } public object ContextData { get { return contextData; } set { contextData = value; } } // Returns 'true' if description data must be ignored when reading the contents of a file public bool IgnoreDescriptionData { get { return ignoreDesc; } set { ignoreDesc = value; } } void ReadNext () { int b = reader.BaseStream.ReadByte (); if (b == -1) { currentType = TagEndOfFile; return; } currentType = (byte) b; if (currentType == TagBeginElement || currentType == TagValue) currentName = ReadString (); } string ReadString () { // The first integer means: // >=0: string of the specified length // -1: null string // <-1: a string from the string table int len = reader.ReadInt32 (); if (len == -1) return null; if (len < -1) return (string) stringTable [-(len + 2)]; byte[] bytes = new byte [len]; int n = 0; while (n < len) { int read = reader.Read (bytes, n, len - n); if (read == 0) throw new InvalidOperationException ("Length too high for string: " + len); n += read; } string s = Encoding.UTF8.GetString (bytes); stringTable.Add (s); return s; } public string LocalName { get { return currentName; } } public bool IsElement { get { return currentType == TagBeginElement; } } public bool IsValue { get { return currentType == TagValue; } } TypeCode ReadValueType (TypeCode type) { if (currentType != TagValue) throw new InvalidOperationException ("Reader not positioned on a value."); TypeCode t = (TypeCode) reader.ReadByte (); if (t != type && type != TypeCode.Empty) throw new InvalidOperationException ("Invalid value type. Expected " + type + ", found " + t); return t; } public string ReadStringValue (string name) { if (!SkipToValue (name)) return null; return ReadStringValue (); } public string ReadStringValue () { if (currentType != TagValue) throw new InvalidOperationException ("Reader not positioned on a value."); TypeCode t = (TypeCode) reader.ReadByte (); if (t == TypeCode.Empty) { ReadNext (); return null; } if (t != TypeCode.String) throw new InvalidOperationException ("Invalid value type. Expected String, found " + t); string s = ReadString (); ReadNext (); return s; } public bool ReadBooleanValue (string name) { if (!SkipToValue (name)) return false; return ReadBooleanValue (); } public bool ReadBooleanValue () { ReadValueType (TypeCode.Boolean); bool value = reader.ReadBoolean (); ReadNext (); return value; } public char ReadCharValue (string name) { if (!SkipToValue (name)) return (char)0; return ReadCharValue (); } public char ReadCharValue () { ReadValueType (TypeCode.Char); char value = reader.ReadChar (); ReadNext (); return value; } public byte ReadByteValue (string name) { if (!SkipToValue (name)) return (byte)0; return ReadByteValue (); } public byte ReadByteValue () { ReadValueType (TypeCode.Byte); byte value = reader.ReadByte (); ReadNext (); return value; } public short ReadInt16Value (string name) { if (!SkipToValue (name)) return (short)0; return ReadInt16Value (); } public short ReadInt16Value () { ReadValueType (TypeCode.Int16); short value = reader.ReadInt16 (); ReadNext (); return value; } public int ReadInt32Value (string name) { if (!SkipToValue (name)) return 0; return ReadInt32Value (); } public int ReadInt32Value () { ReadValueType (TypeCode.Int32); int value = reader.ReadInt32 (); ReadNext (); return value; } public long ReadInt64Value (string name) { if (!SkipToValue (name)) return (long)0; return ReadInt64Value (); } public long ReadInt64Value () { ReadValueType (TypeCode.Int64); long value = reader.ReadInt64 (); ReadNext (); return value; } public DateTime ReadDateTimeValue (string name) { if (!SkipToValue (name)) return DateTime.MinValue; return ReadDateTimeValue (); } public DateTime ReadDateTimeValue () { ReadValueType (TypeCode.DateTime); DateTime value = new DateTime (reader.ReadInt64 ()); ReadNext (); return value; } public object ReadValue (string name) { if (!SkipToValue (name)) return null; return ReadValue (); } public object ReadValue () { object res = ReadValueInternal (); ReadNext (); return res; } public object ReadValue (string name, object targetInstance) { if (!SkipToValue (name)) return null; return ReadValue (targetInstance); } public object ReadValue (object targetInstance) { TypeCode t = (TypeCode) reader.ReadByte (); if (t == TypeCode.Empty) { ReadNext (); return null; } if (t != TypeCode.Object) throw new InvalidOperationException ("Invalid value type. Expected Object, found " + t); object res = ReadObject (targetInstance); ReadNext (); return res; } object ReadValueInternal () { TypeCode t = (TypeCode) reader.ReadByte (); if (t == TypeCode.Empty) return null; return ReadValueInternal (t); } object ReadValueInternal (TypeCode t) { object res; switch (t) { case TypeCode.Boolean: res = reader.ReadBoolean (); break; case TypeCode.Char: res = reader.ReadChar (); break; case TypeCode.SByte: res = reader.ReadSByte (); break; case TypeCode.Byte: res = reader.ReadByte (); break; case TypeCode.Int16: res = reader.ReadInt16 (); break; case TypeCode.UInt16: res = reader.ReadUInt16 (); break; case TypeCode.Int32: res = reader.ReadInt32 (); break; case TypeCode.UInt32: res = reader.ReadUInt32 (); break; case TypeCode.Int64: res = reader.ReadInt64 (); break; case TypeCode.UInt64: res = reader.ReadUInt64 (); break; case TypeCode.Single: res = reader.ReadSingle (); break; case TypeCode.Double: res = reader.ReadDouble (); break; case TypeCode.DateTime: res = new DateTime (reader.ReadInt64 ()); break; case TypeCode.String: res = ReadString (); break; case TypeCode.Object: res = ReadObject (null); break; case TypeCode.Empty: res = null; break; default: throw new InvalidOperationException ("Unexpected value type: " + t); } return res; } bool SkipToValue (string name) { do { if ((currentType == TagBeginElement || currentType == TagValue) && currentName == name) return true; if (EndOfElement) return false; Skip (); } while (true); } public void ReadBeginElement () { if (currentType != TagBeginElement) throw new InvalidOperationException ("Reader not positioned on an element."); ReadNext (); } public void ReadEndElement () { if (currentType != TagEndElement) throw new InvalidOperationException ("Reader not positioned on an element."); ReadNext (); } public bool EndOfElement { get { return currentType == TagEndElement; } } public void Skip () { if (currentType == TagValue) ReadValue (); else if (currentType == TagEndElement) ReadNext (); else if (currentType == TagBeginElement) { ReadNext (); while (!EndOfElement) Skip (); ReadNext (); } } object ReadObject (object targetInstance) { byte ot = reader.ReadByte (); if (ot == TagObjectNull) { return null; } else if (ot == TagObject) { string tname = ReadString (); IBinaryXmlElement ob; if (targetInstance != null) { ob = targetInstance as IBinaryXmlElement; if (ob == null) throw new InvalidOperationException ("Target instance has an invalid type. Expected an IBinaryXmlElement implementation."); } else { ob = typeMap.CreateObject (tname); } ReadNext (); ob.Read (this); while (currentType != TagEndElement) Skip (); return ob; } else if (ot == TagObjectArray) { TypeCode tc = (TypeCode) reader.ReadByte (); int len = reader.ReadInt32 (); if (targetInstance != null) { IList list = targetInstance as IList; if (list == null) throw new InvalidOperationException ("Target instance has an invalid type. Expected an IList implementation."); for (int n=0; n<len; n++) list.Add (ReadValueInternal ()); return list; } else { Array obs = CreateArray (tc, len); for (int n=0; n<len; n++) obs.SetValue (ReadValueInternal (), n); return obs; } } else if (ot == TagObjectDictionary) { int len = reader.ReadInt32 (); IDictionary table; if (targetInstance != null) { table = targetInstance as IDictionary; if (table == null) throw new InvalidOperationException ("Target instance has an invalid type. Expected an IDictionary implementation."); } else { table = new Hashtable (); } for (int n=0; n<len; n++) { object key = ReadValueInternal (); object val = ReadValueInternal (); table [key] = val; } return table; } else throw new InvalidOperationException ("Unknown object type tag: " + ot); } Array CreateArray (TypeCode t, int len) { switch (t) { case TypeCode.Boolean: return new bool [len]; case TypeCode.Char: return new Char [len]; case TypeCode.SByte: return new SByte [len]; case TypeCode.Byte: return new Byte [len]; case TypeCode.Int16: return new Int16 [len]; case TypeCode.UInt16: return new UInt16 [len]; case TypeCode.Int32: return new Int32 [len]; case TypeCode.UInt32: return new UInt32 [len]; case TypeCode.Int64: return new Int64 [len]; case TypeCode.UInt64: return new UInt64 [len]; case TypeCode.Single: return new Single [len]; case TypeCode.Double: return new Double [len]; case TypeCode.DateTime: return new DateTime [len]; case TypeCode.String: return new String [len]; case TypeCode.Object: return new Object [len]; default: throw new InvalidOperationException ("Unexpected value type: " + t); } } const int IndSize = 2; public static void DumpFile (string file) { Console.WriteLine ("FILE: " + file); using (Stream s = File.OpenRead (file)) { BinaryXmlReader r = new BinaryXmlReader (s, new BinaryXmlTypeMap ()); r.Dump (0); } } public void Dump (int ind) { if (currentType == TagValue) { Console.Write (new string (' ', ind) + LocalName + ": "); DumpValue (ind); Console.WriteLine (); } else if (currentType == TagBeginElement) { string name = LocalName; Console.WriteLine (new string (' ', ind) + "<" + name + ">"); DumpElement (ind + IndSize); Console.WriteLine (new string (' ', ind) + "</" + name + ">"); } } public void DumpElement (int ind) { ReadNext (); while (currentType != TagEndElement) { Dump (ind + IndSize); ReadNext (); } } void DumpValue (int ind) { TypeCode t = (TypeCode) reader.ReadByte (); if (t != TypeCode.Object) { object ob = ReadValueInternal (t); if (ob == null) ob = "(null)"; Console.Write (ob); } else { byte ot = reader.ReadByte (); switch (ot) { case TagObjectNull: { Console.Write ("(null)"); break; } case TagObject: { string tname = ReadString (); Console.WriteLine ("(" + tname + ")"); DumpElement (ind + IndSize); break; } case TagObjectArray: { TypeCode tc = (TypeCode) reader.ReadByte (); int len = reader.ReadInt32 (); Console.WriteLine ("(" + tc + "[" + len + "])"); for (int n=0; n<len; n++) { Console.Write (new string (' ', ind + IndSize) + n + ": "); DumpValue (ind + IndSize*2); Console.WriteLine (); } break; } case TagObjectDictionary: { int len = reader.ReadInt32 (); Console.WriteLine ("(IDictionary)"); for (int n=0; n<len; n++) { Console.Write (new string (' ', ind + IndSize) + "key: "); DumpValue (ind + IndSize*2); Console.WriteLine (); Console.Write (new string (' ', ind + IndSize) + "val: "); DumpValue (ind + IndSize*2); Console.WriteLine (); } break; } default: throw new InvalidOperationException ("Invalid object tag: " + ot); } } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Xml; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Calls the specified web service on each log message. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/WebService-target">Documentation on NLog Wiki</seealso> /// <remarks> /// The web service must implement a method that accepts a number of string parameters. /// </remarks> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/WebService/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/Example.cs" /> /// <p>The example web service that works with this example is shown below</p> /// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/WebService1/Service1.asmx.cs" /> /// </example> [Target("WebService")] public sealed class WebServiceTarget : MethodCallTargetBase { private const string SoapEnvelopeNamespaceUri = "http://schemas.xmlsoap.org/soap/envelope/"; private const string Soap12EnvelopeNamespaceUri = "http://www.w3.org/2003/05/soap-envelope"; /// <summary> /// dictionary that maps a concrete <see cref="HttpPostFormatterBase"/> implementation /// to a specific <see cref="WebServiceProtocol"/>-value. /// </summary> private static Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>> _postFormatterFactories = new Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>>() { { WebServiceProtocol.Soap11, t => new HttpPostSoap11Formatter(t)}, { WebServiceProtocol.Soap12, t => new HttpPostSoap12Formatter(t)}, { WebServiceProtocol.HttpPost, t => new HttpPostFormEncodedFormatter(t)}, { WebServiceProtocol.JsonPost, t => new HttpPostJsonFormatter(t)}, { WebServiceProtocol.XmlPost, t => new HttpPostXmlDocumentFormatter(t)}, }; /// <summary> /// Initializes a new instance of the <see cref="WebServiceTarget" /> class. /// </summary> public WebServiceTarget() { Protocol = WebServiceProtocol.Soap11; //default NO utf-8 bom const bool writeBOM = false; Encoding = new UTF8Encoding(writeBOM); IncludeBOM = writeBOM; Headers = new List<MethodCallParameter>(); #if NETSTANDARD1_3 || NETSTANDARD1_5 // NetCore1 throws PlatformNotSupportedException on WebRequest.GetSystemWebProxy, when using DefaultWebProxy // Net5 (or newer) will turn off Http-connection-pooling if not using DefaultWebProxy ProxyType = WebServiceProxyType.NoProxy; #endif } /// <summary> /// Initializes a new instance of the <see cref="WebServiceTarget" /> class. /// </summary> /// <param name="name">Name of the target</param> public WebServiceTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the web service URL. /// </summary> /// <docgen category='Web Service Options' order='10' /> public Layout<Uri> Url { get; set; } /// <summary> /// Gets or sets the value of the User-agent HTTP header. /// </summary> /// <docgen category='Web Service Options' order='10' /> public Layout UserAgent { get; set; } /// <summary> /// Gets or sets the Web service method name. Only used with Soap. /// </summary> /// <docgen category='Web Service Options' order='10' /> public string MethodName { get; set; } /// <summary> /// Gets or sets the Web service namespace. Only used with Soap. /// </summary> /// <docgen category='Web Service Options' order='10' /> public string Namespace { get; set; } /// <summary> /// Gets or sets the protocol to be used when calling web service. /// </summary> /// <docgen category='Web Service Options' order='10' /> public WebServiceProtocol Protocol { get => _activeProtocol.Key; set => _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(value, null); } private KeyValuePair<WebServiceProtocol, HttpPostFormatterBase> _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(WebServiceProtocol.Soap11, null); /// <summary> /// Gets or sets the proxy configuration when calling web service /// </summary> /// <remarks> /// Changing ProxyType on Net5 (or newer) will turn off Http-connection-pooling /// </remarks> /// <docgen category='Web Service Options' order='10' /> public WebServiceProxyType ProxyType { get => _activeProxy.Key; set => _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(value, null); } private KeyValuePair<WebServiceProxyType, IWebProxy> _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(WebServiceProxyType.DefaultWebProxy, null); /// <summary> /// Gets or sets the custom proxy address, include port separated by a colon /// </summary> /// <docgen category='Web Service Options' order='10' /> public Layout ProxyAddress { get; set; } /// <summary> /// Should we include the BOM (Byte-order-mark) for UTF? Influences the <see cref="Encoding"/> property. /// /// This will only work for UTF-8. /// </summary> /// <docgen category='Web Service Options' order='10' /> public bool? IncludeBOM { get; set; } /// <summary> /// Gets or sets the encoding. /// </summary> /// <docgen category='Web Service Options' order='10' /> public Encoding Encoding { get; set; } /// <summary> /// Gets or sets a value whether escaping be done according to Rfc3986 (Supports Internationalized Resource Identifiers - IRIs) /// </summary> /// <value>A value of <c>true</c> if Rfc3986; otherwise, <c>false</c> for legacy Rfc2396.</value> /// <docgen category='Web Service Options' order='100' /> public bool EscapeDataRfc3986 { get; set; } /// <summary> /// Gets or sets a value whether escaping be done according to the old NLog style (Very non-standard) /// </summary> /// <value>A value of <c>true</c> if legacy encoding; otherwise, <c>false</c> for standard UTF8 encoding.</value> /// <docgen category='Web Service Options' order='100' /> public bool EscapeDataNLogLegacy { get; set; } /// <summary> /// Gets or sets the name of the root XML element, /// if POST of XML document chosen. /// If so, this property must not be <c>null</c>. /// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>). /// </summary> /// <docgen category='Web Service Options' order='100' /> public string XmlRoot { get; set; } /// <summary> /// Gets or sets the (optional) root namespace of the XML document, /// if POST of XML document chosen. /// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>). /// </summary> /// <docgen category='Web Service Options' order='100' /> public string XmlRootNamespace { get; set; } /// <summary> /// Gets the array of parameters to be passed. /// </summary> /// <docgen category='Web Service Options' order='10' /> [ArrayParameter(typeof(MethodCallParameter), "header")] public IList<MethodCallParameter> Headers { get; private set; } /// <summary> /// Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in <see cref="Headers"/> parameters) /// </summary> /// <docgen category='Web Service Options' order='100' /> public bool PreAuthenticate { get; set; } private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter(); /// <summary> /// Calls the target method. Must be implemented in concrete classes. /// </summary> /// <param name="parameters">Method call parameters.</param> protected override void DoInvoke(object[] parameters) { // method is not used, instead asynchronous overload will be used throw new NotImplementedException(); } /// <summary> /// Calls the target DoInvoke method, and handles AsyncContinuation callback /// </summary> /// <param name="parameters">Method call parameters.</param> /// <param name="continuation">The continuation.</param> protected override void DoInvoke(object[] parameters, AsyncContinuation continuation) { var url = BuildWebServiceUrl(LogEventInfo.CreateNullEvent(), parameters); var webRequest = (HttpWebRequest)WebRequest.Create(url); DoInvoke(parameters, webRequest, continuation); } /// <summary> /// Invokes the web service method. /// </summary> /// <param name="parameters">Parameters to be passed.</param> /// <param name="logEvent">The logging event.</param> protected override void DoInvoke(object[] parameters, AsyncLogEventInfo logEvent) { var url = BuildWebServiceUrl(logEvent.LogEvent, parameters); var webRequest = (HttpWebRequest)WebRequest.Create(url); if (Headers?.Count > 0) { for (int i = 0; i < Headers.Count; i++) { string headerValue = RenderLogEvent(Headers[i].Layout, logEvent.LogEvent); if (headerValue is null) continue; webRequest.Headers[Headers[i].Name] = headerValue; } } #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var userAgent = RenderLogEvent(UserAgent, logEvent.LogEvent); if (!string.IsNullOrEmpty(userAgent)) { webRequest.UserAgent = userAgent; } #endif DoInvoke(parameters, webRequest, logEvent.Continuation); } private void DoInvoke(object[] parameters, HttpWebRequest webRequest, AsyncContinuation continuation) { Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest = (request, result) => request.BeginGetRequestStream(result, null); Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream = (request, result) => request.EndGetRequestStream(result); switch (ProxyType) { case WebServiceProxyType.DefaultWebProxy: break; #if !NETSTANDARD1_3 && !NETSTANDARD1_5 case WebServiceProxyType.AutoProxy: if (_activeProxy.Value is null) { IWebProxy proxy = WebRequest.GetSystemWebProxy(); proxy.Credentials = CredentialCache.DefaultCredentials; _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy); } webRequest.Proxy = _activeProxy.Value; break; case WebServiceProxyType.ProxyAddress: if (ProxyAddress != null) { if (_activeProxy.Value is null) { IWebProxy proxy = new WebProxy(RenderLogEvent(ProxyAddress, LogEventInfo.CreateNullEvent()), true); _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy); } webRequest.Proxy = _activeProxy.Value; } break; #endif default: webRequest.Proxy = null; break; } #if !NETSTANDARD1_3 && !NETSTANDARD1_5 if (PreAuthenticate || ProxyType == WebServiceProxyType.AutoProxy) { webRequest.PreAuthenticate = true; } #endif DoInvoke(parameters, continuation, webRequest, beginGetRequest, getRequestStream); } internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest webRequest, Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest, Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream) { MemoryStream postPayload = null; if (Protocol == WebServiceProtocol.HttpGet) { webRequest.Method = "GET"; } else { if (_activeProtocol.Value is null) _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(Protocol, _postFormatterFactories[Protocol](this)); postPayload = _activeProtocol.Value.PrepareRequest(webRequest, parameters); } _pendingManualFlushList.BeginOperation(); try { if (postPayload?.Length > 0) { PostPayload(continuation, webRequest, beginGetRequest, getRequestStream, postPayload); } else { WaitForReponse(continuation, webRequest); } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Error starting request", this); if (ExceptionMustBeRethrown(ex)) { throw; } DoInvokeCompleted(continuation, ex); } } private void WaitForReponse(AsyncContinuation continuation, HttpWebRequest webRequest) { webRequest.BeginGetResponse( r => { try { using (var response = webRequest.EndGetResponse(r)) { // Request successfully initialized } DoInvokeCompleted(continuation, null); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(ex, "{0}: Error receiving response", this); DoInvokeCompleted(continuation, ex); } }, null); } private void PostPayload(AsyncContinuation continuation, HttpWebRequest webRequest, Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest, Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream, MemoryStream postPayload) { beginGetRequest(webRequest, result => { try { using (Stream stream = getRequestStream(webRequest, result)) { WriteStreamAndFixPreamble(postPayload, stream, IncludeBOM, Encoding); postPayload.Dispose(); } WaitForReponse(continuation, webRequest); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(ex, "{0}: Error sending payload", this); postPayload.Dispose(); DoInvokeCompleted(continuation, ex); } }); } private void DoInvokeCompleted(AsyncContinuation continuation, Exception ex) { _pendingManualFlushList.CompleteOperation(ex); continuation(ex); } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { _pendingManualFlushList.RegisterCompletionNotification(asyncContinuation).Invoke(null); } /// <inheritdoc/> protected override void CloseTarget() { _pendingManualFlushList.Clear(); // Maybe consider to wait a short while if pending requests? base.CloseTarget(); } /// <summary> /// Builds the URL to use when calling the web service for a message, depending on the WebServiceProtocol. /// </summary> private Uri BuildWebServiceUrl(LogEventInfo logEvent, object[] parameterValues) { var uri = RenderLogEvent(Url, logEvent); if (Protocol != WebServiceProtocol.HttpGet) { return uri; } //if the protocol is HttpGet, we need to add the parameters to the query string of the url string queryParameters; using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { StringBuilder sb = targetBuilder.Result ?? new StringBuilder(); UrlHelper.EscapeEncodingOptions encodingOptions = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, false, EscapeDataRfc3986); BuildWebServiceQueryParameters(parameterValues, sb, encodingOptions); queryParameters = sb.ToString(); } var builder = new UriBuilder(uri); //append our query string to the URL following //the recommendations at https://msdn.microsoft.com/en-us/library/system.uribuilder.query.aspx if (builder.Query?.Length > 1) { builder.Query = string.Concat(builder.Query.Substring(1), "&", queryParameters); } else { builder.Query = queryParameters; } return builder.Uri; } private void BuildWebServiceQueryParameters(object[] parameterValues, StringBuilder sb, UrlHelper.EscapeEncodingOptions encodingOptions) { string separator = string.Empty; for (int i = 0; i < Parameters.Count; i++) { sb.Append(separator); sb.Append(Parameters[i].Name); sb.Append('='); string parameterValue = XmlHelper.XmlConvertToString(parameterValues[i]); if (!string.IsNullOrEmpty(parameterValue)) { UrlHelper.EscapeDataEncode(parameterValue, sb, encodingOptions); } separator = "&"; } } /// <summary> /// Write from input to output. Fix the UTF-8 bom /// </summary> private static void WriteStreamAndFixPreamble(MemoryStream postPayload, Stream output, bool? writeUtf8BOM, Encoding encoding) { //only when utf-8 encoding is used, the Encoding preamble is optional var nothingToDo = writeUtf8BOM is null || !(encoding is UTF8Encoding); const int preambleSize = 3; if (!nothingToDo) { //it's UTF-8 var hasBomInEncoding = encoding.GetPreamble().Length == preambleSize; //BOM already in Encoding. nothingToDo = writeUtf8BOM.Value && hasBomInEncoding; //Bom already not in Encoding nothingToDo = nothingToDo || !writeUtf8BOM.Value && !hasBomInEncoding; } var byteArray = postPayload.GetBuffer(); int offset = nothingToDo ? 0 : preambleSize; output.Write(byteArray, offset, (int)postPayload.Length - offset); } /// <summary> /// base class for POST formatters, that /// implement former <c>PrepareRequest()</c> method, /// that creates the content for /// the requested kind of HTTP request /// </summary> private abstract class HttpPostFormatterBase { protected HttpPostFormatterBase(WebServiceTarget target) { Target = target; } protected string ContentType => _contentType ?? (_contentType = GetContentType(Target)); private string _contentType; protected WebServiceTarget Target { get; private set; } protected virtual string GetContentType(WebServiceTarget target) { return string.Concat("charset=", target.Encoding.WebName); } public MemoryStream PrepareRequest(HttpWebRequest request, object[] parameterValues) { InitRequest(request); var ms = new MemoryStream(); WriteContent(ms, parameterValues); return ms; } protected virtual void InitRequest(HttpWebRequest request) { request.Method = "POST"; request.ContentType = ContentType; } protected abstract void WriteContent(MemoryStream ms, object[] parameterValues); } private class HttpPostFormEncodedFormatter : HttpPostTextFormatterBase { readonly UrlHelper.EscapeEncodingOptions _encodingOptions; public HttpPostFormEncodedFormatter(WebServiceTarget target) : base(target) { _encodingOptions = UrlHelper.GetUriStringEncodingFlags(target.EscapeDataNLogLegacy, true, target.EscapeDataRfc3986); } protected override string GetContentType(WebServiceTarget target) { return string.Concat("application/x-www-form-urlencoded", "; ", base.GetContentType(target)); } protected override void WriteStringContent(StringBuilder builder, object[] parameterValues) { Target.BuildWebServiceQueryParameters(parameterValues, builder, _encodingOptions); } } private class HttpPostJsonFormatter : HttpPostTextFormatterBase { private readonly IJsonConverter _jsonConverter; public HttpPostJsonFormatter(WebServiceTarget target) : base(target) { _jsonConverter = target.ResolveService<IJsonConverter>(); } protected override string GetContentType(WebServiceTarget target) { return string.Concat("application/json", "; ", base.GetContentType(target)); } protected override void WriteStringContent(StringBuilder builder, object[] parameterValues) { if (Target.Parameters.Count == 1 && string.IsNullOrEmpty(Target.Parameters[0].Name) && parameterValues[0] is string s) { // JsonPost with single nameless parameter means complex JsonLayout builder.Append(s); } else { builder.Append('{'); string separator = string.Empty; for (int i = 0; i < Target.Parameters.Count; ++i) { var parameter = Target.Parameters[i]; builder.Append(separator); builder.Append('"'); builder.Append(parameter.Name); builder.Append("\":"); _jsonConverter.SerializeObject(parameterValues[i], builder); separator = ","; } builder.Append('}'); } } } private class HttpPostSoap11Formatter : HttpPostSoapFormatterBase { private readonly string _defaultSoapAction; public HttpPostSoap11Formatter(WebServiceTarget target) : base(target) { _defaultSoapAction = GetDefaultSoapAction(target); } protected override string SoapEnvelopeNamespace => SoapEnvelopeNamespaceUri; protected override string SoapName => "soap"; protected override string GetContentType(WebServiceTarget target) { return string.Concat("text/xml", "; ", base.GetContentType(target)); } protected override void InitRequest(HttpWebRequest request) { base.InitRequest(request); if (Target.Headers?.Count == 0 || string.IsNullOrEmpty(request.Headers["SOAPAction"])) request.Headers["SOAPAction"] = _defaultSoapAction; } } private class HttpPostSoap12Formatter : HttpPostSoapFormatterBase { public HttpPostSoap12Formatter(WebServiceTarget target) : base(target) { } protected override string SoapEnvelopeNamespace => Soap12EnvelopeNamespaceUri; protected override string SoapName => "soap12"; protected override string GetContentType(WebServiceTarget target) { return GetContentTypeSoap12(target, GetDefaultSoapAction(target)); } protected override void InitRequest(HttpWebRequest request) { base.InitRequest(request); string nonDefaultSoapAction = Target.Headers?.Count > 0 ? request.Headers["SOAPAction"] : string.Empty; if (!string.IsNullOrEmpty(nonDefaultSoapAction)) request.ContentType = GetContentTypeSoap12(Target, nonDefaultSoapAction); } private string GetContentTypeSoap12(WebServiceTarget target, string soapAction) { return string.Concat("application/soap+xml", "; ", base.GetContentType(target), "; action=\"", soapAction, "\""); } } private abstract class HttpPostSoapFormatterBase : HttpPostXmlFormatterBase { private readonly XmlWriterSettings _xmlWriterSettings; protected HttpPostSoapFormatterBase(WebServiceTarget target) : base(target) { _xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding }; } protected abstract string SoapEnvelopeNamespace { get; } protected abstract string SoapName { get; } protected override void WriteContent(MemoryStream ms, object[] parameterValues) { using (var xtw = XmlWriter.Create(ms, _xmlWriterSettings)) { xtw.WriteStartElement(SoapName, "Envelope", SoapEnvelopeNamespace); xtw.WriteStartElement("Body", SoapEnvelopeNamespace); xtw.WriteStartElement(Target.MethodName, Target.Namespace); WriteAllParametersToCurrenElement(xtw, parameterValues); xtw.WriteEndElement(); // method name xtw.WriteEndElement(); // Body xtw.WriteEndElement(); // soap:Envelope xtw.Flush(); } } protected static string GetDefaultSoapAction(WebServiceTarget target) { return target.Namespace.EndsWith("/", StringComparison.Ordinal) ? string.Concat(target.Namespace, target.MethodName) : string.Concat(target.Namespace, "/", target.MethodName); } } private abstract class HttpPostTextFormatterBase : HttpPostFormatterBase { readonly ReusableBuilderCreator _reusableStringBuilder = new ReusableBuilderCreator(); readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(1024); readonly byte[] _encodingPreamble; protected HttpPostTextFormatterBase(WebServiceTarget target) : base(target) { _encodingPreamble = target.Encoding.GetPreamble(); } protected override void WriteContent(MemoryStream ms, object[] parameterValues) { lock (_reusableStringBuilder) { using (var targetBuilder = _reusableStringBuilder.Allocate()) { WriteStringContent(targetBuilder.Result, parameterValues); using (var transformBuffer = _reusableEncodingBuffer.Allocate()) { if (_encodingPreamble.Length > 0) ms.Write(_encodingPreamble, 0, _encodingPreamble.Length); targetBuilder.Result.CopyToStream(ms, Target.Encoding, transformBuffer.Result); } } } } protected abstract void WriteStringContent(StringBuilder builder, object[] parameterValues); } private class HttpPostXmlDocumentFormatter : HttpPostXmlFormatterBase { private readonly XmlWriterSettings _xmlWriterSettings; public HttpPostXmlDocumentFormatter(WebServiceTarget target) : base(target) { if (string.IsNullOrEmpty(target.XmlRoot)) throw new InvalidOperationException("WebServiceProtocol.Xml requires WebServiceTarget.XmlRoot to be set."); _xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding, OmitXmlDeclaration = true, Indent = false }; } protected override string GetContentType(WebServiceTarget target) { return string.Concat("application/xml", "; ", base.GetContentType(target)); } protected override void WriteContent(MemoryStream ms, object[] parameterValues) { using (var xtw = XmlWriter.Create(ms, _xmlWriterSettings)) { xtw.WriteStartElement(Target.XmlRoot, Target.XmlRootNamespace); WriteAllParametersToCurrenElement(xtw, parameterValues); xtw.WriteEndElement(); xtw.Flush(); } } } private abstract class HttpPostXmlFormatterBase : HttpPostFormatterBase { protected HttpPostXmlFormatterBase(WebServiceTarget target) : base(target) { } protected void WriteAllParametersToCurrenElement(XmlWriter currentXmlWriter, object[] parameterValues) { for (int i = 0; i < Target.Parameters.Count; i++) { currentXmlWriter.WriteStartElement(Target.Parameters[i].Name); currentXmlWriter.WriteValue(parameterValues[i]); currentXmlWriter.WriteEndElement(); } } } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org/?p=license&r=2.4. // **************************************************************** namespace NUnit.Samples.Money { using System; using NUnit.Framework; /// <summary> /// /// </summary> /// [TestFixture] public class MoneyTest { private Money f12CHF; private Money f14CHF; private Money f7USD; private Money f21USD; private MoneyBag fMB1; private MoneyBag fMB2; /// <summary> /// /// </summary> /// [SetUp] protected void SetUp() { f12CHF= new Money(12, "CHF"); f14CHF= new Money(14, "CHF"); f7USD= new Money( 7, "USD"); f21USD= new Money(21, "USD"); fMB1= new MoneyBag(f12CHF, f7USD); fMB2= new MoneyBag(f14CHF, f21USD); } /// <summary> /// /// </summary> /// [Test] public void BagMultiply() { // {[12 CHF][7 USD]} *2 == {[24 CHF][14 USD]} Money[] bag = { new Money(24, "CHF"), new Money(14, "USD") }; MoneyBag expected= new MoneyBag(bag); Assert.AreEqual(expected, fMB1.Multiply(2)); Assert.AreEqual(fMB1, fMB1.Multiply(1)); Assert.IsTrue(fMB1.Multiply(0).IsZero); } /// <summary> /// /// </summary> /// [Test] public void BagNegate() { // {[12 CHF][7 USD]} negate == {[-12 CHF][-7 USD]} Money[] bag= { new Money(-12, "CHF"), new Money(-7, "USD") }; MoneyBag expected= new MoneyBag(bag); Assert.AreEqual(expected, fMB1.Negate()); } /// <summary> /// /// </summary> /// [Test] public void BagSimpleAdd() { // {[12 CHF][7 USD]} + [14 CHF] == {[26 CHF][7 USD]} Money[] bag= { new Money(26, "CHF"), new Money(7, "USD") }; MoneyBag expected= new MoneyBag(bag); Assert.AreEqual(expected, fMB1.Add(f14CHF)); } /// <summary> /// /// </summary> /// [Test] public void BagSubtract() { // {[12 CHF][7 USD]} - {[14 CHF][21 USD] == {[-2 CHF][-14 USD]} Money[] bag= { new Money(-2, "CHF"), new Money(-14, "USD") }; MoneyBag expected= new MoneyBag(bag); Assert.AreEqual(expected, fMB1.Subtract(fMB2)); } /// <summary> /// /// </summary> /// [Test] public void BagSumAdd() { // {[12 CHF][7 USD]} + {[14 CHF][21 USD]} == {[26 CHF][28 USD]} Money[] bag= { new Money(26, "CHF"), new Money(28, "USD") }; MoneyBag expected= new MoneyBag(bag); Assert.AreEqual(expected, fMB1.Add(fMB2)); } /// <summary> /// /// </summary> /// [Test] public void IsZero() { Assert.IsTrue(fMB1.Subtract(fMB1).IsZero); Money[] bag = { new Money(0, "CHF"), new Money(0, "USD") }; Assert.IsTrue(new MoneyBag(bag).IsZero); } /// <summary> /// /// </summary> /// [Test] public void MixedSimpleAdd() { // [12 CHF] + [7 USD] == {[12 CHF][7 USD]} Money[] bag= { f12CHF, f7USD }; MoneyBag expected= new MoneyBag(bag); Assert.AreEqual(expected, f12CHF.Add(f7USD)); } /// <summary> /// /// </summary> /// [Test] public void MoneyBagEquals() { //NOTE: Normally we use Assert.AreEqual to test whether two // objects are equal. But here we are testing the MoneyBag.Equals() // method itself, so using AreEqual would not serve the purpose. Assert.IsFalse(fMB1.Equals(null)); Assert.IsTrue(fMB1.Equals( fMB1 )); MoneyBag equal= new MoneyBag(new Money(12, "CHF"), new Money(7, "USD")); Assert.IsTrue(fMB1.Equals(equal)); Assert.IsTrue(!fMB1.Equals(f12CHF)); Assert.IsTrue(!f12CHF.Equals(fMB1)); Assert.IsTrue(!fMB1.Equals(fMB2)); } /// <summary> /// /// </summary> /// [Test] public void MoneyBagHash() { MoneyBag equal= new MoneyBag(new Money(12, "CHF"), new Money(7, "USD")); Assert.AreEqual(fMB1.GetHashCode(), equal.GetHashCode()); } /// <summary> /// /// </summary> /// [Test] public void MoneyEquals() { //NOTE: Normally we use Assert.AreEqual to test whether two // objects are equal. But here we are testing the MoneyBag.Equals() // method itself, so using AreEqual would not serve the purpose. Assert.IsFalse(f12CHF.Equals(null)); Money equalMoney= new Money(12, "CHF"); Assert.IsTrue(f12CHF.Equals( f12CHF )); Assert.IsTrue(f12CHF.Equals( equalMoney )); Assert.IsFalse(f12CHF.Equals(f14CHF)); } /// <summary> /// /// </summary> /// [Test] public void MoneyHash() { Assert.IsFalse(f12CHF.Equals(null)); Money equal= new Money(12, "CHF"); Assert.AreEqual(f12CHF.GetHashCode(), equal.GetHashCode()); } /// <summary> /// /// </summary> /// [Test] public void Normalize() { Money[] bag= { new Money(26, "CHF"), new Money(28, "CHF"), new Money(6, "CHF") }; MoneyBag moneyBag= new MoneyBag(bag); Money[] expected = { new Money(60, "CHF") }; // note: expected is still a MoneyBag MoneyBag expectedBag= new MoneyBag(expected); Assert.AreEqual(expectedBag, moneyBag); } /// <summary> /// /// </summary> /// [Test] public void Normalize2() { // {[12 CHF][7 USD]} - [12 CHF] == [7 USD] Money expected= new Money(7, "USD"); Assert.AreEqual(expected, fMB1.Subtract(f12CHF)); } /// <summary> /// /// </summary> /// [Test] public void Normalize3() { // {[12 CHF][7 USD]} - {[12 CHF][3 USD]} == [4 USD] Money[] s1 = { new Money(12, "CHF"), new Money(3, "USD") }; MoneyBag ms1= new MoneyBag(s1); Money expected= new Money(4, "USD"); Assert.AreEqual(expected, fMB1.Subtract(ms1)); } /// <summary> /// /// </summary> /// [Test] public void Normalize4() { // [12 CHF] - {[12 CHF][3 USD]} == [-3 USD] Money[] s1 = { new Money(12, "CHF"), new Money(3, "USD") }; MoneyBag ms1= new MoneyBag(s1); Money expected= new Money(-3, "USD"); Assert.AreEqual(expected, f12CHF.Subtract(ms1)); } /// <summary> /// /// </summary> /// [Test] public void Print() { Assert.AreEqual("[12 CHF]", f12CHF.ToString()); } /// <summary> /// /// </summary> /// [Test] public void SimpleAdd() { // [12 CHF] + [14 CHF] == [26 CHF] Money expected= new Money(26, "CHF"); Assert.AreEqual(expected, f12CHF.Add(f14CHF)); } /// <summary> /// /// </summary> /// [Test] public void SimpleBagAdd() { // [14 CHF] + {[12 CHF][7 USD]} == {[26 CHF][7 USD]} Money[] bag= { new Money(26, "CHF"), new Money(7, "USD") }; MoneyBag expected= new MoneyBag(bag); Assert.AreEqual(expected, f14CHF.Add(fMB1)); } /// <summary> /// /// </summary> /// [Test] public void SimpleMultiply() { // [14 CHF] *2 == [28 CHF] Money expected= new Money(28, "CHF"); Assert.AreEqual(expected, f14CHF.Multiply(2)); } /// <summary> /// /// </summary> /// [Test] public void SimpleNegate() { // [14 CHF] negate == [-14 CHF] Money expected= new Money(-14, "CHF"); Assert.AreEqual(expected, f14CHF.Negate()); } /// <summary> /// /// </summary> /// [Test] public void SimpleSubtract() { // [14 CHF] - [12 CHF] == [2 CHF] Money expected= new Money(2, "CHF"); Assert.AreEqual(expected, f14CHF.Subtract(f12CHF)); } } }
using System; using System.Diagnostics; using System.IO; using Raksha.Utilities.IO; using Raksha.Asn1.Utilities; namespace Raksha.Asn1 { /** * a general purpose ASN.1 decoder - note: this class differs from the * others in that it returns null after it has read the last object in * the stream. If an ASN.1 Null is encountered a Der/BER Null object is * returned. */ public class Asn1InputStream : FilterStream { private readonly int limit; internal static int FindLimit(Stream input) { if (input is LimitedInputStream) { return ((LimitedInputStream)input).GetRemaining(); } else if (input is MemoryStream) { MemoryStream mem = (MemoryStream)input; return (int)(mem.Length - mem.Position); } return int.MaxValue; } public Asn1InputStream( Stream inputStream) : this(inputStream, FindLimit(inputStream)) { } /** * Create an ASN1InputStream where no DER object will be longer than limit. * * @param input stream containing ASN.1 encoded data. * @param limit maximum size of a DER encoded object. */ public Asn1InputStream( Stream inputStream, int limit) : base(inputStream) { this.limit = limit; } /** * Create an ASN1InputStream based on the input byte array. The length of DER objects in * the stream is automatically limited to the length of the input array. * * @param input array containing ASN.1 encoded data. */ public Asn1InputStream( byte[] input) : this(new MemoryStream(input, false), input.Length) { } /** * build an object given its tag and the number of bytes to construct it from. */ private Asn1Object BuildObject( int tag, int tagNo, int length) { bool isConstructed = (tag & Asn1Tags.Constructed) != 0; DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this, length); if ((tag & Asn1Tags.Application) != 0) { return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray()); } if ((tag & Asn1Tags.Tagged) != 0) { return new Asn1StreamParser(defIn).ReadTaggedObject(isConstructed, tagNo); } if (isConstructed) { // TODO There are other tags that may be constructed (e.g. BitString) switch (tagNo) { case Asn1Tags.OctetString: // // yes, people actually do this... // return new BerOctetString(BuildDerEncodableVector(defIn)); case Asn1Tags.Sequence: return CreateDerSequence(defIn); case Asn1Tags.Set: return CreateDerSet(defIn); case Asn1Tags.External: return new DerExternal(BuildDerEncodableVector(defIn)); default: return new DerUnknownTag(true, tagNo, defIn.ToArray()); } } return CreatePrimitiveDerObject(tagNo, defIn.ToArray()); } internal Asn1EncodableVector BuildEncodableVector() { Asn1EncodableVector v = new Asn1EncodableVector(); Asn1Object o; while ((o = ReadObject()) != null) { v.Add(o); } return v; } internal virtual Asn1EncodableVector BuildDerEncodableVector( DefiniteLengthInputStream dIn) { return new Asn1InputStream(dIn).BuildEncodableVector(); } internal virtual DerSequence CreateDerSequence( DefiniteLengthInputStream dIn) { return DerSequence.FromVector(BuildDerEncodableVector(dIn)); } internal virtual DerSet CreateDerSet( DefiniteLengthInputStream dIn) { return DerSet.FromVector(BuildDerEncodableVector(dIn), false); } public Asn1Object ReadObject() { int tag = ReadByte(); if (tag <= 0) { if (tag == 0) throw new IOException("unexpected end-of-contents marker"); return null; } // // calculate tag number // int tagNo = ReadTagNumber(this, tag); bool isConstructed = (tag & Asn1Tags.Constructed) != 0; // // calculate length // int length = ReadLength(this, limit); if (length < 0) // indefinite length method { if (!isConstructed) throw new IOException("indefinite length primitive encoding encountered"); IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(this, limit); Asn1StreamParser sp = new Asn1StreamParser(indIn, limit); if ((tag & Asn1Tags.Application) != 0) { return new BerApplicationSpecificParser(tagNo, sp).ToAsn1Object(); } if ((tag & Asn1Tags.Tagged) != 0) { return new BerTaggedObjectParser(true, tagNo, sp).ToAsn1Object(); } // TODO There are other tags that may be constructed (e.g. BitString) switch (tagNo) { case Asn1Tags.OctetString: return new BerOctetStringParser(sp).ToAsn1Object(); case Asn1Tags.Sequence: return new BerSequenceParser(sp).ToAsn1Object(); case Asn1Tags.Set: return new BerSetParser(sp).ToAsn1Object(); case Asn1Tags.External: return new DerExternalParser(sp).ToAsn1Object(); default: throw new IOException("unknown BER object encountered"); } } else { try { return BuildObject(tag, tagNo, length); } catch (ArgumentException e) { throw new Asn1Exception("corrupted stream detected", e); } } } internal static int ReadTagNumber( Stream s, int tag) { int tagNo = tag & 0x1f; // // with tagged object tag number is bottom 5 bits, or stored at the start of the content // if (tagNo == 0x1f) { tagNo = 0; int b = s.ReadByte(); // X.690-0207 8.1.2.4.2 // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." if ((b & 0x7f) == 0) // Note: -1 will pass { throw new IOException("Corrupted stream - invalid high tag number found"); } while ((b >= 0) && ((b & 0x80) != 0)) { tagNo |= (b & 0x7f); tagNo <<= 7; b = s.ReadByte(); } if (b < 0) throw new EndOfStreamException("EOF found inside tag value."); tagNo |= (b & 0x7f); } return tagNo; } internal static int ReadLength( Stream s, int limit) { int length = s.ReadByte(); if (length < 0) throw new EndOfStreamException("EOF found when length expected"); if (length == 0x80) return -1; // indefinite-length encoding if (length > 127) { int size = length & 0x7f; // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here if (size > 4) throw new IOException("DER length more than 4 bytes: " + size); length = 0; for (int i = 0; i < size; i++) { int next = s.ReadByte(); if (next < 0) throw new EndOfStreamException("EOF found reading length"); length = (length << 8) + next; } if (length < 0) throw new IOException("Corrupted stream - negative length found"); if (length >= limit) // after all we must have read at least 1 byte throw new IOException("Corrupted stream - out of bounds length found"); } return length; } internal static Asn1Object CreatePrimitiveDerObject( int tagNo, byte[] bytes) { switch (tagNo) { case Asn1Tags.BitString: return DerBitString.FromAsn1Octets(bytes); case Asn1Tags.BmpString: return new DerBmpString(bytes); case Asn1Tags.Boolean: return new DerBoolean(bytes); case Asn1Tags.Enumerated: return new DerEnumerated(bytes); case Asn1Tags.GeneralizedTime: return new DerGeneralizedTime(bytes); case Asn1Tags.GeneralString: return new DerGeneralString(bytes); case Asn1Tags.IA5String: return new DerIA5String(bytes); case Asn1Tags.Integer: return new DerInteger(bytes); case Asn1Tags.Null: return DerNull.Instance; // actual content is ignored (enforce 0 length?) case Asn1Tags.NumericString: return new DerNumericString(bytes); case Asn1Tags.ObjectIdentifier: return new DerObjectIdentifier(bytes); case Asn1Tags.OctetString: return new DerOctetString(bytes); case Asn1Tags.PrintableString: return new DerPrintableString(bytes); case Asn1Tags.T61String: return new DerT61String(bytes); case Asn1Tags.UniversalString: return new DerUniversalString(bytes); case Asn1Tags.UtcTime: return new DerUtcTime(bytes); case Asn1Tags.Utf8String: return new DerUtf8String(bytes); case Asn1Tags.VisibleString: return new DerVisibleString(bytes); default: return new DerUnknownTag(false, tagNo, bytes); } } } }
// 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.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class FormatSpecifierTests : CSharpResultProviderTestBase { [Fact] public void NoQuotes_String() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes); var stringType = runtime.GetType(typeof(string)); // null var value = CreateDkmClrValue(null, type: stringType); var evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "null", "string", "s", editableValue: null, flags: DkmEvaluationResultFlags.None)); // "" value = CreateDkmClrValue(string.Empty, type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "", "string", "s", editableValue: "\"\"", flags: DkmEvaluationResultFlags.RawString)); // "'" value = CreateDkmClrValue("'", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "'", "string", "s", editableValue: "\"'\"", flags: DkmEvaluationResultFlags.RawString)); // "\"" value = CreateDkmClrValue("\"", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\"", "string", "s", editableValue: "\"\\\"\"", flags: DkmEvaluationResultFlags.RawString)); // "\\" value = CreateDkmClrValue("\\", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\\", "string", "s", editableValue: "\"\\\\\"", flags: DkmEvaluationResultFlags.RawString)); // "a\r\n\t\v\b\u001eb" value = CreateDkmClrValue("a\r\n\tb\v\b\u001ec", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "a\r\n\tb\v\b\u001ec", "string", "s", editableValue: "\"a\\r\\n\\tb\\v\\b\\u001ec\"", flags: DkmEvaluationResultFlags.RawString)); // "a\0b" value = CreateDkmClrValue("a\0b", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "a\0b", "string", "s", editableValue: "\"a\\0b\"", flags: DkmEvaluationResultFlags.RawString)); // "\u007f\u009f" value = CreateDkmClrValue("\u007f\u009f", type: stringType); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\u007f\u009f", "string", "s", editableValue: "\"\\u007f\\u009f\"", flags: DkmEvaluationResultFlags.RawString)); // " " with alias value = CreateDkmClrValue(" ", type: stringType, alias: "$1", evalFlags: DkmEvaluationResultFlags.HasObjectId); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", " {$1}", "string", "s", editableValue: "\" \"", flags: DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.HasObjectId)); // array value = CreateDkmClrValue(new string[] { "1" }, type: stringType.MakeArrayType()); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{string[1]}", "string[]", "a", editableValue: null, flags: DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); // DkmInspectionContext should not be inherited. Verify(children, EvalResult("[0]", "\"1\"", "string", "a[0]", editableValue: "\"1\"", flags: DkmEvaluationResultFlags.RawString)); } [Fact] public void NoQuotes_Char() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes); var charType = runtime.GetType(typeof(char)); // 0 var value = CreateDkmClrValue((char)0, type: charType); var evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "0 \0", "char", "c", editableValue: "'\\0'", flags: DkmEvaluationResultFlags.None)); // '\'' value = CreateDkmClrValue('\'', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "39 '", "char", "c", editableValue: "'\\''", flags: DkmEvaluationResultFlags.None)); // '"' value = CreateDkmClrValue('"', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "34 \"", "char", "c", editableValue: "'\"'", flags: DkmEvaluationResultFlags.None)); // '\\' value = CreateDkmClrValue('\\', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "92 \\", "char", "c", editableValue: "'\\\\'", flags: DkmEvaluationResultFlags.None)); // '\n' value = CreateDkmClrValue('\n', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "10 \n", "char", "c", editableValue: "'\\n'", flags: DkmEvaluationResultFlags.None)); // '\u001e' value = CreateDkmClrValue('\u001e', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "30 \u001e", "char", "c", editableValue: "'\\u001e'", flags: DkmEvaluationResultFlags.None)); // '\u007f' value = CreateDkmClrValue('\u007f', type: charType); evalResult = FormatResult("c", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("c", "127 \u007f", "char", "c", editableValue: "'\\u007f'", flags: DkmEvaluationResultFlags.None)); // array value = CreateDkmClrValue(new char[] { '1' }, type: charType.MakeArrayType()); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{char[1]}", "char[]", "a", editableValue: null, flags: DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); // DkmInspectionContext should not be inherited. Verify(children, EvalResult("[0]", "49 '1'", "char", "a[0]", editableValue: "'1'", flags: DkmEvaluationResultFlags.None)); } [Fact] public void NoQuotes_DebuggerDisplay() { var source = @"using System.Diagnostics; [DebuggerDisplay(""{F}+{G}"")] class C { string F = ""f""; object G = 'g'; }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes)); Verify(evalResult, EvalResult("o", "f+103 g", "C", "o", DkmEvaluationResultFlags.Expandable)); } } [Fact] public void RawView_NoProxy() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw); // int var value = CreateDkmClrValue(1, type: runtime.GetType(typeof(int))); var evalResult = FormatResult("i", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("i", "1", "int", "i, raw", editableValue: null, flags: DkmEvaluationResultFlags.None)); // string value = CreateDkmClrValue(string.Empty, type: runtime.GetType(typeof(string))); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("s", "\"\"", "string", "s, raw", editableValue: "\"\"", flags: DkmEvaluationResultFlags.RawString)); // object[] value = CreateDkmClrValue(new object[] { 1, 2, 3 }, type: runtime.GetType(typeof(object)).MakeArrayType()); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{object[3]}", "object[]", "a, raw", editableValue: null, flags: DkmEvaluationResultFlags.Expandable)); } [Fact] public void RawView() { var source = @"using System.Diagnostics; internal class P { public P(C c) { this.G = c.F != null; } public readonly bool G; } [DebuggerTypeProxy(typeof(P))] class C { internal C() : this(new C(null)) { } internal C(C f) { this.F = f; } internal readonly C F; } class Program { static void Main() { var o = new C(); System.Diagnostics.Debugger.Break(); } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); // Non-null value. var value = type.Instantiate(); var evalResult = FormatResult("o", "o, raw", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw)); Verify(evalResult, EvalResult("o", "{C}", "C", "o, raw", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{C}", "C", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); children = GetChildren(children[0]); // ShowValueRaw is not inherited. Verify(children, EvalResult("G", "false", "bool", "new P(o.F).G", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Null value. value = CreateDkmClrValue( value: null, type: type); evalResult = FormatResult("o", "o, raw", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw)); Verify(evalResult, EvalResult("o", "null", "C", "o, raw")); } } [Fact] public void ResultsView_FrameworkTypes() { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore()); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly); // object: not enumerable var value = CreateDkmClrValue(new object(), type: runtime.GetType(typeof(object))); var evalResult = FormatResult("o", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("o", "Only Enumerable types can have Results View", fullName: null)); // string: not considered enumerable which is consistent with legacy EE value = CreateDkmClrValue("", type: runtime.GetType(typeof(string))); evalResult = FormatResult("s", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("s", "Only Enumerable types can have Results View")); // Array: not considered enumerable which is consistent with legacy EE value = CreateDkmClrValue(new[] { 1 }, type: runtime.GetType(typeof(int[]))); evalResult = FormatResult("i", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("i", "Only Enumerable types can have Results View")); // ArrayList value = CreateDkmClrValue(new System.Collections.ArrayList(new[] { 2 }), type: runtime.GetType(typeof(System.Collections.ArrayList))); evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "Count = 1", "System.Collections.ArrayList", "a, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(a).Items[0]")); // List<object> value = CreateDkmClrValue(new System.Collections.Generic.List<object>(new object[] { 3 }), type: runtime.GetType(typeof(System.Collections.Generic.List<object>))); evalResult = FormatResult("l", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("l", "Count = 1", "System.Collections.Generic.List<object>", "l, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "3", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(l).Items[0]")); // int? value = CreateDkmClrValue(1, type: runtime.GetType(typeof(System.Nullable<>)).MakeGenericType(runtime.GetType(typeof(int)))); evalResult = FormatResult("i", value, inspectionContext: inspectionContext); Verify(evalResult, EvalFailedResult("i", "Only Enumerable types can have Results View")); } [Fact] public void ResultsView_IEnumerable() { var source = @"using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return new C(); } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o, results, d", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult("o", "{C}", "C", "o, results, d", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); // ResultsOnly is not inherited. Verify(children, EvalResult("[0]", "{C}", "object {C}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]")); } } [Fact] public void ResultsView_IEnumerableOfT() { var source = @"using System; using System.Collections; using System.Collections.Generic; struct S<T> : IEnumerable<T> { private readonly T t; internal S(T t) { this.t = t; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { yield return t; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("S`1").MakeGenericType(runtime.GetType(typeof(int))); var value = type.Instantiate(2); var evalResult = FormatResult("o", "o, results", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult("o", "{S<int>}", "S<int>", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]")); } } /// <summary> /// ResultsOnly is ignored for GetChildren and GetItems. /// </summary> [Fact] public void ResultsView_GetChildren() { var source = @"using System.Collections; using System.Collections.Generic; class C { IEnumerable<int> F { get { yield return 1; } } IEnumerable G { get { yield return 2; } } int H { get { return 3; } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // GetChildren without ResultsOnly var children = GetChildren(evalResult, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.None)); Verify(children, EvalResult("F", "{C.<get_F>d__1}", "System.Collections.Generic.IEnumerable<int> {C.<get_F>d__1}", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult("G", "{C.<get_G>d__3}", "System.Collections.IEnumerable {C.<get_G>d__3}", "o.G", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult("H", "3", "int", "o.H", DkmEvaluationResultFlags.ReadOnly)); // GetChildren with ResultsOnly children = GetChildren(evalResult, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(children, EvalResult("F", "{C.<get_F>d__1}", "System.Collections.Generic.IEnumerable<int> {C.<get_F>d__1}", "o.F, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult("G", "{C.<get_G>d__3}", "System.Collections.IEnumerable {C.<get_G>d__3}", "o.G, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalFailedResult("H", "Only Enumerable types can have Results View", fullName: null)); } } /// <summary> /// [DebuggerTypeProxy] should be ignored. /// </summary> [Fact] public void ResultsView_TypeProxy() { var source = @"using System.Collections; using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 1; } } class P { public P(C c) { } public object F { get { return 2; } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o, results", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult("o", "{C}", "C", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); } } [Fact] public void ResultsView_ExceptionThrown() { var source = @"using System; using System.Collections; class E : Exception, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { yield return 1; } } class C { internal ArrayList P { get { throw new NotImplementedException(); } } internal ArrayList Q { get { throw new E(); } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); var evalResult = FormatResult("o.P", "o.P, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.P", "'o.P' threw an exception of type 'System.NotImplementedException'")); memberValue = value.GetMemberValue("Q", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); evalResult = FormatResult("o.Q", "o.Q, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.Q", "'o.Q' threw an exception of type 'E'")); } } /// <summary> /// Report the error message for error values, regardless /// of whether the value is actually enumerable. /// </summary> [Fact] public void ResultsView_Error() { var source = @"using System.Collections; class C { bool f; internal ArrayList P { get { while (!this.f) { } return new ArrayList(); } } internal int Q { get { while (!this.f) { } return 3; } } }"; DkmClrRuntimeInstance runtime = null; GetMemberValueDelegate getMemberValue = (v, m) => { switch (m) { case "P": return CreateErrorValue(runtime.GetType(typeof(System.Collections.ArrayList)), "Property 'P' evaluation timed out"); case "Q": return CreateErrorValue(runtime.GetType(typeof(string)), "Property 'Q' evaluation timed out"); default: return null; } }; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); var evalResult = FormatResult("o.P", "o.P, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.P", "Property 'P' evaluation timed out")); memberValue = value.GetMemberValue("Q", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); evalResult = FormatResult("o.Q", "o.Q, results", memberValue, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o.Q", "Property 'Q' evaluation timed out")); } } [Fact] public void ResultsView_NoSystemCore() { var source = @"using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 1; } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", "o, results", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalFailedResult("o", "Results View requires System.Core.dll to be referenced")); } } } }
using System; using System.Collections; using UnityEngine; namespace Beat { /// <summary> /// RelativeValues of Beats /// </summary> public enum TickValue { ThirtySecond = 12, SixteenthTriplet = 16, Sixteenth = 24, EighthTriplet = 32, Eighth = 48, QuarterTriplet = 64, Quarter = 96, Half = 192, Measure = 384, Max = 385 }; /// <summary> /// RelativeValues of Beats /// </summary> public enum BeatValue { ThirtySecond, Sixteenth = 2, Eighth = 4, Quarter = 8, Half = 16, Measure = 32, Max = 33 }; /// <summary> /// Arguments for Beat Events /// </summary> public class Args { public TickValue BeatVal; public double BeatTime; public double NextBeatTime; public TickMask<bool> TickMask; public Args(TickValue beatVal, double beatTime, double nextBeatTime, TickMask<bool> beatTickMask) { BeatVal = beatVal; BeatTime = beatTime; NextBeatTime = nextBeatTime; TickMask = beatTickMask; } } /// <summary> /// Collections with beat value indexers /// </summary> /// <typeparam name="T">Type of beat mask, herein bool</typeparam> public class TickMask<T> { private readonly T[] _beatMaskArr = new T[(int)TickValue.Max]; public void Clear() { Array.Clear(_beatMaskArr, 0, (int)TickValue.Max); } public T this[TickValue i] { get { return _beatMaskArr[(int)i]; } set { _beatMaskArr[(int)i] = value; } } } /// <summary> /// Collections with beat value indexers /// </summary> /// <typeparam name="T">Type of beat mask, herein bool</typeparam> public class BeatMask<T> { private readonly T[] _beatMaskArr = new T[(int)BeatValue.Max]; public void Clear() { Array.Clear(_beatMaskArr, 0, (int)BeatValue.Max); } public T this[BeatValue i] { get { return _beatMaskArr[(int)i]; } set { _beatMaskArr[(int)i] = value; } } } [RequireComponent(typeof(AudioSource))] public class Clock : Singleton<Clock> { public class WaitForBeatSync : CustomYieldInstruction { private BeatValue _waitBeatValue; private int currentThirtySecond; public override bool keepWaiting { get { return (!Clock.Instance.ThisBeatMask[_waitBeatValue] || currentThirtySecond == Clock.Instance._thirtySecondCount); } } public WaitForBeatSync(BeatValue wtBeatValue) { this._waitBeatValue = wtBeatValue; this.currentThirtySecond = Clock.Instance._thirtySecondCount; //print("Starting Tick: " + currentTick); } } protected Clock() { } void Awake() { if (BPM.Equals(0.0)) Debug.LogWarning("BPM not set! Please set the BPM in the Beat Clock."); } public double StartDelay; [Header("M:B:T")] [SerializeField] private int Measures; //for display purposes in unity editor [SerializeField] private int Beats; [SerializeField] private int Ticks; [Header("Tempo")] public double BPM; [Header("Time Signature")] public int beatsPerMeasure; public int beatUnit = 4; //Not ready for primetime yet, need to massage distinctions between ticks & 32nd notes for it to work reliably //Honestly, American Music notation is terrible at making this clear, and whole note, etc. becomes ambiguous [Header("Accuracy Benchmarks (in ms)")] [SerializeField] private int AverageLatency; [SerializeField] private int AverageJitter; private double _sampleRate = 0.0; public BeatMask<bool> ThisBeatMask = new BeatMask<bool>(); public TickMask<bool> TickMask = new TickMask<bool>(); private TickMask<bool>[] _tickMaskArray = new TickMask<bool>[384]; public const int TicksPerBeat = 96; public double SamplesPerBeat; public int _tickCounter; private int _ticksPerMeasure; private int _thirtySecondCount; private int _lastThirtySecondCount; public double SamplesPerTick; private int _measureCount; public double TickLength; private double _thirtySecondLength; private double _sixteenthLength; private double _sixteenthTripletLength; private double _eighthLength; private double _eighthTripletLength; private double _quarterLength; private double _quarterTripletLength; private double _halfLength; private double _measureLength; private double _secondsPerMeasure; private double _nextTick = System.Double.MaxValue; private double _nextThirtySecond = System.Double.MaxValue; private double _nextSixteenth; private double _nextSixteenthTriplet; private double _nextEighth; private double _nextEighthTriplet; private double _nextQuarter; private double _nextQuarterTriplet; private double _nextHalf; private double _nextMeasure; private bool _initialized; private bool TestBool; private double _dspTimeAtTick; private int _latencyCounter; private double _latencyCompensation = 0; private double _rollingAverageOfLatency; private double _standardDeviationOfLatency; private double[] latency = new double[25]; public int latencyCalculationInterval; public delegate void CustomUpdate(); public event CustomUpdate AudioUpdate; public delegate void BeatEvent(Args args); /// <summary> /// Event sent every 32nd note /// </summary> public event BeatEvent ThirtySecond; /// <summary> /// Event sent every 16th note /// </summary> public event BeatEvent Sixteenth; /// <summary> /// Event sent every 8th note /// </summary> public event BeatEvent Eighth; /// <summary> /// Event sent every beat (1/4 note) /// </summary> public event BeatEvent Beat; /// <summary> /// Event sent every 32nd note /// </summary> public event BeatEvent Measure; /// <summary> /// Creates a beat mask array based on the number of ticks per measure /// </summary> void BuildBeatMaskArray() { _tickMaskArray = new TickMask<bool>[_ticksPerMeasure+1]; for (int i = 1; i <= _ticksPerMeasure; i++) { _tickMaskArray[i] = new TickMask<bool>(); //TODO: See if this impacts performance , used to use != & continue statements before triplets if (i % (int)TickValue.ThirtySecond == 0) _tickMaskArray[i][TickValue.ThirtySecond] = true; if (i % (int)TickValue.SixteenthTriplet == 0) _tickMaskArray[i][TickValue.SixteenthTriplet] = true; if (i % (int)TickValue.Sixteenth == 0) _tickMaskArray[i][TickValue.Sixteenth] = true; if (i % (int)TickValue.EighthTriplet == 0) _tickMaskArray[i][TickValue.EighthTriplet] = true; if (i % (int)TickValue.Eighth == 0) _tickMaskArray[i][TickValue.Eighth] = true; if (i % (int)TickValue.QuarterTriplet == 0) _tickMaskArray[i][TickValue.QuarterTriplet] = true; if (i % (int)TickValue.Quarter == 0) _tickMaskArray[i][TickValue.Quarter] = true; if (i % (int)TickValue.Half == 0) _tickMaskArray[i][TickValue.Half] = true; if (i % (int)TickValue.Measure == 0) _tickMaskArray[i][TickValue.Measure] = true; } } void BuildBeatMask() { //print("Build that mask: " + _thirtySecondCount); ThisBeatMask.Clear(); ThisBeatMask[BeatValue.ThirtySecond] = true; if (_thirtySecondCount % 2 != 0) return; ThisBeatMask[BeatValue.Sixteenth] = true; if (_thirtySecondCount % 4 != 0) return; ThisBeatMask[BeatValue.Eighth] = true; if (_thirtySecondCount % 8 != 0) return; ThisBeatMask[BeatValue.Quarter] = true; if (_thirtySecondCount % 16 != 0) return; ThisBeatMask[BeatValue.Half] = true; if (_thirtySecondCount % 32 != 0) return; ThisBeatMask[BeatValue.Measure] = true; } /// <summary> /// Set a new BPM. /// </summary> /// <param name="newBPM">New BPM, can be int, float, or double</param> public void SetBPM(int newBPM) { double BPMdbl = (double) newBPM; InitializeBPM(BPMdbl); } /// <summary> /// Set a new BPM. /// </summary> /// <param name="newBPM">New BPM, can be int, float, or double</param> public void SetBPM(float newBPM) { double BPMdbl = (double) newBPM; InitializeBPM(BPMdbl); } /// <summary> /// Set a new BPM. /// </summary> /// <param name="newBPM">New BPM, can be int, float, or double</param> public void SetBPM(double NewBPM) { InitializeBPM((NewBPM)); } /// <summary> /// Internal function to intitialize a new BPM. /// </summary> /// <param name="newBPM">BPM to be initialzed</param> void InitializeBPM(double NewBPM) { _initialized = false; ResetBeatCounts(); //if (NewBPM > 210) //{ // NewBPM = NewBPM / 2; // Debug.LogWarning("New BPM set > 210. Clock loses stability above ~210. Dividing BPM in half, using " + NewBPM + " instead."); //} BPM = NewBPM; //running = true; _secondsPerMeasure = 60/BPM*beatsPerMeasure; _ticksPerMeasure = TicksPerBeat*beatsPerMeasure; _tickCounter = _ticksPerMeasure; SetLengths(); BuildBeatMaskArray(); FirstBeat(); latency = new double[latencyCalculationInterval]; } /// <summary> /// Internal function to set lengths of each beat value /// </summary> void SetLengths() { _measureLength = _secondsPerMeasure; _sampleRate = AudioSettings.outputSampleRate; SamplesPerTick = _sampleRate*(_secondsPerMeasure/_ticksPerMeasure); SamplesPerBeat = SamplesPerTick * (_ticksPerMeasure / beatsPerMeasure); TickLength = _measureLength / _ticksPerMeasure; _thirtySecondLength = TickLength * (int)TickValue.ThirtySecond; _sixteenthTripletLength = TickLength*(int) TickValue.SixteenthTriplet; _sixteenthLength = TickLength*(int) TickValue.Sixteenth; _eighthTripletLength = TickLength*(int) TickValue.EighthTriplet; _eighthLength = TickLength*(int) TickValue.Eighth; _quarterTripletLength = TickLength * (int)TickValue.QuarterTriplet; _quarterLength = TickLength*(int)TickValue.Quarter; _halfLength = TickLength*(int) TickValue.Half; } /// <summary> /// Internal function, sets timings for next beats /// </summary> void FirstBeat() { double startTick = AudioSettings.dspTime + StartDelay; _nextTick = startTick * _sampleRate + SamplesPerTick; //_tickLength; _nextThirtySecond = startTick + _thirtySecondLength; _nextSixteenthTriplet = startTick + _sixteenthTripletLength; _nextSixteenth = startTick + _sixteenthLength; _nextEighthTriplet = startTick + _eighthTripletLength; _nextEighth = startTick + _eighthLength; _nextQuarterTriplet = startTick + _eighthTripletLength; _nextQuarter = startTick + _quarterLength; _nextHalf = startTick + _halfLength; _nextMeasure = startTick + _measureLength; _initialized = true; } /// <summary> /// Resets counts for all beats /// </summary> void ResetBeatCounts() { _tickCounter = 1; _measureCount = 1; } /// <summary> /// Initilizes & starts Clock on Start() /// </summary> void Start() { Application.runInBackground = true; if (!BPM.Equals(0.0)) { InitializeBPM(BPM); } else { Debug.LogWarning("BPM not set or set to 0, Clock not initialized on load."); } } void Update() { if (_thirtySecondCount != _lastThirtySecondCount) { BuildBeatMask(); _lastThirtySecondCount = _thirtySecondCount; } int A = 1; for (int i = 0; i < 10000; i++) { A = A+A; } } /// <summary> /// Using OnAudioFilter Read to updates beats & dispatches events accordingly. /// </summary> void OnAudioFilterRead(float[] data, int channels) { if (!_initialized) return; double sample = AudioSettings.dspTime*_sampleRate; int dataLen = data.Length/channels; int n = 0; while (n < dataLen) { if (sample + n >= _nextTick) { _nextTick += SamplesPerTick; if (++_tickCounter > _ticksPerMeasure) { _tickCounter = 1; _measureCount++; } UpdateBeats(); Measures = _measureCount; Beats = 1 + _tickCounter / (TicksPerBeat) ; Ticks = 1 + _tickCounter % (TicksPerBeat); //latency[_latencyCounter] = (_dspTimeAtTick - (_nextThirtySecond)); //benchmarking stuff } n++; } //_latencyCounter++; //if (_latencyCounter == latencyCalculationInterval) //{ // CalculateLatency(); //} } /// <summary> /// Function to update beat counts, called after every new tick /// </summary> void UpdateBeats() { if (AudioUpdate != null) AudioUpdate(); TickMask = _tickMaskArray[_tickCounter]; if (TickMask[TickValue.ThirtySecond]) { if (ThirtySecond != null) ThirtySecond(new Args(TickValue.ThirtySecond, _nextThirtySecond, _nextThirtySecond + _thirtySecondLength, TickMask)); _nextThirtySecond += _thirtySecondLength; _thirtySecondCount++; } if (TickMask[TickValue.SixteenthTriplet]) { _nextSixteenthTriplet += _sixteenthTripletLength; } if (TickMask[TickValue.Sixteenth]) { if (Sixteenth != null) Sixteenth(new Args(TickValue.Sixteenth, _nextSixteenth, _nextSixteenth + _sixteenthLength, TickMask)); _nextSixteenth += _sixteenthLength; } if (TickMask[TickValue.EighthTriplet]) { _nextEighthTriplet += _eighthTripletLength; } if (TickMask[TickValue.Eighth]) { if (Eighth != null) Eighth(new Args(TickValue.Eighth, _nextEighth, _nextEighth + _eighthLength, TickMask)); _nextEighth += _eighthLength; } if (TickMask[TickValue.QuarterTriplet]) { _nextQuarterTriplet += _quarterTripletLength; } if (TickMask[TickValue.Quarter]) { if (Beat != null) Beat(new Args(TickValue.Quarter, _nextQuarter, _nextQuarter + _quarterLength, TickMask)); _nextQuarter += _quarterLength; } if (TickMask[TickValue.Half]) { _nextHalf += _halfLength; } if (TickMask[TickValue.Measure]) { if (Measure != null) Measure(new Args(TickValue.Measure, _nextMeasure, _nextMeasure + _measureLength, TickMask)); _nextMeasure += _measureLength; //_thirtySecondCount = 0; } } /// <summary> /// Sync the execution of a function to the next specified beat, optionally add a number repetitions /// </summary> /// <param name="callback">Function to call at next beatTickValue</param> /// <param name="beatTickValue">Beat value at which function will be called (Default is measure / downbeat)</param> public void SyncFunction(System.Action callback, TickValue beatTickValue = TickValue.Measure) { StartCoroutine(YieldForSync(callback, beatTickValue)); } /// <summary> /// Sync the execution of a function to the next specified beat, optionally add a number repetitions /// </summary> /// <param name="callback">Function to call at next beatTickValue</param> /// <param name="beatTickValue">Beat value at which function will be called (Default is measure / downbeat)</param> IEnumerator YieldForSync(System.Action callback, TickValue beatTickValue) { return YieldForSyncRepeating(callback, beatTickValue, 1); } /// <summary> /// Sync the execution of a particular callback to a specified beat a specified number of times /// </summary> /// <param name="callback">Function to call at next beatTickValue</param> /// <param name="beatTickValue">Beat value at which function will be called</param> /// <param name="repetitions">Number of times function will be called</param> public void SyncFunction(System.Action callback, TickValue beatTickValue, int repetitions) { StartCoroutine(YieldForSyncRepeating(callback, beatTickValue, repetitions)); } /// <summary> /// Sync the execution of a particular callback to a specified beat a specified number of times /// </summary> /// <param name="callback">Function to call</param> /// <param name="beatTickValue">Beat value at which function will be called</param> /// <param name="repetitions">Number of times function will be called</param> /// <returns></returns> IEnumerator YieldForSyncRepeating(System.Action callback, TickValue beatTickValue, int repetitions) { int startCount = _tickCounter + _measureCount * _ticksPerMeasure; bool isStartNote = true; bool waiting = true; int timesRun = 0; int tickOfLastRun = 0; while (waiting) { isStartNote = isStartNote && startCount == _tickCounter + _measureCount * _ticksPerMeasure; if (isStartNote) yield return false; isStartNote = false; if ((beatTickValue == TickValue.ThirtySecond || TickMask[beatTickValue]) && (tickOfLastRun != _tickCounter + _measureCount * _ticksPerMeasure)) { if (repetitions <= timesRun) { waiting = false; } else { callback(); tickOfLastRun = _tickCounter + _measureCount * _ticksPerMeasure; timesRun++; yield return false; } } else yield return false; } } /// <summary> /// Returns time of next specified value Usage: AudioSource.PlayScheduled(AtNext(Beat.TickValue.Quarter)) /// </summary> /// <param name="beatTickValue">TickValue for which to get time of next</param> /// <returns>Time of next specified value</returns> public double AtNext(TickValue beatTickValue) { switch (beatTickValue) { case TickValue.ThirtySecond: return AtNextThirtySecond(); case TickValue.SixteenthTriplet: return AtNextSixteenthTriplet(); case TickValue.Sixteenth: return AtNextSixteenth(); case TickValue.EighthTriplet: return AtNextEighthTriplet(); case TickValue.Eighth: return AtNextEighth(); case TickValue.QuarterTriplet: return AtNextQuarterTriplet(); case TickValue.Quarter: return AtNextQuarter(); case TickValue.Half: return AtNextHalf(); case TickValue.Measure: return AtNextMeasure(); default: return AtNextBeat(); } } /// <summary> /// Time of next 32nd note. Usage: AudioSource.PlayScheduled(AtNextThirtySecond()) /// </summary> /// <returns>Time of next 32nd note as double</returns> public double AtNextThirtySecond() { return _nextThirtySecond; } /// <summary> /// Time of next 16th note triplet. Usage: AudioSource.PlayScheduled(AtNextSixteenth()) /// </summary> /// <returns>Time of next 16th note triplet as double</returns> public double AtNextSixteenthTriplet() { return _nextSixteenth; } /// <summary> /// Time of next 16th note. Usage: AudioSource.PlayScheduled(AtNextSixteenth()) /// </summary> /// <returns>Time of next 16th note as double</returns> public double AtNextSixteenth() { return _nextSixteenth; } /// <summary> /// Time of next 8th note triplet. Usage: AudioSource.PlayScheduled(AtNextEighth()) /// </summary> /// <returns>Time of next 8th note as double</returns> public double AtNextEighthTriplet() { return _nextEighthTriplet; } /// <summary> /// Time of next 8th note. Usage: AudioSource.PlayScheduled(AtNextEighth()) /// </summary> /// <returns>Time of next 8th note as double</returns> public double AtNextEighth() { return _nextEighth; } /// <summary> /// Time of next 1/4 note triplet. Usage: AudioSource.PlayScheduled(AtNextQuarter()) /// </summary> /// <returns>Time of next 1/4 note triplet as double</returns> public double AtNextQuarterTriplet() { return _nextQuarterTriplet; } /// <summary> /// Time of next 1/4 note. Usage: AudioSource.PlayScheduled(AtNextQuarter()) /// </summary> /// <returns>Time of next 1/4 note as double</returns> public double AtNextQuarter() { return _nextQuarter; } /// <summary> /// Time of next beat (1/4 note). Usage: AudioSource.PlayScheduled(AtNextBeat()) /// </summary> /// <returns>Time of next beat (1/4 note) as double</returns> public double AtNextBeat() { return _nextQuarter; } /// <summary> /// Time of next 1/2 note. Usage: AudioSource.PlayScheduled(AtNextHalf()) /// </summary> /// <returns>Time of next 1/2 note as double</returns> public double AtNextHalf() { return _nextHalf; } /// <summary> /// Time of next measure. Usage: AudioSource.PlayScheduled(AtNextMeasure()) /// </summary> /// <returns>Time of next measure as double</returns> public double AtNextMeasure() { return _nextMeasure; } /// <summary> /// Helper fucntions for timing things like tweens & animations to the beat clock /// </summary> /// <param name="beatTickValue"></param> /// <returns></returns> public float LengthOf(TickValue beatTickValue) { switch (beatTickValue) { case TickValue.ThirtySecond: return ThirtySecondLength(); case TickValue.SixteenthTriplet: return SixteenthTripletLength(); case TickValue.Sixteenth: return SixteenthLength(); case TickValue.EighthTriplet: return EighthTripletLength(); case TickValue.Eighth: return EighthLength(); case TickValue.QuarterTriplet: return QuarterTripletLength(); case TickValue.Quarter: return QuarterLength(); case TickValue.Half: return HalfLength(); case TickValue.Measure: return MeasureLength(); default: return BeatLength(); } } public float ThirtySecondLength() { return (float)_thirtySecondLength; } public float SixteenthTripletLength() { return (float)_sixteenthTripletLength; } public float SixteenthLength() { return (float)_sixteenthLength; } public float EighthTripletLength() { return (float)_eighthTripletLength; } public float EighthLength() { return (float)_eighthLength; } public float QuarterTripletLength() { return (float)_quarterTripletLength; } public float QuarterLength() { return (float)_quarterLength; } public float BeatLength() { return (float)_quarterLength; } public float HalfLength() { return (float)_halfLength; } public float MeasureLength() { return (float)_measureLength; } /// <summary> /// Helper functions for timing precise audio playback to the beatclock /// </summary> /// <param name="beatTickValue"></param> /// <returns>Returns length of the beat value</returns> public double LengthOfD(TickValue beatTickValue) { switch (beatTickValue) { case TickValue.ThirtySecond: return ThirtySecondLengthD(); case TickValue.SixteenthTriplet: return SixteenthTripletLengthD(); case TickValue.Sixteenth: return SixteenthLengthD(); case TickValue.EighthTriplet: return EighthTripletLengthD(); case TickValue.Eighth: return EighthLengthD(); case TickValue.QuarterTriplet: return QuarterTripletLengthD(); case TickValue.Quarter: return QuarterLengthD(); case TickValue.Half: return HalfLengthD(); case TickValue.Measure: return MeasureLengthD(); default: return BeatLengthD(); } } public double ThirtySecondLengthD() { return _thirtySecondLength; } public double SixteenthTripletLengthD() { return _sixteenthTripletLength; } public double SixteenthLengthD() { return _sixteenthLength; } public double EighthTripletLengthD() { return _eighthTripletLength; } public double EighthLengthD() { return _eighthLength; } public double QuarterTripletLengthD() { return _quarterTripletLength; } public double QuarterLengthD() { return _quarterLength; } public double BeatLengthD() { return _quarterLength; } public double HalfLengthD() { return _halfLength; } public double MeasureLengthD() { return _measureLength; } /// <summary> /// Benchmarking function for latency compensation /// </summary> void CalculateLatency() { _rollingAverageOfLatency = Average(latency); _latencyCompensation += _rollingAverageOfLatency; _latencyCounter = 0; _standardDeviationOfLatency = StdDev(latency); AverageLatency = (int)(1000 * (_rollingAverageOfLatency)); AverageJitter = (int)(1000 * (_standardDeviationOfLatency)); } /// <summary> /// Benchmarking function for latency compensation /// </summary> /// <param name="values">List of values to be averaged</param> /// <returns>Average of list of values</returns> double Average(double[] values) { int periodLength = 0; double total = 0.0; foreach (double value in values) { total += value; periodLength++; } return total / periodLength; } /// <summary> /// Benchmarking function for latency compensation /// </summary> /// <param name="values">List of values for which to calculate standard deviation</param> /// <returns>Standard deviation of list of values</returns> double StdDev(double[] values) { double mean = 0.0; double sum = 0.0; double stdDev = 0.0; int periodLength = latencyCalculationInterval; foreach (double value in values) { double delta = value - mean; mean += delta / periodLength; sum += delta * (value - mean); } stdDev = Math.Sqrt(sum / (periodLength - 1)); return stdDev; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; using Microsoft.Internal; namespace System.ComponentModel.Composition.Hosting { public partial class ApplicationCatalog : ComposablePartCatalog, ICompositionElement { private bool _isDisposed = false; private volatile AggregateCatalog _innerCatalog = null; private readonly object _thisLock = new object(); private ICompositionElement _definitionOrigin = null; private ReflectionContext _reflectionContext = null; public ApplicationCatalog() {} public ApplicationCatalog(ICompositionElement definitionOrigin) { Requires.NotNull(definitionOrigin, nameof(definitionOrigin)); _definitionOrigin = definitionOrigin; } public ApplicationCatalog(ReflectionContext reflectionContext) { Requires.NotNull(reflectionContext, nameof(reflectionContext)); _reflectionContext = reflectionContext; } public ApplicationCatalog(ReflectionContext reflectionContext, ICompositionElement definitionOrigin) { Requires.NotNull(reflectionContext, nameof(reflectionContext)); Requires.NotNull(definitionOrigin, nameof(definitionOrigin)); _reflectionContext = reflectionContext; _definitionOrigin = definitionOrigin; } internal ComposablePartCatalog CreateCatalog(string location, string pattern) { if(_reflectionContext != null) { return (_definitionOrigin != null) ? new DirectoryCatalog(location, pattern, _reflectionContext, _definitionOrigin) : new DirectoryCatalog(location, pattern, _reflectionContext); } return (_definitionOrigin != null) ? new DirectoryCatalog(location, pattern, _definitionOrigin) : new DirectoryCatalog(location, pattern); } // Note: // Creating a catalog does not cause change notifications to propagate, For some reason the DeploymentCatalog did, but that is a bug. // InnerCatalog is delay evaluated, from data supplied at construction time and so does not propagate change notifications private AggregateCatalog InnerCatalog { get { if(_innerCatalog == null) { lock(_thisLock) { if(_innerCatalog == null) { var location = AppDomain.CurrentDomain.BaseDirectory; if(location == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } var catalogs = new List<ComposablePartCatalog>(); catalogs.Add(CreateCatalog(location, "*.exe")); catalogs.Add(CreateCatalog(location, "*.dll")); string relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath; if(!string.IsNullOrEmpty(relativeSearchPath)) { string[] probingPaths = relativeSearchPath.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries); foreach(var probingPath in probingPaths) { var path = Path.Combine(location, probingPath); if(Directory.Exists(path)) { catalogs.Add(CreateCatalog(path, "*.dll")); } } } var innerCatalog = new AggregateCatalog(catalogs); _innerCatalog = innerCatalog; } } } return _innerCatalog; } } protected override void Dispose(bool disposing) { try { if (!_isDisposed) { IDisposable innerCatalog = null; lock (_thisLock) { innerCatalog = _innerCatalog as IDisposable; _innerCatalog = null; _isDisposed = true; } if(innerCatalog != null) { innerCatalog.Dispose(); } } } finally { base.Dispose(disposing); } } public override IEnumerator<ComposablePartDefinition> GetEnumerator() { ThrowIfDisposed(); return InnerCatalog.GetEnumerator(); } /// <summary> /// Returns the export definitions that match the constraint defined by the specified definition. /// </summary> /// <param name="definition"> /// The <see cref="ImportDefinition"/> that defines the conditions of the /// <see cref="ExportDefinition"/> objects to return. /// </param> /// <returns> /// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the /// <see cref="ExportDefinition"/> objects and their associated /// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined /// by <paramref name="definition"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="definition"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="DirectoryCatalog"/> has been disposed of. /// </exception> public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition) { ThrowIfDisposed(); Requires.NotNull(definition, nameof(definition)); return InnerCatalog.GetExports(definition); } [DebuggerStepThrough] private void ThrowIfDisposed() { if (_isDisposed) { throw ExceptionBuilder.CreateObjectDisposed(this); } } private string GetDisplayName() { return string.Format(CultureInfo.CurrentCulture, "{0} (Path=\"{1}\") (PrivateProbingPath=\"{2}\")", // NOLOC GetType().Name, AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath); } /// <summary> /// Returns a string representation of the directory catalog. /// </summary> /// <returns> /// A <see cref="String"/> containing the string representation of the <see cref="DirectoryCatalog"/>. /// </returns> public override string ToString() { return GetDisplayName(); } /// <summary> /// Gets the display name of the ApplicationCatalog. /// </summary> /// <value> /// A <see cref="String"/> containing a human-readable display name of the <see cref="ApplicationCatalog"/>. /// </value> [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] string ICompositionElement.DisplayName { get { return GetDisplayName(); } } /// <summary> /// Gets the composition element from which the ApplicationCatalog originated. /// </summary> /// <value> /// This property always returns <see langword="null"/>. /// </value> [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] ICompositionElement ICompositionElement.Origin { get { return null; } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.ComponentModel; using System.Runtime.Caching; using System.Text; using System.Web.UI; using System.Web.UI.HtmlControls; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Caching; namespace Adxstudio.Xrm.Web.UI.WebControls { public enum TextCase { Mixed, Upper, Lower } /// <summary> /// The base class for all Reverse Turing Test challenges. /// </summary> public abstract class Captcha : System.Web.UI.WebControls.WebControl, INamingContainer { /// <summary> /// Stores the challenge ID associated for future requests. /// </summary> private HtmlInputHidden _hiddenData; /// <summary> /// Whether Authenticate has previously succeeded in this HttpRequest. /// </summary> private bool _authenticated; /// <summary> /// Backing store for Expiration. /// </summary> private int _expiration = 120; [Category("Data")] [Description("The name of the ObjectCacheElement used for configuring the caching services.")] [DefaultValue(null)] public string ObjectCacheName { get; set; } /// <summary> /// Gets or sets the duration of time (seconds) a user has before the challenge expires. /// </summary> /// <value> /// The duration of time (seconds) a user has before the challenge expires. /// </value> [Category("Behavior")] [Description("The duration of time (seconds) a user has before the challenge expires.")] [DefaultValue(120)] public int SecondsBeforeExpiration { get { return _expiration; } set { _expiration = value; } } private TextCase _challengeTextCase = TextCase.Lower; /// <summary> /// Gets or sets the <see cref="TextCase"/> of the generated challenge. /// </summary> [Category("Behavior")] [Description("The text case of the challenge (e.g., upper-case).")] [DefaultValue(TextCase.Lower)] public TextCase ChallengeTextCase { get { return _challengeTextCase; } set { _challengeTextCase = value; } } private int _challengeTextLength = 5; /// <summary> /// Gets or sets the text length of the challenge. /// </summary> /// <value> /// The text length of the challenge. /// </value> [Category("Behavior")] [Description("The text length of the challenge.")] [DefaultValue(5)] public int ChallengeTextLength { get { return _challengeTextLength; } set { _challengeTextLength = value; } } /// <summary> /// Selects a word to use in an image. /// </summary> /// <returns> /// The word to use in the challenge. /// </returns> protected virtual string ChooseWord() { var word = new RandomStringGenerator(ChallengeTextCase); return word.Build(ChallengeTextLength); } /// <summary> /// Creates the hidden field control that stores the challenge ID. /// </summary> protected override void CreateChildControls() { _hiddenData = new HtmlInputHidden { EnableViewState = false }; Controls.Add(_hiddenData); base.CreateChildControls(); } /// <summary> /// Generates a new image and fills in the dynamic image and hidden field appropriately. /// </summary> /// <param name="e">Ignored.</param> protected sealed override void OnPreRender(EventArgs e) { // Gets a word for the challenge, associates it with a new ID, and stores it for the client. var content = ChooseWord(); var id = Guid.NewGuid(); SetChallengeText(id, content, DateTime.Now.AddSeconds(_expiration), ObjectCacheName); _hiddenData.Value = id.ToString(); // Generates a challenge based on the selected word/phrase. RenderChallenge(id, content); base.OnPreRender(e); } /// <summary> /// Gets the challenge text for a particular ID. /// </summary> /// <param name="challengeId">The ID of the challenge text to retrieve.</param> /// <returns> /// The text associated with the specified ID; null if no text exists. /// </returns> public static string GetChallengeText(Guid challengeId, string objectCacheName) { return ObjectCacheManager.GetInstance(objectCacheName).Get(GetChallengeCacheKey(challengeId)) as string; } internal static string GetChallengeCacheKey(Guid challengeId) { return "captcha:{0}".FormatWith(challengeId); } /// <summary> /// Sets the challenge text for a particular ID. /// </summary> /// <param name="challengeId">The ID of the challenge with which this text should be associated.</param> /// <param name="text">The text to store along with the challenge ID.</param> /// <param name="expiration">The expiration date fo the challenge.</param> internal static void SetChallengeText(Guid challengeId, string text, DateTime expiration, string objectCacheName) { var key = GetChallengeCacheKey(challengeId); if (text == null) { ObjectCacheManager.GetInstance(objectCacheName).Remove(key); } else { var policy = new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable }; ObjectCacheManager.GetInstance(objectCacheName).Insert(key, text, policy); } } /// <summary> /// Authenticates user-supplied data against that retrieved using the challenge ID. /// </summary> /// <param name="userData">The user-supplied data.</param> /// <returns> /// Whether the user-supplied data matches that retrieved using the challenge ID. /// </returns> internal bool Authenticate(string userData) { // We want to allow multiple authentication requests within the same HTTP request, // so we can the result as a member variable of the class (non-static). if (_authenticated) { return true; } // If no authentication has happened previously, and if the user has supplied text, // and if the ID is stored correctly in the page, and if the user text matches the challenge text, // then set the challenge text, note that we've authenticated, and return true. Otherwise, failed authentication. if (!(string.IsNullOrEmpty(userData) || string.IsNullOrEmpty(_hiddenData.Value))) { try { var id = new Guid(_hiddenData.Value); var text = GetChallengeText(id, ObjectCacheName); if (text != null && string.Compare(userData, text) == 0) { _authenticated = true; SetChallengeText(id, null, DateTime.MinValue, ObjectCacheName); return true; } } catch (FormatException) { // Swallow the exception. } } return false; } /// <summary> /// Generates the challenge and presents it to the user. /// </summary> /// <param name="id">The ID of the challenge.</param> /// <param name="content">The content to render.</param> protected abstract void RenderChallenge(Guid id, string content); internal class RandomStringGenerator { private readonly string _characterSet; private readonly Random _random = new Random(); private const string UpperCaseCharacterSet = "ABCDEFGHJKMNPQRSTUVWXYZ"; private const string LowerCaseCharacterSet = "abcdefghjkmnpqrstuvwxyz"; private const string NumericCharacterSet = "23456789"; public RandomStringGenerator(TextCase textCase) : this(BuildCharacterSet(textCase)) { } public RandomStringGenerator(string characterSet) { _characterSet = characterSet; } public string CharacterSet { get { return _characterSet; } } public string Build(int length) { var randomString = new StringBuilder(length); for (var i = 0; i < length; i++) { randomString.Append(GetRandomCharacter()); } return randomString.ToString(); } protected char GetRandomCharacter() { return CharacterSet[_random.Next(CharacterSet.Length)]; } private static string BuildCharacterSet(TextCase textCase) { var characterSet = new StringBuilder(NumericCharacterSet); if (textCase == TextCase.Upper || textCase == TextCase.Mixed) { characterSet.Append(UpperCaseCharacterSet); } if (textCase == TextCase.Lower || textCase == TextCase.Mixed) { characterSet.Append(LowerCaseCharacterSet); } return characterSet.ToString(); } } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Provisioning.OnPrem.AsyncWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// // PodcastActions.cs // // Authors: // Gabriel Burt <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Gtk; using Migo.Syndication; using Banshee.Base; using Banshee.Query; using Banshee.Sources; using Banshee.Library; using Banshee.Playlist; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.ServiceStack; using Banshee.Widgets; using Banshee.Gui.Dialogs; using Banshee.Gui.Widgets; using Banshee.Gui; using Banshee.Podcasting; using Banshee.Podcasting.Data; namespace Banshee.Podcasting.Gui { public class PodcastActions : BansheeActionGroup { private uint actions_id; private DatabaseSource last_source; public PodcastActions (PodcastSource source) : base (ServiceManager.Get<InterfaceActionService> (), "Podcast") { AddImportant ( new ActionEntry ( "PodcastUpdateAllAction", Stock.Refresh, Catalog.GetString ("Check for New Episodes"), null,//"<control><shift>U", Catalog.GetString ("Refresh All Podcasts"), OnPodcastUpdateAll ), new ActionEntry ( "PodcastAddAction", Stock.Add, Catalog.GetString ("Subscribe to Podcast..."),"<control><shift>F", Catalog.GetString ("Subscribe to a new podcast"), OnPodcastAdd ) ); Add ( new ActionEntry("PodcastFeedPopupAction", null, String.Empty, null, null, OnFeedPopup), new ActionEntry ( "PodcastDeleteAction", Stock.Delete, Catalog.GetString ("Unsubscribe and Delete"), null, String.Empty, OnPodcastDelete ), new ActionEntry ( "PodcastUpdateFeedAction", Stock.Refresh, Catalog.GetString ("Check for New Episodes"), null, String.Empty, OnPodcastUpdate ), new ActionEntry ( "PodcastDownloadAllAction", Stock.Save, Catalog.GetString ("Download All Episodes"), null, String.Empty, OnPodcastDownloadAllEpisodes ), new ActionEntry ( "PodcastHomepageAction", Stock.JumpTo, Catalog.GetString ("Visit Podcast Homepage"), null, String.Empty, OnPodcastHomepage ), new ActionEntry ( "PodcastPropertiesAction", Stock.Properties, Catalog.GetString ("Properties"), null, String.Empty, OnPodcastProperties ), new ActionEntry ( "PodcastItemMarkNewAction", null, Catalog.GetString ("Mark as New"), null, String.Empty, OnPodcastItemMarkNew ), new ActionEntry ( "PodcastItemMarkOldAction", null, Catalog.GetString ("Mark as Old"), "y", String.Empty, OnPodcastItemMarkOld ), new ActionEntry ( "PodcastItemDownloadAction", Stock.Save, /* Translators: this is a verb used as a button name, not a noun*/ Catalog.GetString ("Download Podcast(s)"), "<control><shift>D", String.Empty, OnPodcastItemDownload ), new ActionEntry ( "PodcastItemCancelAction", Stock.Cancel, Catalog.GetString ("Cancel Download"), "<control><shift>C", String.Empty, OnPodcastItemCancel ), new ActionEntry ( "PodcastItemDeleteFileAction", Stock.Remove, Catalog.GetString ("Remove Downloaded File(s)"), null, String.Empty, OnPodcastItemDeleteFile ), new ActionEntry ( "PodcastItemLinkAction", Stock.JumpTo, Catalog.GetString ("Visit Website"), null, String.Empty, OnPodcastItemLink ), new ActionEntry ( "PodcastItemPropertiesAction", Stock.Properties, Catalog.GetString ("Properties"), null, String.Empty, OnPodcastItemProperties ) ); this["PodcastAddAction"].ShortLabel = Catalog.GetString ("Subscribe to Podcast"); actions_id = Actions.UIManager.AddUiFromResource ("GlobalUI.xml"); Actions.AddActionGroup (this); ServiceManager.SourceManager.ActiveSourceChanged += HandleActiveSourceChanged; OnSelectionChanged (null, null); } public override void Dispose () { Actions.UIManager.RemoveUi (actions_id); Actions.RemoveActionGroup (this); base.Dispose (); } #region State Event Handlers private void HandleActiveSourceChanged (SourceEventArgs args) { if (last_source != null) { foreach (IFilterListModel filter in last_source.AvailableFilters) { filter.Selection.Changed -= OnSelectionChanged; } last_source.TrackModel.Selection.Changed -= OnSelectionChanged; last_source = null; } last_source = args.Source as DatabaseSource; if (IsPodcastSource) { if (last_source != null) { foreach (IFilterListModel filter in last_source.AvailableFilters) { filter.Selection.Changed += OnSelectionChanged; } last_source.TrackModel.Selection.Changed += OnSelectionChanged; } } else { last_source = null; } OnSelectionChanged (null, null); } private void OnSelectionChanged (object o, EventArgs args) { Banshee.Base.ThreadAssist.ProxyToMain (delegate { UpdateFeedActions (); UpdateItemActions (); }); } #endregion #region Utility Methods private DatabaseSource ActiveDbSource { get { return last_source; } } private bool IsPodcastSource { get { return ActiveDbSource != null && (ActiveDbSource is PodcastSource || ActiveDbSource.Parent is PodcastSource); } } public PodcastFeedModel ActiveFeedModel { get { if (ActiveDbSource == null) { return null; } else if (ActiveDbSource is PodcastSource) { return (ActiveDbSource as PodcastSource).FeedModel; } else { foreach (IFilterListModel filter in ActiveDbSource.AvailableFilters) { if (filter is PodcastFeedModel) { return filter as PodcastFeedModel; } } return null; } } } private void UpdateItemActions () { if (IsPodcastSource) { bool has_single_selection = ActiveDbSource.TrackModel.Selection.Count == 1; UpdateActions (true, has_single_selection, "PodcastItemLinkAction" ); } } private void UpdateFeedActions () { if (IsPodcastSource) { bool has_single_selection = ActiveFeedModel.Selection.Count == 1; bool all_selected = ActiveFeedModel.Selection.AllSelected; UpdateActions (true, has_single_selection && !all_selected, "PodcastHomepageAction", "PodcastPropertiesAction" ); UpdateActions (true, ActiveFeedModel.Selection.Count > 0 && !all_selected, "PodcastDeleteAction", "PodcastUpdateFeedAction", "PodcastDownloadAllAction" ); } } private void SubscribeToPodcast (Uri uri, FeedAutoDownload syncPreference) { FeedsManager.Instance.FeedManager.CreateFeed (uri.ToString (), syncPreference); } private IEnumerable<TrackInfo> GetSelectedItems () { return new List<TrackInfo> (ActiveDbSource.TrackModel.SelectedItems); } #endregion #region Action Handlers private void OnFeedPopup (object o, EventArgs args) { if (ActiveFeedModel.Selection.AllSelected) { ShowContextMenu ("/PodcastAllFeedsContextMenu"); } else { ShowContextMenu ("/PodcastFeedPopup"); } } private void RunSubscribeDialog () { Uri feedUri = null; FeedAutoDownload syncPreference; PodcastSubscribeDialog subscribeDialog = new PodcastSubscribeDialog (); ResponseType response = (ResponseType) subscribeDialog.Run (); syncPreference = subscribeDialog.SyncPreference; subscribeDialog.Destroy (); if (response == ResponseType.Ok) { string url = subscribeDialog.Url.Trim ().Trim ('/'); if (String.IsNullOrEmpty (subscribeDialog.Url)) { return; } if (!TryParseUrl (url, out feedUri)) { HigMessageDialog.RunHigMessageDialog ( null, DialogFlags.Modal, MessageType.Warning, ButtonsType.Ok, Catalog.GetString ("Invalid URL"), Catalog.GetString ("Podcast URL is invalid.") ); } else { SubscribeToPodcast (feedUri, syncPreference); } } } /*private void RunConfirmDeleteDialog (bool feed, int selCount, out bool delete, out bool deleteFiles) { delete = false; deleteFiles = false; string header = null; int plural = (feed | (selCount > 1)) ? 2 : 1; if (feed) { header = Catalog.GetPluralString ("Delete Podcast?","Delete Podcasts?", selCount); } else { header = Catalog.GetPluralString ("Delete episode?", "Delete episodes?", selCount); } HigMessageDialog md = new HigMessageDialog ( ServiceManager.Get<GtkElementsService> ("GtkElementsService").PrimaryWindow, DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.None, header, Catalog.GetPluralString ( "Would you like to delete the associated file?", "Would you like to delete the associated files?", plural ) ); md.AddButton (Stock.Cancel, ResponseType.Cancel, true); md.AddButton ( Catalog.GetPluralString ( "Keep File", "Keep Files", plural ), ResponseType.No, false ); md.AddButton (Stock.Delete, ResponseType.Yes, false); try { switch ((ResponseType)md.Run ()) { case ResponseType.Yes: deleteFiles = true; goto case ResponseType.No; case ResponseType.No: delete = true; break; } } finally { md.Destroy (); } }*/ private bool TryParseUrl (string url, out Uri uri) { uri = null; bool ret = false; try { uri = new Uri (url); if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) { ret = true; } } catch {} return ret; } /*private void OnFeedSelectionChangedHandler (object sender, EventArgs e) { lock (sync) { if (!disposed || disposing) { if (source.FeedModel.SelectedItems.Count == 0) { source.FeedModel.Selection.Select (0); } if (source.FeedModel.Selection.Contains (0)) { itemModel.FilterOnFeed (Feed.All); } else { itemModel.FilterOnFeeds (source.FeedModel.CopySelectedItems ()); } itemModel.Selection.Clear (); } } } private void OnPodcastItemRowActivatedHandler (object sender, RowActivatedArgs<PodcastItem> e) { lock (sync) { if (!disposed || disposing) { if (e.RowValue.Enclosure != null) { e.RowValue.New = false; ServiceManager.PlayerEngine.OpenPlay (e.RowValue); } } } }*/ private void OnPodcastAdd (object sender, EventArgs e) { RunSubscribeDialog (); } private void OnPodcastUpdate (object sender, EventArgs e) { foreach (Feed feed in ActiveFeedModel.SelectedItems) { feed.Update (); } } private void OnPodcastUpdateAll (object sender, EventArgs e) { foreach (Feed feed in Feed.Provider.FetchAll ()) { feed.Update (); } } private void OnPodcastDelete (object sender, EventArgs e) { foreach (Feed feed in ActiveFeedModel.SelectedItems) { if (feed != null) { feed.Delete (true); } } } private void OnPodcastDownloadAllEpisodes (object sender, EventArgs e) { foreach (Feed feed in ActiveFeedModel.SelectedItems) { if (feed != null) { foreach (FeedItem item in feed.Items) { item.Enclosure.AsyncDownload (); } } } } private void OnPodcastItemDeleteFile (object sender, EventArgs e) { foreach (PodcastTrackInfo pi in PodcastTrackInfo.From (GetSelectedItems ())) { if (pi.Enclosure.LocalPath != null) pi.Enclosure.DeleteFile (); } } private void OnPodcastHomepage (object sender, EventArgs e) { Feed feed = ActiveFeedModel.FocusedItem; if (feed != null && !String.IsNullOrEmpty (feed.Link)) { Banshee.Web.Browser.Open (feed.Link); } } private void OnPodcastProperties (object sender, EventArgs e) { Feed feed = ActiveFeedModel.FocusedItem; if (feed != null) { new PodcastFeedPropertiesDialog (feed).Run (); } } private void OnPodcastItemProperties (object sender, EventArgs e) { /*ReadOnlyCollection<PodcastItem> items = itemModel.CopySelectedItems (); if (items != null && items.Count == 1) { new PodcastPropertiesDialog (items[0]).Run (); } */ } private void OnPodcastItemMarkNew (object sender, EventArgs e) { MarkPodcastItemSelection (false); } private void OnPodcastItemMarkOld (object sender, EventArgs e) { MarkPodcastItemSelection (true); } private void MarkPodcastItemSelection (bool markRead) { TrackInfo new_selection_track = ActiveDbSource.TrackModel [ActiveDbSource.TrackModel.Selection.LastIndex + 1]; PodcastService.IgnoreItemChanges = true; bool any = false; foreach (PodcastTrackInfo track in PodcastTrackInfo.From (GetSelectedItems ())) { if (track.Item.IsRead != markRead) { track.Item.IsRead = markRead; track.Item.Save (); if (track.Item.IsRead ^ track.Track.PlayCount > 0) { track.Track.PlayCount = track.Item.IsRead ? 1 : 0; track.Track.Save (false); } any = true; } } PodcastService.IgnoreItemChanges = false; if (any) { ActiveDbSource.Reload (); // If we just removed all of the selected items from our view, we should select the // item after the last removed item if (ActiveDbSource.TrackModel.Selection.Count == 0 && new_selection_track != null) { int new_i = ActiveDbSource.TrackModel.IndexOf (new_selection_track); if (new_i != -1) { ActiveDbSource.TrackModel.Selection.Clear (false); ActiveDbSource.TrackModel.Selection.FocusedIndex = new_i; ActiveDbSource.TrackModel.Selection.Select (new_i); } } } } private void OnPodcastItemCancel (object sender, EventArgs e) { /* if (!disposed || disposing) { ReadOnlyCollection<PodcastItem> items = itemModel.CopySelectedItems (); if (items != null) { foreach (PodcastItem pi in items) { pi.Enclosure.CancelAsyncDownload (); } } }*/ } private void OnPodcastItemDownload (object sender, EventArgs e) { foreach (PodcastTrackInfo pi in PodcastTrackInfo.From (GetSelectedItems ())) { pi.Enclosure.AsyncDownload (); } } private void OnPodcastItemLink (object sender, EventArgs e) { PodcastTrackInfo track = PodcastTrackInfo.From (ActiveDbSource.TrackModel.FocusedItem); if (track != null && !String.IsNullOrEmpty (track.Item.Link)) { Banshee.Web.Browser.Open (track.Item.Link); } } #endregion } }
using DotNet.HighStock.Attributes; using DotNet.HighStock.Enums; using DotNet.HighStock.Helpers; using System; using System.Drawing; namespace DotNet.HighStock.Options { /// <summary> /// <p>The X axis or category axis. Normally this is the horizontal axis, though if the chart is inverted this is the vertical axis. In case of multiple axes, the xAxis node is an array of configuration objects.</p> <p>See <a class='internal' href='#axis.object'>the Axis object</a> for programmatic access to the axis.</p> /// </summary> public class XAxis { /// <summary> /// Whether to allow decimals in this axis' ticks. When counting integers, like persons or hits on a web page, decimals must be avoided in the axis tick labels. /// Default: true /// </summary> public bool? AllowDecimals { get; set; } /// <summary> /// When using an alternate grid color, a band is painted across the plot area between every other grid line. /// </summary> public Color? AlternateGridColor { get; set; } /// <summary> /// <p>If categories are present for the xAxis, names are used instead of numbers for that axis. Since Highstock 3.0, categories can also be extracted by giving each point a <a href='#series.data'>name</a> and setting axis <a href='#xAxis.type'>type</a> to <code>'category'</code>.</p><p>Example:<pre>categories: ['Apples', 'Bananas', 'Oranges']</pre> Defaults to <code>null</code></p> /// </summary> public string[] Categories { get; set; } /// <summary> /// The highest allowed value for automatically computed axis extremes. /// </summary> public Number? Ceiling { get; set; } /// <summary> /// For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default string representations used for each unit. For an overview of the replacement codes, see dateFormat. Defaults to:<pre>{ millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y'}</pre> /// </summary> public DateTimeLabel DateTimeLabelFormats { get; set; } /// <summary> /// Whether to force the axis to end on a tick. Use this option with the <code>maxPadding</code> option to control the axis end. /// Default: false /// </summary> public bool? EndOnTick { get; set; } /// <summary> /// Event handlers for the axis. /// </summary> public XAxisEvents Events { get; set; } /// <summary> /// The lowest allowed value for automatically computed axis extremes. /// Default: null /// </summary> public Number? Floor { get; set; } /// <summary> /// Color of the grid lines extending the ticks across the plot area. /// Default: #C0C0C0 /// </summary> public Color? GridLineColor { get; set; } /// <summary> /// The dash or dot style of the grid lines. For possible values, see <a href='http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highstock.com/tree/master/samples/highstock/plotoptions/series-dashstyle-all/'>this demonstration</a>. /// Default: Solid /// </summary> public DashStyles? GridLineDashStyle { get; set; } /// <summary> /// The width of the grid lines extending the ticks across the plot area. /// Default: 0 /// </summary> public Number? GridLineWidth { get; set; } /// <summary> /// The Z index of the grid lines. /// Default: 1 /// </summary> public Number? GridZIndex { get; set; } /// <summary> /// An id for the axis. This can be used after render time to get a pointer to the axis object through <code>chart.get()</code>. /// </summary> public string Id { get; set; } /// <summary> /// The axis labels show the number or category for each tick. /// </summary> public XAxisLabels Labels { get; set; } /// <summary> /// The color of the line marking the axis itself. /// Default: #C0D0E0 /// </summary> public Color? LineColor { get; set; } /// <summary> /// The width of the line marking the axis itself. /// Default: 1 /// </summary> public Number? LineWidth { get; set; } /// <summary> /// Index of another axis that this axis is linked to. When an axis is linked to a master axis, it will take the same extremes as the master, but as assigned by min or max or by setExtremes. It can be used to show additional info, or to ease reading the chart by duplicating the scales. /// </summary> public Number? LinkedTo { get; set; } /// <summary> /// The maximum value of the axis. If <code>null</code>, the max value is automatically calculated. If the <code>endOnTick</code> option is true, the <code>max</code> value might be rounded up. The actual maximum value is also influenced by <a class='internal' href='#chart'>chart.alignTicks</a>. /// </summary> public Number? Max { get; set; } /// <summary> /// Padding of the max value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the highest data value to appear on the edge of the plot area. When the axis' <code>max</code> option is set or a max extreme is set using <code>axis.setExtremes()</code>, the maxPadding will be ignored. /// Default: 0.01 /// </summary> public Number? MaxPadding { get; set; } [Obsolete("Deprecated. Renamed to <code>minRange</code> as of Highstock 2.2.")] public Number? MaxZoom { get; set; } /// <summary> /// The minimum value of the axis. If <code>null</code> the min value is automatically calculated. If the <code>startOnTick</code> option is true, the <code>min</code> value might be rounded down. /// </summary> public Number? Min { get; set; } /// <summary> /// Padding of the min value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the lowest data value to appear on the edge of the plot area. When the axis' <code>min</code> option is set or a min extreme is set using <code>axis.setExtremes()</code>, the minPadding will be ignored. /// Default: 0.01 /// </summary> public Number? MinPadding { get; set; } /// <summary> /// <p>The minimum range to display on this axis. The entire axis will not be allowed to span over a smaller interval than this. For example, for a datetime axis the main unit is milliseconds. If minRange is set to 3600000, you can't zoom in more than to one hour.</p> <p>The default minRange for the x axis is five times the smallest interval between any of the data points.</p> <p>On a logarithmic axis, the unit for the minimum range is the power. So a minRange of 1 means that the axis can be zoomed to 10-100, 100-1000, 1000-10000 etc.</p> /// </summary> public Number? MinRange { get; set; } /// <summary> /// The minimum tick interval allowed in axis values. For example on zooming in on an axis with daily data, this can be used to prevent the axis from showing hours. /// </summary> public Number? MinTickInterval { get; set; } /// <summary> /// Color of the minor, secondary grid lines. /// Default: #E0E0E0 /// </summary> public Color? MinorGridLineColor { get; set; } /// <summary> /// The dash or dot style of the minor grid lines. For possible values, see <a href='http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highstock.com/tree/master/samples/highstock/plotoptions/series-dashstyle-all/'>this demonstration</a>. /// Default: Solid /// </summary> public DashStyles? MinorGridLineDashStyle { get; set; } /// <summary> /// Width of the minor, secondary grid lines. /// Default: 1 /// </summary> public Number? MinorGridLineWidth { get; set; } /// <summary> /// Color for the minor tick marks. /// Default: #A0A0A0 /// </summary> public Color? MinorTickColor { get; set; } /// <summary> /// <p>Tick interval in scale units for the minor ticks. On a linear axis, if <code>'auto'</code>, the minor tick interval is calculated as a fifth of the tickInterval. If <code>null</code>, minor ticks are not shown.</p> <p>On logarithmic axes, the unit is the power of the value. For example, setting the minorTickInterval to 1 puts one tick on each of 0.1, 1, 10, 100 etc. Setting the minorTickInterval to 0.1 produces 9 ticks between 1 and 10, 10 and 100 etc. A minorTickInterval of 'auto' on a log axis results in a best guess, attempting to enter approximately 5 minor ticks between each major tick.</p><p>On axes using <a href='#xAxis.categories'>categories</a>, minor ticks are not supported.</p> /// </summary> public Number? MinorTickInterval { get; set; } /// <summary> /// The pixel length of the minor tick marks. /// Default: 2 /// </summary> public Number? MinorTickLength { get; set; } /// <summary> /// The position of the minor tick marks relative to the axis line. Can be one of <code>inside</code> and <code>outside</code>. /// Default: outside /// </summary> public TickPositions? MinorTickPosition { get; set; } /// <summary> /// The pixel width of the minor tick mark. /// Default: 0 /// </summary> public Number? MinorTickWidth { get; set; } /// <summary> /// The distance in pixels from the plot area to the axis line. A positive offset moves the axis with it's line, labels and ticks away from the plot area. This is typically used when two or more axes are displayed on the same side of the plot. /// Default: 0 /// </summary> public Number? Offset { get; set; } /// <summary> /// Whether to display the axis on the opposite side of the normal. The normal is on the left side for vertical axes and bottom for horizontal, so the opposite sides will be right and top respectively. This is typically used with dual or multiple axes. /// Default: false /// </summary> public bool? Opposite { get; set; } /// <summary> /// <p>An array of colored bands stretching across the plot area marking an interval on the axis.</p><p>In a gauge, a plot band on the Y axis (value axis) will stretch along the perimeter of the gauge.</p> /// </summary> public XAxisPlotBands[] PlotBands { get; set; } /// <summary> /// An array of lines stretching across the plot area, marking a specific value on one of the axes. /// </summary> public XAxisPlotLines[] PlotLines { get; set; } /// <summary> /// Whether to reverse the axis so that the highest number is closest to the origin. If the chart is inverted, the x axis is reversed by default. /// Default: false /// </summary> public bool? Reversed { get; set; } /// <summary> /// Whether to show the axis line and title when the axis has no data. /// Default: true /// </summary> public bool? ShowEmpty { get; set; } /// <summary> /// Whether to show the first tick label. /// Default: true /// </summary> public bool? ShowFirstLabel { get; set; } /// <summary> /// Whether to show the last tick label. /// Default: true /// </summary> public bool? ShowLastLabel { get; set; } /// <summary> /// For datetime axes, this decides where to put the tick between weeks. 0 = Sunday, 1 = Monday. /// Default: 1 /// </summary> public WeekDays? StartOfWeek { get; set; } /// <summary> /// Whether to force the axis to start on a tick. Use this option with the <code>maxPadding</code> option to control the axis start. /// Default: false /// </summary> public bool? StartOnTick { get; set; } /// <summary> /// Color for the main tick marks. /// Default: #C0D0E0 /// </summary> public Color? TickColor { get; set; } /// <summary> /// <p>The interval of the tick marks in axis units. When <code>null</code>, the tick interval is computed to approximately follow the <a href='#xAxis.tickPixelInterval'>tickPixelInterval</a> on linear and datetime axes. On categorized axes, a <code>null</code> tickInterval will default to 1, one category. Note that datetime axes are based on milliseconds, so for example an interval of one day is expressed as <code>24 * 3600 * 1000</code>.</p> <p>On logarithmic axes, the tickInterval is based on powers, so a tickInterval of 1 means one tick on each of 0.1, 1, 10, 100 etc. A tickInterval of 2 means a tick of 0.1, 10, 1000 etc. A tickInterval of 0.2 puts a tick on 0.1, 0.2, 0.4, 0.6, 0.8, 1, 2, 4, 6, 8, 10, 20, 40 etc.</p> /// </summary> public Number? TickInterval { get; set; } /// <summary> /// The pixel length of the main tick marks. /// Default: 10 /// </summary> public Number? TickLength { get; set; } /// <summary> /// If tickInterval is <code>null</code> this option sets the approximate pixel interval of the tick marks. Not applicable to categorized axis. Defaults to <code>72</code> for the Y axis and <code>100</code> forthe X axis. /// </summary> public Number? TickPixelInterval { get; set; } /// <summary> /// The position of the major tick marks relative to the axis line. Can be one of <code>inside</code> and <code>outside</code>. /// Default: outside /// </summary> public TickPositions? TickPosition { get; set; } /// <summary> /// A callback function returning array defining where the ticks are laid out on the axis. This overrides the default behaviour of <a href='#xAxis.tickPixelInterval'>tickPixelInterval</a> and <a href='#xAxis.tickInterval'>tickInterval</a>. /// </summary> [JsonFormatter("{0}")] public string TickPositioner { get; set; } /// <summary> /// An array defining where the ticks are laid out on the axis. This overrides the default behaviour of <a href='#xAxis.tickPixelInterval'>tickPixelInterval</a> and <a href='#xAxis.tickInterval'>tickInterval</a>. /// </summary> public Number?[] TickPositions { get; set; } /// <summary> /// The pixel width of the major tick marks. /// Default: 1 /// </summary> public Number? TickWidth { get; set; } /// <summary> /// For categorized axes only. If 'on' the tick mark is placed in the center of the category, if 'between' the tick mark is placed between categories. /// Default: between /// </summary> public Placement? TickmarkPlacement { get; set; } /// <summary> /// The axis title, showing next to the axis line. /// </summary> public XAxisTitle Title { get; set; } /// <summary> /// The type of axis. Can be one of <code>'linear'</code>, <code>'logarithmic'</code>, <code>'datetime'</code> or <code>'category'</code>. In a datetime axis, the numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days. In a category axis, the <a href='#series.data'>point names</a> of the chart's series are used for categories, if not a <a href='#xAxis.categories'>categories</a> array is defined. /// Default: linear /// </summary> public AxisTypes? Type { get; set; } } }
/* * Copyright 2013 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Globalization; using System.Text; using ZXing.Common; using ZXing.PDF417.Internal.EC; using ZXing.Reader; namespace ZXing.PDF417.Internal { /// <summary> /// /// </summary> /// <author>Guenther Grau</author> internal static class PDF417ScanningDecoder { private const int CODEWORD_SKEW_SIZE = 2; private const int MAX_ERRORS = 3; private const int MAX_EC_CODEWORDS = 512; private static readonly ErrorCorrection errorCorrection = new ErrorCorrection(); /// <summary> /// Decode the specified image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight, minCodewordWidth /// and maxCodewordWidth. /// TODO: don't pass in minCodewordWidth and maxCodewordWidth, pass in barcode columns for start and stop pattern /// columns. That way width can be deducted from the pattern column. /// This approach also allows to detect more details about the barcode, e.g. if a bar type (white or black) is wider /// than it should be. This can happen if the scanner used a bad blackpoint. /// </summary> /// <param name="image">Image.</param> /// <param name="imageTopLeft">Image top left.</param> /// <param name="imageBottomLeft">Image bottom left.</param> /// <param name="imageTopRight">Image top right.</param> /// <param name="imageBottomRight">Image bottom right.</param> /// <param name="minCodewordWidth">Minimum codeword width.</param> /// <param name="maxCodewordWidth">Max codeword width.</param> public static DecoderResult decode(BitMatrix image, ResultPoint imageTopLeft, ResultPoint imageBottomLeft, ResultPoint imageTopRight, ResultPoint imageBottomRight, int minCodewordWidth, int maxCodewordWidth) { BoundingBox boundingBox = BoundingBox.Create(image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight); if (boundingBox == null) return null; DetectionResultRowIndicatorColumn leftRowIndicatorColumn = null; DetectionResultRowIndicatorColumn rightRowIndicatorColumn = null; DetectionResult detectionResult = null; for (int i = 0; i < 2; i++) { if (imageTopLeft != null) { leftRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopLeft, true, minCodewordWidth, maxCodewordWidth); } if (imageTopRight != null) { rightRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopRight, false, minCodewordWidth, maxCodewordWidth); } detectionResult = merge(leftRowIndicatorColumn, rightRowIndicatorColumn); if (detectionResult == null) { // TODO Based on Owen's Comments in <see cref="ZXing.ReaderException"/>, this method has been modified to continue silently // if a barcode was not decoded where it was detected instead of throwing a new exception object. return null; } if (i == 0 && detectionResult.Box != null && (detectionResult.Box.MinY < boundingBox.MinY || detectionResult.Box.MaxY > boundingBox.MaxY)) { boundingBox = detectionResult.Box; } else { detectionResult.Box = boundingBox; break; } } int maxBarcodeColumn = detectionResult.ColumnCount + 1; detectionResult.DetectionResultColumns[0] = leftRowIndicatorColumn; detectionResult.DetectionResultColumns[maxBarcodeColumn] = rightRowIndicatorColumn; bool leftToRight = leftRowIndicatorColumn != null; for (int barcodeColumnCount = 1; barcodeColumnCount <= maxBarcodeColumn; barcodeColumnCount++) { int barcodeColumn = leftToRight ? barcodeColumnCount : maxBarcodeColumn - barcodeColumnCount; if (detectionResult.DetectionResultColumns[barcodeColumn] != null) { // This will be the case for the opposite row indicator column, which doesn't need to be decoded again. continue; } DetectionResultColumn detectionResultColumn; if (barcodeColumn == 0 || barcodeColumn == maxBarcodeColumn) { detectionResultColumn = new DetectionResultRowIndicatorColumn(boundingBox, barcodeColumn == 0); } else { detectionResultColumn = new DetectionResultColumn(boundingBox); } detectionResult.DetectionResultColumns[barcodeColumn] = detectionResultColumn; int startColumn = -1; int previousStartColumn = startColumn; // TODO start at a row for which we know the start position, then detect upwards and downwards from there. for (int imageRow = boundingBox.MinY; imageRow <= boundingBox.MaxY; imageRow++) { startColumn = getStartColumn(detectionResult, barcodeColumn, imageRow, leftToRight); if (startColumn < 0 || startColumn > boundingBox.MaxX) { if (previousStartColumn == -1) { continue; } startColumn = previousStartColumn; } Codeword codeword = detectCodeword(image, boundingBox.MinX, boundingBox.MaxX, leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth); if (codeword != null) { detectionResultColumn.setCodeword(imageRow, codeword); previousStartColumn = startColumn; minCodewordWidth = Math.Min(minCodewordWidth, codeword.Width); maxCodewordWidth = Math.Max(maxCodewordWidth, codeword.Width); } } } return createDecoderResult(detectionResult); } /// <summary> /// Merge the specified leftRowIndicatorColumn and rightRowIndicatorColumn. /// </summary> /// <param name="leftRowIndicatorColumn">Left row indicator column.</param> /// <param name="rightRowIndicatorColumn">Right row indicator column.</param> private static DetectionResult merge(DetectionResultRowIndicatorColumn leftRowIndicatorColumn, DetectionResultRowIndicatorColumn rightRowIndicatorColumn) { if (leftRowIndicatorColumn == null && rightRowIndicatorColumn == null) { return null; } BarcodeMetadata barcodeMetadata = getBarcodeMetadata(leftRowIndicatorColumn, rightRowIndicatorColumn); if (barcodeMetadata == null) { return null; } BoundingBox boundingBox = BoundingBox.merge(adjustBoundingBox(leftRowIndicatorColumn), adjustBoundingBox(rightRowIndicatorColumn)); return new DetectionResult(barcodeMetadata, boundingBox); } /// <summary> /// Adjusts the bounding box. /// </summary> /// <returns>The bounding box.</returns> /// <param name="rowIndicatorColumn">Row indicator column.</param> private static BoundingBox adjustBoundingBox(DetectionResultRowIndicatorColumn rowIndicatorColumn) { if (rowIndicatorColumn == null) { return null; } int[] rowHeights = rowIndicatorColumn.getRowHeights(); if (rowHeights == null) { return null; } int maxRowHeight = getMax(rowHeights); int missingStartRows = 0; foreach (int rowHeight in rowHeights) { missingStartRows += maxRowHeight - rowHeight; if (rowHeight > 0) { break; } } Codeword[] codewords = rowIndicatorColumn.Codewords; for (int row = 0; missingStartRows > 0 && codewords[row] == null; row++) { missingStartRows--; } int missingEndRows = 0; for (int row = rowHeights.Length - 1; row >= 0; row--) { missingEndRows += maxRowHeight - rowHeights[row]; if (rowHeights[row] > 0) { break; } } for (int row = codewords.Length - 1; missingEndRows > 0 && codewords[row] == null; row--) { missingEndRows--; } return rowIndicatorColumn.Box.addMissingRows(missingStartRows, missingEndRows, rowIndicatorColumn.IsLeft); } private static int getMax(int[] values) { int maxValue = -1; for (var index = values.Length - 1; index >= 0; index--) { maxValue = Math.Max(maxValue, values[index]); } return maxValue; } /// <summary> /// Gets the barcode metadata. /// </summary> /// <returns>The barcode metadata.</returns> /// <param name="leftRowIndicatorColumn">Left row indicator column.</param> /// <param name="rightRowIndicatorColumn">Right row indicator column.</param> private static BarcodeMetadata getBarcodeMetadata(DetectionResultRowIndicatorColumn leftRowIndicatorColumn, DetectionResultRowIndicatorColumn rightRowIndicatorColumn) { BarcodeMetadata leftBarcodeMetadata; if (leftRowIndicatorColumn == null || (leftBarcodeMetadata = leftRowIndicatorColumn.getBarcodeMetadata()) == null) { return rightRowIndicatorColumn == null ? null : rightRowIndicatorColumn.getBarcodeMetadata(); } BarcodeMetadata rightBarcodeMetadata; if (rightRowIndicatorColumn == null || (rightBarcodeMetadata = rightRowIndicatorColumn.getBarcodeMetadata()) == null) { return leftBarcodeMetadata; } if (leftBarcodeMetadata.ColumnCount != rightBarcodeMetadata.ColumnCount && leftBarcodeMetadata.ErrorCorrectionLevel != rightBarcodeMetadata.ErrorCorrectionLevel && leftBarcodeMetadata.RowCount != rightBarcodeMetadata.RowCount) { return null; } return leftBarcodeMetadata; } /// <summary> /// Gets the row indicator column. /// </summary> /// <returns>The row indicator column.</returns> /// <param name="image">Image.</param> /// <param name="boundingBox">Bounding box.</param> /// <param name="startPoint">Start point.</param> /// <param name="leftToRight">If set to <c>true</c> left to right.</param> /// <param name="minCodewordWidth">Minimum codeword width.</param> /// <param name="maxCodewordWidth">Max codeword width.</param> private static DetectionResultRowIndicatorColumn getRowIndicatorColumn(BitMatrix image, BoundingBox boundingBox, ResultPoint startPoint, bool leftToRight, int minCodewordWidth, int maxCodewordWidth) { DetectionResultRowIndicatorColumn rowIndicatorColumn = new DetectionResultRowIndicatorColumn(boundingBox, leftToRight); for (int i = 0; i < 2; i++) { int increment = i == 0 ? 1 : -1; int startColumn = (int) startPoint.X; for (int imageRow = (int) startPoint.Y; imageRow <= boundingBox.MaxY && imageRow >= boundingBox.MinY; imageRow += increment) { Codeword codeword = detectCodeword(image, 0, image.Width, leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth); if (codeword != null) { rowIndicatorColumn.setCodeword(imageRow, codeword); if (leftToRight) { startColumn = codeword.StartX; } else { startColumn = codeword.EndX; } } } } return rowIndicatorColumn; } /// <summary> /// Adjusts the codeword count. /// </summary> /// <param name="detectionResult">Detection result.</param> /// <param name="barcodeMatrix">Barcode matrix.</param> private static bool adjustCodewordCount(DetectionResult detectionResult, BarcodeValue[][] barcodeMatrix) { int[] numberOfCodewords = barcodeMatrix[0][1].getValue(); int calculatedNumberOfCodewords = detectionResult.ColumnCount* detectionResult.RowCount - getNumberOfECCodeWords(detectionResult.ErrorCorrectionLevel); if (numberOfCodewords.Length == 0) { if (calculatedNumberOfCodewords < 1 || calculatedNumberOfCodewords > PDF417Common.MAX_CODEWORDS_IN_BARCODE) { return false; } barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords); } else if (numberOfCodewords[0] != calculatedNumberOfCodewords) { // The calculated one is more reliable as it is derived from the row indicator columns barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords); } return true; } /// <summary> /// Creates the decoder result. /// </summary> /// <returns>The decoder result.</returns> /// <param name="detectionResult">Detection result.</param> private static DecoderResult createDecoderResult(DetectionResult detectionResult) { BarcodeValue[][] barcodeMatrix = createBarcodeMatrix(detectionResult); if (!adjustCodewordCount(detectionResult, barcodeMatrix)) { return null; } List<int> erasures = new List<int>(); int[] codewords = new int[detectionResult.RowCount*detectionResult.ColumnCount]; List<int[]> ambiguousIndexValuesList = new List<int[]>(); List<int> ambiguousIndexesList = new List<int>(); for (int row = 0; row < detectionResult.RowCount; row++) { for (int column = 0; column < detectionResult.ColumnCount; column++) { int[] values = barcodeMatrix[row][column + 1].getValue(); int codewordIndex = row*detectionResult.ColumnCount + column; if (values.Length == 0) { erasures.Add(codewordIndex); } else if (values.Length == 1) { codewords[codewordIndex] = values[0]; } else { ambiguousIndexesList.Add(codewordIndex); ambiguousIndexValuesList.Add(values); } } } int[][] ambiguousIndexValues = new int[ambiguousIndexValuesList.Count][]; for (int i = 0; i < ambiguousIndexValues.Length; i++) { ambiguousIndexValues[i] = ambiguousIndexValuesList[i]; } return createDecoderResultFromAmbiguousValues(detectionResult.ErrorCorrectionLevel, codewords, erasures.ToArray(), ambiguousIndexesList.ToArray(), ambiguousIndexValues); } /// <summary> /// This method deals with the fact, that the decoding process doesn't always yield a single most likely value. The /// current error correction implementation doesn't deal with erasures very well, so it's better to provide a value /// for these ambiguous codewords instead of treating it as an erasure. The problem is that we don't know which of /// the ambiguous values to choose. We try decode using the first value, and if that fails, we use another of the /// ambiguous values and try to decode again. This usually only happens on very hard to read and decode barcodes, /// so decoding the normal barcodes is not affected by this. /// </summary> /// <returns>The decoder result from ambiguous values.</returns> /// <param name="ecLevel">Ec level.</param> /// <param name="codewords">Codewords.</param> /// <param name="erasureArray">contains the indexes of erasures.</param> /// <param name="ambiguousIndexes">array with the indexes that have more than one most likely value.</param> /// <param name="ambiguousIndexValues">two dimensional array that contains the ambiguous values. The first dimension must /// be the same Length as the ambiguousIndexes array.</param> private static DecoderResult createDecoderResultFromAmbiguousValues(int ecLevel, int[] codewords, int[] erasureArray, int[] ambiguousIndexes, int[][] ambiguousIndexValues) { int[] ambiguousIndexCount = new int[ambiguousIndexes.Length]; int tries = 100; while (tries-- > 0) { for (int i = 0; i < ambiguousIndexCount.Length; i++) { codewords[ambiguousIndexes[i]] = ambiguousIndexValues[i][ambiguousIndexCount[i]]; } try { var result = decodeCodewords(codewords, ecLevel, erasureArray); if (result != null) return result; } catch (ZXingReaderException) { // ignored, should not happen } if (ambiguousIndexCount.Length == 0) { return null; } for (int i = 0; i < ambiguousIndexCount.Length; i++) { if (ambiguousIndexCount[i] < ambiguousIndexValues[i].Length - 1) { ambiguousIndexCount[i]++; break; } else { ambiguousIndexCount[i] = 0; if (i == ambiguousIndexCount.Length - 1) { return null; } } } } return null; } /// <summary> /// Creates the barcode matrix. /// </summary> /// <returns>The barcode matrix.</returns> /// <param name="detectionResult">Detection result.</param> private static BarcodeValue[][] createBarcodeMatrix(DetectionResult detectionResult) { // Manually setup Jagged Array in C# BarcodeValue[][] barcodeMatrix = new BarcodeValue[detectionResult.RowCount][]; for (int row = 0; row < barcodeMatrix.Length; row++) { barcodeMatrix[row] = new BarcodeValue[detectionResult.ColumnCount + 2]; for (int col = 0; col < barcodeMatrix[row].Length; col++) { barcodeMatrix[row][col] = new BarcodeValue(); } } int column = -1; foreach (DetectionResultColumn detectionResultColumn in detectionResult.getDetectionResultColumns()) { column++; if (detectionResultColumn == null) { continue; } foreach (Codeword codeword in detectionResultColumn.Codewords) { if (codeword == null || codeword.RowNumber == -1) { continue; } barcodeMatrix[codeword.RowNumber][column].setValue(codeword.Value); } } return barcodeMatrix; } /// <summary> /// Tests to see if the Barcode Column is Valid /// </summary> /// <returns><c>true</c>, if barcode column is valid, <c>false</c> otherwise.</returns> /// <param name="detectionResult">Detection result.</param> /// <param name="barcodeColumn">Barcode column.</param> private static bool isValidBarcodeColumn(DetectionResult detectionResult, int barcodeColumn) { return (barcodeColumn >= 0) && (barcodeColumn <= detectionResult.DetectionResultColumns.Length + 1); } /// <summary> /// Gets the start column. /// </summary> /// <returns>The start column.</returns> /// <param name="detectionResult">Detection result.</param> /// <param name="barcodeColumn">Barcode column.</param> /// <param name="imageRow">Image row.</param> /// <param name="leftToRight">If set to <c>true</c> left to right.</param> private static int getStartColumn(DetectionResult detectionResult, int barcodeColumn, int imageRow, bool leftToRight) { int offset = leftToRight ? 1 : -1; Codeword codeword = null; if (isValidBarcodeColumn(detectionResult, barcodeColumn - offset)) { codeword = detectionResult.DetectionResultColumns[barcodeColumn - offset].getCodeword(imageRow); } if (codeword != null) { return leftToRight ? codeword.EndX : codeword.StartX; } codeword = detectionResult.DetectionResultColumns[barcodeColumn].getCodewordNearby(imageRow); if (codeword != null) { return leftToRight ? codeword.StartX : codeword.EndX; } if (isValidBarcodeColumn(detectionResult, barcodeColumn - offset)) { codeword = detectionResult.DetectionResultColumns[barcodeColumn - offset].getCodewordNearby(imageRow); } if (codeword != null) { return leftToRight ? codeword.EndX : codeword.StartX; } int skippedColumns = 0; while (isValidBarcodeColumn(detectionResult, barcodeColumn - offset)) { barcodeColumn -= offset; foreach (Codeword previousRowCodeword in detectionResult.DetectionResultColumns[barcodeColumn].Codewords) { if (previousRowCodeword != null) { return (leftToRight ? previousRowCodeword.EndX : previousRowCodeword.StartX) + offset* skippedColumns* (previousRowCodeword.EndX - previousRowCodeword.StartX); } } skippedColumns++; } return leftToRight ? detectionResult.Box.MinX : detectionResult.Box.MaxX; } /// <summary> /// Detects the codeword. /// </summary> /// <returns>The codeword.</returns> /// <param name="image">Image.</param> /// <param name="minColumn">Minimum column.</param> /// <param name="maxColumn">Max column.</param> /// <param name="leftToRight">If set to <c>true</c> left to right.</param> /// <param name="startColumn">Start column.</param> /// <param name="imageRow">Image row.</param> /// <param name="minCodewordWidth">Minimum codeword width.</param> /// <param name="maxCodewordWidth">Max codeword width.</param> private static Codeword detectCodeword(BitMatrix image, int minColumn, int maxColumn, bool leftToRight, int startColumn, int imageRow, int minCodewordWidth, int maxCodewordWidth) { startColumn = adjustCodewordStartColumn(image, minColumn, maxColumn, leftToRight, startColumn, imageRow); // we usually know fairly exact now how long a codeword is. We should provide minimum and maximum expected length // and try to adjust the read pixels, e.g. remove single pixel errors or try to cut off exceeding pixels. // min and maxCodewordWidth should not be used as they are calculated for the whole barcode an can be inaccurate // for the current position int[] moduleBitCount = getModuleBitCount(image, minColumn, maxColumn, leftToRight, startColumn, imageRow); if (moduleBitCount == null) { return null; } int endColumn; int codewordBitCount = PDF417Common.getBitCountSum(moduleBitCount); if (leftToRight) { endColumn = startColumn + codewordBitCount; } else { for (int i = 0; i < (moduleBitCount.Length >> 1); i++) { int tmpCount = moduleBitCount[i]; moduleBitCount[i] = moduleBitCount[moduleBitCount.Length - 1 - i]; moduleBitCount[moduleBitCount.Length - 1 - i] = tmpCount; } endColumn = startColumn; startColumn = endColumn - codewordBitCount; } // TODO implement check for width and correction of black and white bars // use start (and maybe stop pattern) to determine if blackbars are wider than white bars. If so, adjust. // should probably done only for codewords with a lot more than 17 bits. // The following fixes 10-1.png, which has wide black bars and small white bars // for (int i = 0; i < moduleBitCount.Length; i++) { // if (i % 2 == 0) { // moduleBitCount[i]--; // } else { // moduleBitCount[i]++; // } // } // We could also use the width of surrounding codewords for more accurate results, but this seems // sufficient for now if (!checkCodewordSkew(codewordBitCount, minCodewordWidth, maxCodewordWidth)) { // We could try to use the startX and endX position of the codeword in the same column in the previous row, // create the bit count from it and normalize it to 8. This would help with single pixel errors. return null; } int decodedValue = PDF417CodewordDecoder.getDecodedValue(moduleBitCount); int codeword = PDF417Common.getCodeword(decodedValue); if (codeword == -1) { return null; } return new Codeword(startColumn, endColumn, getCodewordBucketNumber(decodedValue), codeword); } /// <summary> /// Gets the module bit count. /// </summary> /// <returns>The module bit count.</returns> /// <param name="image">Image.</param> /// <param name="minColumn">Minimum column.</param> /// <param name="maxColumn">Max column.</param> /// <param name="leftToRight">If set to <c>true</c> left to right.</param> /// <param name="startColumn">Start column.</param> /// <param name="imageRow">Image row.</param> private static int[] getModuleBitCount(BitMatrix image, int minColumn, int maxColumn, bool leftToRight, int startColumn, int imageRow) { int imageColumn = startColumn; int[] moduleBitCount = new int[8]; int moduleNumber = 0; int increment = leftToRight ? 1 : -1; bool previousPixelValue = leftToRight; while (((leftToRight && imageColumn < maxColumn) || (!leftToRight && imageColumn >= minColumn)) && moduleNumber < moduleBitCount.Length) { if (image[imageColumn, imageRow] == previousPixelValue) { moduleBitCount[moduleNumber]++; imageColumn += increment; } else { moduleNumber++; previousPixelValue = !previousPixelValue; } } if (moduleNumber == moduleBitCount.Length || (((leftToRight && imageColumn == maxColumn) || (!leftToRight && imageColumn == minColumn)) && moduleNumber == moduleBitCount.Length - 1)) { return moduleBitCount; } return null; } /// <summary> /// Gets the number of EC code words. /// </summary> /// <returns>The number of EC code words.</returns> /// <param name="barcodeECLevel">Barcode EC level.</param> private static int getNumberOfECCodeWords(int barcodeECLevel) { return 2 << barcodeECLevel; } /// <summary> /// Adjusts the codeword start column. /// </summary> /// <returns>The codeword start column.</returns> /// <param name="image">Image.</param> /// <param name="minColumn">Minimum column.</param> /// <param name="maxColumn">Max column.</param> /// <param name="leftToRight">If set to <c>true</c> left to right.</param> /// <param name="codewordStartColumn">Codeword start column.</param> /// <param name="imageRow">Image row.</param> private static int adjustCodewordStartColumn(BitMatrix image, int minColumn, int maxColumn, bool leftToRight, int codewordStartColumn, int imageRow) { int correctedStartColumn = codewordStartColumn; int increment = leftToRight ? -1 : 1; // there should be no black pixels before the start column. If there are, then we need to start earlier. for (int i = 0; i < 2; i++) { while (((leftToRight && correctedStartColumn >= minColumn) || (!leftToRight && correctedStartColumn < maxColumn)) && leftToRight == image[correctedStartColumn, imageRow]) { if (Math.Abs(codewordStartColumn - correctedStartColumn) > CODEWORD_SKEW_SIZE) { return codewordStartColumn; } correctedStartColumn += increment; } increment = -increment; leftToRight = !leftToRight; } return correctedStartColumn; } /// <summary> /// Checks the codeword for any skew. /// </summary> /// <returns><c>true</c>, if codeword is within the skew, <c>false</c> otherwise.</returns> /// <param name="codewordSize">Codeword size.</param> /// <param name="minCodewordWidth">Minimum codeword width.</param> /// <param name="maxCodewordWidth">Max codeword width.</param> private static bool checkCodewordSkew(int codewordSize, int minCodewordWidth, int maxCodewordWidth) { return minCodewordWidth - CODEWORD_SKEW_SIZE <= codewordSize && codewordSize <= maxCodewordWidth + CODEWORD_SKEW_SIZE; } /// <summary> /// Decodes the codewords. /// </summary> /// <returns>The codewords.</returns> /// <param name="codewords">Codewords.</param> /// <param name="ecLevel">Ec level.</param> /// <param name="erasures">Erasures.</param> private static DecoderResult decodeCodewords(int[] codewords, int ecLevel, int[] erasures) { if (codewords.Length == 0) { return null; } int numECCodewords = 1 << (ecLevel + 1); int correctedErrorsCount = correctErrors(codewords, erasures, numECCodewords); if (correctedErrorsCount < 0) { return null; } if (!verifyCodewordCount(codewords, numECCodewords)) { return null; } // Decode the codewords DecoderResult decoderResult = DecodedBitStreamParser.decode(codewords, ecLevel.ToString()); if (decoderResult != null) { decoderResult.ErrorsCorrected = correctedErrorsCount; decoderResult.Erasures = erasures.Length; } return decoderResult; } /// <summary> /// Given data and error-correction codewords received, possibly corrupted by errors, attempts to /// correct the errors in-place. /// </summary> /// <returns>The errors.</returns> /// <param name="codewords">data and error correction codewords.</param> /// <param name="erasures">positions of any known erasures.</param> /// <param name="numECCodewords">number of error correction codewords that are available in codewords.</param> private static int correctErrors(int[] codewords, int[] erasures, int numECCodewords) { if (erasures != null && erasures.Length > numECCodewords/2 + MAX_ERRORS || numECCodewords < 0 || numECCodewords > MAX_EC_CODEWORDS) { // Too many errors or EC Codewords is corrupted return -1; } int errorCount; if (!errorCorrection.decode(codewords, numECCodewords, erasures, out errorCount)) { return -1; } return errorCount; } /// <summary> /// Verifies that all is well with the the codeword array. /// </summary> /// <param name="codewords">Codewords.</param> /// <param name="numECCodewords">Number EC codewords.</param> private static bool verifyCodewordCount(int[] codewords, int numECCodewords) { if (codewords.Length < 4) { // Codeword array size should be at least 4 allowing for // Count CW, At least one Data CW, Error Correction CW, Error Correction CW return false; } // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad // codewords, but excluding the number of error correction codewords. int numberOfCodewords = codewords[0]; if (numberOfCodewords > codewords.Length) { return false; } if (numberOfCodewords == 0) { // Reset to the Length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords) if (numECCodewords < codewords.Length) { codewords[0] = codewords.Length - numECCodewords; } else { return false; } } return true; } /// <summary> /// Gets the bit count for codeword. /// </summary> /// <returns>The bit count for codeword.</returns> /// <param name="codeword">Codeword.</param> private static int[] getBitCountForCodeword(int codeword) { int[] result = new int[8]; int previousValue = 0; int i = result.Length - 1; while (true) { if ((codeword & 0x1) != previousValue) { previousValue = codeword & 0x1; i--; if (i < 0) { break; } } result[i]++; codeword >>= 1; } return result; } /// <summary> /// Gets the codeword bucket number. /// </summary> /// <returns>The codeword bucket number.</returns> /// <param name="codeword">Codeword.</param> private static int getCodewordBucketNumber(int codeword) { return getCodewordBucketNumber(getBitCountForCodeword(codeword)); } /// <summary> /// Gets the codeword bucket number. /// </summary> /// <returns>The codeword bucket number.</returns> /// <param name="moduleBitCount">Module bit count.</param> private static int getCodewordBucketNumber(int[] moduleBitCount) { return (moduleBitCount[0] - moduleBitCount[2] + moduleBitCount[4] - moduleBitCount[6] + 9)%9; } /// <summary> /// Returns a <see cref="System.String"/> that represents the <see cref="ZXing.PDF417.Internal.BarcodeValue"/> jagged array. /// </summary> /// <returns>A <see cref="System.String"/> that represents the <see cref="ZXing.PDF417.Internal.BarcodeValue"/> jagged array.</returns> /// <param name="barcodeMatrix">Barcode matrix as a jagged array.</param> public static String ToString(BarcodeValue[][] barcodeMatrix) { StringBuilder formatter = new StringBuilder(); for (int row = 0; row < barcodeMatrix.Length; row++) { formatter.AppendFormat(CultureInfo.InvariantCulture, "Row {0,2}: ", row); for (int column = 0; column < barcodeMatrix[row].Length; column++) { BarcodeValue barcodeValue = barcodeMatrix[row][column]; int[] values = barcodeValue.getValue(); if (values.Length == 0) { formatter.Append(" "); } else { formatter.AppendFormat(CultureInfo.InvariantCulture, "{0,4}({1,2})", values[0], barcodeValue.getConfidence(values[0])); } } formatter.Append("\n"); } return formatter.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. using System.Collections.Generic; namespace System { public static class AppContext { [Flags] private enum SwitchValueState { HasFalseValue = 0x1, HasTrueValue = 0x2, HasLookedForOverride = 0x4, UnknownValue = 0x8 // Has no default and could not find an override } private static readonly Dictionary<string, SwitchValueState> s_switchMap = new Dictionary<string, SwitchValueState>(); static AppContext() { // Unloading event must happen before ProcessExit event AppDomain.CurrentDomain.ProcessExit += OnUnloading; AppDomain.CurrentDomain.ProcessExit += OnProcessExit; // populate the AppContext with the default set of values AppContextDefaultValues.PopulateDefaultValues(); } public static string BaseDirectory { get { // The value of APP_CONTEXT_BASE_DIRECTORY key has to be a string and it is not allowed to be any other type. // Otherwise the caller will get invalid cast exception return (string)AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") ?? AppDomain.CurrentDomain.BaseDirectory; } } public static string TargetFrameworkName { get { // Forward the value that is set on the current domain. return AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName; } } public static object GetData(string name) { return AppDomain.CurrentDomain.GetData(name); } public static void SetData(string name, object data) { AppDomain.CurrentDomain.SetData(name, data); } public static event UnhandledExceptionEventHandler UnhandledException { add { AppDomain.CurrentDomain.UnhandledException += value; } remove { AppDomain.CurrentDomain.UnhandledException -= value; } } public static event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException { add { AppDomain.CurrentDomain.FirstChanceException += value; } remove { AppDomain.CurrentDomain.FirstChanceException -= value; } } public static event System.EventHandler ProcessExit; internal static event System.EventHandler Unloading; private static void OnProcessExit(object sender, EventArgs e) { var processExit = ProcessExit; if (processExit != null) { processExit(null, EventArgs.Empty); } } private static void OnUnloading(object sender, EventArgs e) { var unloading = Unloading; if (unloading != null) { unloading(null, EventArgs.Empty); } } #region Switch APIs /// <summary> /// Try to get the value of the switch. /// </summary> /// <param name="switchName">The name of the switch</param> /// <param name="isEnabled">A variable where to place the value of the switch</param> /// <returns>A return value of true represents that the switch was set and <paramref name="isEnabled"/> contains the value of the switch</returns> public static bool TryGetSwitch(string switchName, out bool isEnabled) { if (switchName == null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName)); // By default, the switch is not enabled. isEnabled = false; SwitchValueState switchValue; lock (s_switchMap) { if (s_switchMap.TryGetValue(switchName, out switchValue)) { // The value is in the dictionary. // There are 3 cases here: // 1. The value of the switch is 'unknown'. This means that the switch name is not known to the system (either via defaults or checking overrides). // Example: This is the case when, during a servicing event, a switch is added to System.Xml which ships before mscorlib. The value of the switch // Will be unknown to mscorlib.dll and we want to prevent checking the overrides every time we check this switch // 2. The switch has a valid value AND we have read the overrides for it // Example: TryGetSwitch is called for a switch set via SetSwitch // 3. The switch has the default value and we need to check for overrides // Example: TryGetSwitch is called for the first time for a switch that has a default value // 1. The value is unknown if (switchValue == SwitchValueState.UnknownValue) { isEnabled = false; return false; } // We get the value of isEnabled from the value that we stored in the dictionary isEnabled = (switchValue & SwitchValueState.HasTrueValue) == SwitchValueState.HasTrueValue; // 2. The switch has a valid value AND we have checked for overrides if ((switchValue & SwitchValueState.HasLookedForOverride) == SwitchValueState.HasLookedForOverride) { return true; } // 3. The switch has a valid value, but we need to check for overrides. // Regardless of whether or not the switch has an override, we need to update the value to reflect // the fact that we checked for overrides. bool overrideValue; if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue)) { // we found an override! isEnabled = overrideValue; } // Update the switch in the dictionary to mark it as 'checked for override' s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; return true; } else { // The value is NOT in the dictionary // In this case we need to see if we have an override defined for the value. // There are 2 cases: // 1. The value has an override specified. In this case we need to add the value to the dictionary // and mark it as checked for overrides // Example: In a servicing event, System.Xml introduces a switch and an override is specified. // The value is not found in mscorlib (as System.Xml ships independent of mscorlib) // 2. The value does not have an override specified // In this case, we want to capture the fact that we looked for a value and found nothing by adding // an entry in the dictionary with the 'sentinel' value of 'SwitchValueState.UnknownValue'. // Example: This will prevent us from trying to find overrides for values that we don't have in the dictionary // 1. The value has an override specified. bool overrideValue; if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue)) { isEnabled = overrideValue; // Update the switch in the dictionary to mark it as 'checked for override' s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; return true; } // 2. The value does not have an override. s_switchMap[switchName] = SwitchValueState.UnknownValue; } } return false; // we did not find a value for the switch } /// <summary> /// Assign a switch a value /// </summary> /// <param name="switchName">The name of the switch</param> /// <param name="isEnabled">The value to assign</param> public static void SetSwitch(string switchName, bool isEnabled) { if (switchName == null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName)); SwitchValueState switchValue = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; lock (s_switchMap) { // Store the new value and the fact that we checked in the dictionary s_switchMap[switchName] = switchValue; } } /// <summary> /// This method is going to be called from the AppContextDefaultValues class when setting up the /// default values for the switches. !!!! This method is called during the static constructor so it does not /// take a lock !!!! If you are planning to use this outside of that, please ensure proper locking. /// </summary> internal static void DefineSwitchDefault(string switchName, bool isEnabled) { s_switchMap[switchName] = isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue; } #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.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.NetworkInformation; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.Test.Common { public class LoopbackServer { public static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> AllowAllCertificates = (_, __, ___, ____) => true; public class Options { public IPAddress Address { get; set; } = IPAddress.Loopback; public int ListenBacklog { get; set; } = 1; public bool UseSsl { get; set; } = false; public SslProtocols SslProtocols { get; set; } = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; } public static Task CreateServerAsync(Func<Socket, Uri, Task> funcAsync, Options options = null) { IPEndPoint ignored; return CreateServerAsync(funcAsync, out ignored, options); } public static Task CreateServerAsync(Func<Socket, Uri, Task> funcAsync, out IPEndPoint localEndPoint, Options options = null) { options = options ?? new Options(); try { var server = new Socket(options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); server.Bind(new IPEndPoint(options.Address, 0)); server.Listen(options.ListenBacklog); localEndPoint = (IPEndPoint)server.LocalEndPoint; string host = options.Address.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{localEndPoint.Address}]" : localEndPoint.Address.ToString(); var url = new Uri($"{(options.UseSsl ? "https" : "http")}://{host}:{localEndPoint.Port}/"); return funcAsync(server, url).ContinueWith(t => { server.Dispose(); t.GetAwaiter().GetResult(); }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); } catch (Exception e) { localEndPoint = null; return Task.FromException(e); } } public static string DefaultHttpResponse => $"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 0\r\n\r\n"; public static IPAddress GetIPv6LinkLocalAddress() => NetworkInterface .GetAllNetworkInterfaces() .SelectMany(i => i.GetIPProperties().UnicastAddresses) .Select(a => a.Address) .Where(a => a.IsIPv6LinkLocal) .FirstOrDefault(); public static Task<List<string>> ReadRequestAndSendResponseAsync(Socket server, string response = null, Options options = null) { return AcceptSocketAsync(server, (s, stream, reader, writer) => ReadWriteAcceptedAsync(s, reader, writer, response), options); } public static async Task<List<string>> ReadWriteAcceptedAsync(Socket s, StreamReader reader, StreamWriter writer, string response = null) { // Read request line and headers. Skip any request body. var lines = new List<string>(); string line; while (!string.IsNullOrEmpty(line = await reader.ReadLineAsync().ConfigureAwait(false))) { lines.Add(line); } await writer.WriteAsync(response ?? DefaultHttpResponse).ConfigureAwait(false); s.Shutdown(SocketShutdown.Send); return lines; } public static async Task<List<string>> AcceptSocketAsync(Socket server, Func<Socket, Stream, StreamReader, StreamWriter, Task<List<string>>> funcAsync, Options options = null) { options = options ?? new Options(); using (Socket s = await AcceptAsyncApm(server).ConfigureAwait(false)) // TODO: Issue #17690 { Stream stream = new NetworkStream(s, ownsSocket: false); if (options.UseSsl) { var sslStream = new SslStream(stream, false, delegate { return true; }); using (var cert = Configuration.Certificates.GetServerCertificate()) { await sslStream.AuthenticateAsServerAsync( cert, clientCertificateRequired: true, // allowed but not required enabledSslProtocols: options.SslProtocols, checkCertificateRevocation: false).ConfigureAwait(false); } stream = sslStream; } using (var reader = new StreamReader(stream, Encoding.ASCII)) using (var writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true }) { return await funcAsync(s, stream, reader, writer).ConfigureAwait(false); } } } public enum TransferType { None = 0, ContentLength, Chunked } public enum TransferError { None = 0, ContentLengthTooLarge, ChunkSizeTooLarge, MissingChunkTerminator } public static Task StartTransferTypeAndErrorServer( TransferType transferType, TransferError transferError, out IPEndPoint localEndPoint) { return CreateServerAsync((server, url) => AcceptSocketAsync(server, async (client, stream, reader, writer) => { // Read past request headers. string line; while (!string.IsNullOrEmpty(line = reader.ReadLine())) ; // Determine response transfer headers. string transferHeader = null; string content = "This is some response content."; if (transferType == TransferType.ContentLength) { transferHeader = transferError == TransferError.ContentLengthTooLarge ? $"Content-Length: {content.Length + 42}\r\n" : $"Content-Length: {content.Length}\r\n"; } else if (transferType == TransferType.Chunked) { transferHeader = "Transfer-Encoding: chunked\r\n"; } // Write response header await writer.WriteAsync("HTTP/1.1 200 OK\r\n").ConfigureAwait(false); await writer.WriteAsync($"Date: {DateTimeOffset.UtcNow:R}\r\n").ConfigureAwait(false); await writer.WriteAsync("Content-Type: text/plain\r\n").ConfigureAwait(false); if (!string.IsNullOrEmpty(transferHeader)) { await writer.WriteAsync(transferHeader).ConfigureAwait(false); } await writer.WriteAsync("\r\n").ConfigureAwait(false); // Write response body if (transferType == TransferType.Chunked) { string chunkSizeInHex = string.Format( "{0:x}\r\n", content.Length + (transferError == TransferError.ChunkSizeTooLarge ? 42 : 0)); await writer.WriteAsync(chunkSizeInHex).ConfigureAwait(false); await writer.WriteAsync($"{content}\r\n").ConfigureAwait(false); if (transferError != TransferError.MissingChunkTerminator) { await writer.WriteAsync("0\r\n\r\n").ConfigureAwait(false); } } else { await writer.WriteAsync($"{content}\r\n").ConfigureAwait(false); } client.Shutdown(SocketShutdown.Both); return null; }), out localEndPoint); } private static Task<Socket> AcceptAsyncApm(Socket socket) { var tcs = new TaskCompletionSource<Socket>(socket); socket.BeginAccept(null, 0, iar => { var innerTcs = (TaskCompletionSource<Socket>)iar.AsyncState; try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndAccept(iar)); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } } }
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Linq; using System.Reflection; using System.Collections.Generic; using System.Security.Cryptography; using UnityEngine.AssetGraph; using V1=AssetBundleGraph; namespace UnityEngine.AssetGraph.DataModel.Version2 { /// <summary> /// Node data. /// </summary> [Serializable] public class NodeData { [System.Serializable] public class NodeInstance : SerializedInstance<Node> { public NodeInstance() : base() {} public NodeInstance(NodeInstance instance): base(instance) {} public NodeInstance(Node obj) : base(obj) {} } [SerializeField] private string m_name; [SerializeField] private string m_id; [SerializeField] private float m_x; [SerializeField] private float m_y; [SerializeField] private NodeInstance m_nodeInstance; [SerializeField] private List<ConnectionPointData> m_inputPoints; [SerializeField] private List<ConnectionPointData> m_outputPoints; private bool m_nodeNeedsRevisit; /* * Properties */ public bool NeedsRevisit { get { return m_nodeNeedsRevisit; } set { m_nodeNeedsRevisit = value; } } public string Name { get { return m_name; } set { m_name = value; } } public string Id { get { return m_id; } } public NodeInstance Operation { get { return m_nodeInstance; } } public float X { get { return m_x; } set { m_x = value; } } public float Y { get { return m_y; } set { m_y = value; } } public List<ConnectionPointData> InputPoints { get { return m_inputPoints; } } public List<ConnectionPointData> OutputPoints { get { return m_outputPoints; } } /// <summary> /// Create new node from GUI. /// </summary> /// <param name="name">Name.</param> /// <param name="node">Node.</param> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> public NodeData(string name, Node node, float x, float y) { m_id = Guid.NewGuid().ToString(); m_name = name; m_x = x; m_y = y; m_nodeInstance = new NodeInstance(node); m_nodeNeedsRevisit = false; m_inputPoints = new List<ConnectionPointData>(); m_outputPoints = new List<ConnectionPointData>(); m_nodeInstance.Object.Initialize(this); } public NodeData(NodeData node, bool keepId = false) { m_name = node.m_name; m_x = node.m_x; m_y = node.m_y; m_nodeNeedsRevisit = false; m_inputPoints = new List<ConnectionPointData>(); m_outputPoints = new List<ConnectionPointData>(); if(keepId) { m_id = node.m_id; node.InputPoints.ForEach(p => m_inputPoints.Add(new ConnectionPointData(p))); node.OutputPoints.ForEach(p => m_outputPoints.Add(new ConnectionPointData(p))); m_nodeInstance = new NodeInstance(node.m_nodeInstance); } else { m_id = Guid.NewGuid().ToString(); Node n = node.m_nodeInstance.Object.Clone(this); m_nodeInstance = new NodeInstance(n); } } public NodeData(V1.NodeData v1) { //TODO: m_id = v1.Id; m_name = v1.Name; m_x = v1.X; m_y = v1.Y; m_nodeNeedsRevisit = false; m_inputPoints = new List<ConnectionPointData>(); m_outputPoints = new List<ConnectionPointData>(); foreach(var input in v1.InputPoints) { m_inputPoints.Add(new ConnectionPointData(input)); } foreach(var output in v1.OutputPoints) { m_outputPoints.Add(new ConnectionPointData(output)); } Node n = CreateNodeFromV1NodeData(v1, this); m_nodeInstance = new NodeInstance(n); } public NodeData Duplicate (bool keepId = false) { return new NodeData(this, keepId); } public ConnectionPointData AddInputPoint(string label) { var p = new ConnectionPointData(label, this, true); m_inputPoints.Add(p); return p; } public ConnectionPointData AddOutputPoint(string label) { var p = new ConnectionPointData(label, this, false); m_outputPoints.Add(p); return p; } public ConnectionPointData AddDefaultInputPoint() { var p = m_inputPoints.Find(v => v.Label == Settings.DEFAULT_INPUTPOINT_LABEL); if(null == p) { p = AddInputPoint(Settings.DEFAULT_INPUTPOINT_LABEL); } return p; } public ConnectionPointData AddDefaultOutputPoint() { var p = m_outputPoints.Find(v => v.Label == Settings.DEFAULT_OUTPUTPOINT_LABEL); if(null == p) { p = AddOutputPoint(Settings.DEFAULT_OUTPUTPOINT_LABEL); } return p; } public ConnectionPointData FindInputPoint(string id) { return m_inputPoints.Find(p => p.Id == id); } public ConnectionPointData FindOutputPoint(string id) { return m_outputPoints.Find(p => p.Id == id); } public ConnectionPointData FindConnectionPoint(string id) { var v = FindInputPoint(id); if(v != null) { return v; } return FindOutputPoint(id); } public bool Validate () { return m_nodeInstance.Object != null; } public void ResetInstance() { m_nodeInstance.Invalidate (); } public bool CompareIgnoreGUIChanges (NodeData rhs) { if( m_nodeInstance == null && rhs.m_nodeInstance != null || m_nodeInstance != null && rhs.m_nodeInstance == null ) { LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Node Type"); return false; } if(m_nodeInstance.ClassName != rhs.m_nodeInstance.ClassName) { LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Node Type"); return false; } if(m_nodeInstance.Data != rhs.m_nodeInstance.Data) { LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Node Variable"); return false; } if(m_inputPoints.Count != rhs.m_inputPoints.Count) { LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Input Count"); return false; } if(m_outputPoints.Count != rhs.m_outputPoints.Count) { LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Output Count"); return false; } foreach(var pin in m_inputPoints) { if(rhs.m_inputPoints.Find(x => pin.Id == x.Id) == null) { LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Input point not found"); return false; } } foreach(var pout in m_outputPoints) { if(rhs.m_outputPoints.Find(x => pout.Id == x.Id) == null) { LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Output point not found"); return false; } } return true; } public static Node CreateNodeFromV1NodeData(V1.NodeData v1, NodeData data) { NodeDataImporter imp = null; Node n = null; switch(v1.Kind) { case V1.NodeKind.LOADER_GUI: { var v = new Loader(); imp = v; n = v; } break; case V1.NodeKind.FILTER_GUI: { var v = new Filter(); imp = v; n = v; } break; case V1.NodeKind.IMPORTSETTING_GUI: { var v = new ImportSetting(); imp = v; n = v; } break; case V1.NodeKind.MODIFIER_GUI: { var v = new Modifier(); imp = v; n = v; } break; case V1.NodeKind.GROUPING_GUI: { var v = new Grouping(); imp = v; n = v; } break; case V1.NodeKind.PREFABBUILDER_GUI: { var v = new PrefabBuilder(); imp = v; n = v; } break; case V1.NodeKind.BUNDLECONFIG_GUI: { var v = new BundleConfigurator(); imp = v; n = v; } break; case V1.NodeKind.BUNDLEBUILDER_GUI: { var v = new BundleBuilder(); imp = v; n = v; } break; case V1.NodeKind.EXPORTER_GUI: { var v = new Exporter(); imp = v; n = v; } break; } n.Initialize(data); imp.Import(v1, data); return n; } } }
/* Copyright 2019 Esri 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 ESRI.ArcGIS; using ESRI.ArcGIS.ADF.CATIDs; using Schematic = ESRI.ArcGIS.Schematic; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.esriSystem; using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Windows.Forms; using CustomRulesCS; namespace CustomRulesPageCS { [ClassInterface(ClassInterfaceType.None)] [Guid(NodeReductionRulePropertyPage.GUID)] [ProgId(NodeReductionRulePropertyPage.PROGID)] public class NodeReductionRulePropertyPage : IComPropertyPage { // Register/unregister categories for this class #region "Component Category Registration" [System.Runtime.InteropServices.ComRegisterFunction()] public static void Register(string CLSID) { SchematicRulePropertyPages.Register(CLSID); } [System.Runtime.InteropServices.ComUnregisterFunction()] public static void Unregister(string CLSID) { SchematicRulePropertyPages.Unregister(CLSID); } #endregion public const string GUID = "F58F5916-3A99-49CF-9A7D-5EB97E7618FD"; public const string PROGID = "CustomRulesPageCS.NodeReductionRulePropertyPage"; private FrmNodeReductionRule m_form = new FrmNodeReductionRule(); // the custom form private NodeReductionRule m_myNodeReductionRule; // the custom rule private string m_title = "Node Reduction Rule C#"; // the form title private int m_priority = 0; // the IComPage priority #region IComPropertyPage Membres public int Activate() { if (m_form == null) m_form = new FrmNodeReductionRule(); return (int)m_form.Handle; } public bool Applies(ISet objects) { Schematic.ISchematicRule mySchematicRule; mySchematicRule = FindMyRule(objects); return (mySchematicRule != null); } public void Apply() { try { m_myNodeReductionRule.Description = m_form.TxtDescription.Text; } catch { } try { m_myNodeReductionRule.ReducedNodeClassName = m_form.cmbReducedNodeClass.SelectedItem.ToString(); } catch { } try { m_myNodeReductionRule.SuperpanLinkClassName = m_form.cmbTargetSuperspanClass.SelectedItem.ToString(); } catch { } try { m_myNodeReductionRule.KeepVertices = m_form.chkKeepVertices.Checked; } catch { } try { m_myNodeReductionRule.LengthAttributeName = m_form.cmbAttributeName.SelectedItem.ToString(); } catch { } try { m_myNodeReductionRule.LinkAttribute = m_form.chkLinkAttribute.Checked; } catch { } try { m_myNodeReductionRule.LinkAttributeName = m_form.txtLinkAttribute.Text; } catch { } m_form.IsDirty = false; } public void Cancel() { m_form.IsDirty = false; } public void Deactivate() { m_form.DiagramClass = null; m_form.Close(); } public int Height { get { return m_form.Height; } } public int get_HelpContextID(int controlID) { // TODO: return context ID if desired return 0; } public string HelpFile { get { return ""; } } public void Hide() { m_form.Hide(); } public bool IsPageDirty { get { return m_form.IsDirty; } } public IComPropertyPageSite PageSite { set { m_form.PageSite = value; } } public int Priority { get { return m_priority; } set { m_priority = value; } } public void SetObjects(ISet objects) { // Search for the custom rule object instance m_myNodeReductionRule = FindMyRule(objects); } public void Show() { Schematic.ISchematicDiagramClass diagramClass; diagramClass = ((Schematic.ISchematicRule)m_myNodeReductionRule).SchematicDiagramClass; if (diagramClass == null) return; m_form.DiagramClass = diagramClass; Schematic.ISchematicElementClass elementClass; Schematic.IEnumSchematicElementClass enumElementClass; enumElementClass = diagramClass.AssociatedSchematicElementClasses; m_form.cmbReducedNodeClass.Items.Clear(); m_form.cmbTargetSuperspanClass.Items.Clear(); m_form.cmbAttributeName.Items.Clear(); try { enumElementClass.Reset(); elementClass = enumElementClass.Next(); while (elementClass != null) { if (elementClass.SchematicElementType == ESRI.ArcGIS.Schematic.esriSchematicElementType.esriSchematicNodeType) m_form.cmbReducedNodeClass.Items.Add(elementClass.Name); else if (elementClass.SchematicElementType == ESRI.ArcGIS.Schematic.esriSchematicElementType.esriSchematicLinkType) { m_form.cmbTargetSuperspanClass.Items.Add(elementClass.Name); } elementClass = enumElementClass.Next(); } m_form.cmbAttributeName.Text = m_myNodeReductionRule.LengthAttributeName; m_form.TxtDescription.Text = m_myNodeReductionRule.Description; m_form.cmbReducedNodeClass.Text = m_myNodeReductionRule.ReducedNodeClassName; m_form.cmbTargetSuperspanClass.Text = m_myNodeReductionRule.SuperpanLinkClassName; m_form.chkKeepVertices.Checked = m_myNodeReductionRule.KeepVertices; m_form.chkLinkAttribute.Checked = m_myNodeReductionRule.LinkAttribute; m_form.txtLinkAttribute.Text = m_myNodeReductionRule.LinkAttributeName; m_form.IsDirty = false; SetVisibleControls(); } catch (System.Exception ex) { MessageBox.Show(ex.Message, "Unable to initialize property page", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void SetVisibleControls() { m_form.Visible = true; m_form.lblDescription.Visible = true; m_form.lblGroup.Visible = true; m_form.lblReducedNode.Visible = true; m_form.lblTargetSuperspan.Visible = true; m_form.lblAttributeName.Visible = true; m_form.cmbReducedNodeClass.Visible = true; m_form.cmbTargetSuperspanClass.Visible = true; m_form.chkKeepVertices.Visible = true; m_form.chkLinkAttribute.Visible = true; m_form.txtLinkAttribute.Visible = true; } public string Title { get { return m_title; } set { m_title = value; } } public int Width { get { return m_form.Width; } } #endregion ~NodeReductionRulePropertyPage() { m_form.DiagramClass = null; m_form = null; m_myNodeReductionRule = null; } // Find and return this rule from the passed in objects private NodeReductionRule FindMyRule(ESRI.ArcGIS.esriSystem.ISet Objectset) { if (Objectset.Count == 0) return null; Objectset.Reset(); object obj; obj = Objectset.Next(); while (obj != null) { if (obj is CustomRulesCS.NodeReductionRule) { break; } obj = Objectset.Next(); } return (NodeReductionRule)obj; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.Dynamic; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime.Binding { using Ast = Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; class MetaOldClass : MetaPythonObject, IPythonInvokable, IPythonGetable, IPythonOperable, IPythonConvertible { public MetaOldClass(Expression/*!*/ expression, BindingRestrictions/*!*/ restrictions, OldClass/*!*/ value) : base(expression, BindingRestrictions.Empty, value) { Assert.NotNull(value); } #region IPythonInvokable Members public DynamicMetaObject/*!*/ Invoke(PythonInvokeBinder/*!*/ pythonInvoke, Expression/*!*/ codeContext, DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args) { return MakeCallRule(pythonInvoke, codeContext, args); } #endregion #region IPythonGetable Members public DynamicMetaObject GetMember(PythonGetMemberBinder member, DynamicMetaObject codeContext) { // no codeContext filtering but avoid an extra site by handling this action directly return MakeGetMember(member, codeContext); } #endregion #region MetaObject Overrides public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) { return BindingHelpers.GenericInvokeMember(action, null, this, args); } public override DynamicMetaObject/*!*/ BindInvoke(InvokeBinder/*!*/ call, params DynamicMetaObject/*!*/[]/*!*/ args) { return MakeCallRule(call, AstUtils.Constant(PythonContext.GetPythonContext(call).SharedContext), args); } public override DynamicMetaObject/*!*/ BindCreateInstance(CreateInstanceBinder/*!*/ create, params DynamicMetaObject/*!*/[]/*!*/ args) { return MakeCallRule(create, AstUtils.Constant(PythonContext.GetPythonContext(create).SharedContext), args); } public override DynamicMetaObject/*!*/ BindGetMember(GetMemberBinder/*!*/ member) { return MakeGetMember(member, PythonContext.GetCodeContextMO(member)); } public override DynamicMetaObject/*!*/ BindSetMember(SetMemberBinder/*!*/ member, DynamicMetaObject/*!*/ value) { return MakeSetMember(member.Name, value); } public override DynamicMetaObject/*!*/ BindDeleteMember(DeleteMemberBinder/*!*/ member) { return MakeDeleteMember(member); } public override DynamicMetaObject BindConvert(ConvertBinder/*!*/ conversion) { return ConvertWorker(conversion, conversion.Type, conversion.Explicit ? ConversionResultKind.ExplicitCast : ConversionResultKind.ImplicitCast); } public DynamicMetaObject BindConvert(PythonConversionBinder binder) { return ConvertWorker(binder, binder.Type, binder.ResultKind); } public DynamicMetaObject ConvertWorker(DynamicMetaObjectBinder binder, Type toType, ConversionResultKind kind) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass Convert"); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass Convert"); if (toType.IsSubclassOf(typeof(Delegate))) { return MakeDelegateTarget(binder, toType, Restrict(typeof(OldClass))); } return FallbackConvert(binder); } public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() { foreach (object o in ((IPythonMembersList)Value).GetMemberNames(DefaultContext.Default)) { if (o is string) { yield return (string)o; } } } #endregion #region Calls private DynamicMetaObject/*!*/ MakeCallRule(DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext, DynamicMetaObject[] args) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass Invoke w/ " + args.Length + " args"); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass Invoke"); CallSignature signature = BindingHelpers.GetCallSignature(call); // TODO: If we know __init__ wasn't present we could construct the OldInstance directly. Expression[] exprArgs = new Expression[args.Length]; for (int i = 0; i < args.Length; i++) { exprArgs[i] = args[i].Expression; } ParameterExpression init = Ast.Variable(typeof(object), "init"); ParameterExpression instTmp = Ast.Variable(typeof(object), "inst"); DynamicMetaObject self = Restrict(typeof(OldClass)); return new DynamicMetaObject( Ast.Block( new ParameterExpression[] { init, instTmp }, Ast.Assign( instTmp, Ast.New( typeof(OldInstance).GetConstructor(new Type[] { typeof(CodeContext), typeof(OldClass) }), codeContext, self.Expression ) ), Ast.Condition( Expression.Not( Expression.TypeIs( Expression.Assign( init, Ast.Call( typeof(PythonOps).GetMethod("OldClassTryLookupInit"), self.Expression, instTmp ) ), typeof(OperationFailed) ) ), DynamicExpression.Dynamic( PythonContext.GetPythonContext(call).Invoke( signature ), typeof(object), ArrayUtils.Insert<Expression>(codeContext, init, exprArgs) ), NoInitCheckNoArgs(signature, self, args) ), instTmp ), self.Restrictions.Merge(BindingRestrictions.Combine(args)) ); } private static Expression NoInitCheckNoArgs(CallSignature signature, DynamicMetaObject self, DynamicMetaObject[] args) { int unusedCount = args.Length; Expression dictExpr = GetArgumentExpression(signature, ArgumentType.Dictionary, ref unusedCount, args); Expression listExpr = GetArgumentExpression(signature, ArgumentType.List, ref unusedCount, args); if (signature.IsSimple || unusedCount > 0) { if (args.Length > 0) { return Ast.Call( typeof(PythonOps).GetMethod("OldClassMakeCallError"), self.Expression ); } return AstUtils.Constant(null); } return Ast.Call( typeof(PythonOps).GetMethod("OldClassCheckCallError"), self.Expression, dictExpr, listExpr ); } private static Expression GetArgumentExpression(CallSignature signature, ArgumentType kind, ref int unusedCount, DynamicMetaObject/*!*/[]/*!*/ args) { int index = signature.IndexOf(kind); if (index != -1) { unusedCount--; return args[index].Expression; } return AstUtils.Constant(null); } public static object MakeCallError() { // Normally, if we have an __init__ method, the method binder detects signature mismatches. // This can happen when a class does not define __init__ and therefore does not take any arguments. // Beware that calls like F(*(), **{}) have 2 arguments but they're empty and so it should still // match against def F(). throw PythonOps.TypeError("this constructor takes no arguments"); } #endregion #region Member Access private DynamicMetaObject/*!*/ MakeSetMember(string/*!*/ name, DynamicMetaObject/*!*/ value) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass SetMember"); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass SetMember"); DynamicMetaObject self = Restrict(typeof(OldClass)); Expression call, valueExpr = AstUtils.Convert(value.Expression, typeof(object)); switch (name) { case "__bases__": call = Ast.Call( typeof(PythonOps).GetMethod("OldClassSetBases"), self.Expression, valueExpr ); break; case "__name__": call = Ast.Call( typeof(PythonOps).GetMethod("OldClassSetName"), self.Expression, valueExpr ); break; case "__dict__": call = Ast.Call( typeof(PythonOps).GetMethod("OldClassSetDictionary"), self.Expression, valueExpr ); break; default: call = Ast.Call( typeof(PythonOps).GetMethod("OldClassSetNameHelper"), self.Expression, AstUtils.Constant(name), valueExpr ); break; } return new DynamicMetaObject( call, self.Restrictions.Merge(value.Restrictions) ); } private DynamicMetaObject/*!*/ MakeDeleteMember(DeleteMemberBinder/*!*/ member) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass DeleteMember"); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass DeleteMember"); DynamicMetaObject self = Restrict(typeof(OldClass)); return new DynamicMetaObject( Ast.Call( typeof(PythonOps).GetMethod("OldClassDeleteMember"), AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext), self.Expression, AstUtils.Constant(member.Name) ), self.Restrictions ); } private DynamicMetaObject/*!*/ MakeGetMember(DynamicMetaObjectBinder/*!*/ member, DynamicMetaObject codeContext) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass GetMember"); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass GetMember"); DynamicMetaObject self = Restrict(typeof(OldClass)); Expression target; string memberName = GetGetMemberName(member); switch (memberName) { case "__dict__": target = Ast.Block( Ast.Call( typeof(PythonOps).GetMethod("OldClassDictionaryIsPublic"), self.Expression ), Ast.Call( typeof(PythonOps).GetMethod("OldClassGetDictionary"), self.Expression ) ); break; case "__bases__": target = Ast.Call( typeof(PythonOps).GetMethod("OldClassGetBaseClasses"), self.Expression ); break; case "__name__": target = Ast.Call( typeof(PythonOps).GetMethod("OldClassGetName"), self.Expression ); break; default: ParameterExpression tmp = Ast.Variable(typeof(object), "lookupVal"); return new DynamicMetaObject( Ast.Block( new ParameterExpression[] { tmp }, Ast.Condition( Expression.Not( Expression.TypeIs( Expression.Assign( tmp, Ast.Call( typeof(PythonOps).GetMethod("OldClassTryLookupValue"), AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext), self.Expression, AstUtils.Constant(memberName) ) ), typeof(OperationFailed) ) ), tmp, AstUtils.Convert( GetMemberFallback(this, member, codeContext).Expression, typeof(object) ) ) ), self.Restrictions ); } return new DynamicMetaObject( target, self.Restrictions ); } #endregion #region Helpers public new OldClass/*!*/ Value { get { return (OldClass)base.Value; } } #endregion #region IPythonOperable Members DynamicMetaObject IPythonOperable.BindOperation(PythonOperationBinder action, DynamicMetaObject[] args) { if (action.Operation == PythonOperationKind.IsCallable) { return new DynamicMetaObject( AstUtils.Constant(true), Restrictions.Merge(BindingRestrictions.GetTypeRestriction(Expression, typeof(OldClass))) ); } return null; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using SourceParkAPI.Areas.HelpPage.ModelDescriptions; using SourceParkAPI.Areas.HelpPage.Models; namespace SourceParkAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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; public struct VT { public short[,] short2darr; public short[, ,] short3darr; public short[,] short2darr_b; public short[, ,] short3darr_b; } public class CL { public short[,] short2darr = { { 0, 1 }, { 0, 0 } }; public short[, ,] short3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; public short[,] short2darr_b = { { 0, 49 }, { 0, 0 } }; public short[, ,] short3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; } public class shortMDArrTest { static short[,] short2darr = { { 0, 1 }, { 0, 0 } }; static short[, ,] short3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; static short[,] short2darr_b = { { 0, 49 }, { 0, 0 } }; static short[, ,] short3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; static short[][,] ja1 = new short[2][,]; static short[][, ,] ja2 = new short[2][, ,]; static short[][,] ja1_b = new short[2][,]; static short[][, ,] ja2_b = new short[2][, ,]; public static int Main() { bool pass = true; VT vt1; vt1.short2darr = new short[,] { { 0, 1 }, { 0, 0 } }; vt1.short3darr = new short[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; vt1.short2darr_b = new short[,] { { 0, 49 }, { 0, 0 } }; vt1.short3darr_b = new short[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; CL cl1 = new CL(); ja1[0] = new short[,] { { 0, 1 }, { 0, 0 } }; ja2[1] = new short[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; ja1_b[0] = new short[,] { { 0, 49 }, { 0, 0 } }; ja2_b[1] = new short[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; short result = 1; // 2D if (result != short2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.short2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.short2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja1[0][0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (result != short3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.short3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.short3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja2[1][1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToBool bool Bool_result = true; // 2D if (Bool_result != Convert.ToBoolean(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Bool_result != Convert.ToBoolean(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToByte tests byte Byte_result = 1; // 2D if (Byte_result != Convert.ToByte(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Byte_result != Convert.ToByte(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToDecimal tests decimal Decimal_result = 1; // 2D if (Decimal_result != Convert.ToDecimal(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Decimal_result != Convert.ToDecimal(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToDouble double Double_result = 1; // 2D if (Double_result != Convert.ToDouble(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Double_result != Convert.ToDouble(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToSingle float Single_result = 1; // 2D if (Single_result != Convert.ToSingle(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Single_result != Convert.ToSingle(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToInt32 tests int Int32_result = 1; // 2D if (Int32_result != Convert.ToInt32(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int32_result != Convert.ToInt32(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToInt64 tests long Int64_result = 1; // 2D if (Int64_result != Convert.ToInt64(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int64_result != Convert.ToInt64(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToSByte sbyte SByte_result = 1; // 2D if (SByte_result != Convert.ToSByte(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (SByte_result != Convert.ToSByte(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToUInt32 uint UInt32_result = 1; // 2D if (UInt32_result != Convert.ToUInt32(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt32_result != Convert.ToUInt32(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToUInt64 tests ulong UInt64_result = 1; // 2D if (UInt64_result != Convert.ToUInt64(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt64_result != Convert.ToUInt64(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToUInt16 tests ushort UInt16_result = 1; // 2D if (UInt16_result != Convert.ToUInt16(short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.short2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt16_result != Convert.ToUInt16(short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.short3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int16ToChar tests char Char_result = '1'; // 2D if (Char_result != Convert.ToChar(short2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("2darr[0, 1] is: {0}", short2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.short2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.short2darr_b[0, 1] is: {0}", vt1.short2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.short2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.short2darr_b[0, 1] is: {0}", cl1.short2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Char_result != Convert.ToChar(short3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("short3darr_b[1,0,1] is: {0}", short3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.short3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.short3darr_b[1,0,1] is: {0}", vt1.short3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.short3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.short3darr_b[1,0,1] is: {0}", cl1.short3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (!pass) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } };
using System; using System.Collections.Generic; using System.Text; using Sandbox.ModAPI; using Sandbox.Common; using Sandbox.Common.ObjectBuilders; using Sandbox.Common.Components; using Sandbox.Definitions; using Sandbox.ModAPI.Interfaces; using System.Reflection; namespace AirlockRKR { [MyEntityComponentDescriptor(typeof(MyObjectBuilder_TerminalBlock))] // [MyEntityComponentDescriptor(typeof(MyObjectBuilder_Beacon))] public class AirlockRKR : MyGameLogicComponent { static private bool Debugging = false; private Logger LOG = null; Sandbox.Common.ObjectBuilders.MyObjectBuilder_EntityBase m_objectBuilder = null; Control.Status progress = Control.Status.Standby; Dictionary<Sandbox.ModAPI.Ingame.IMySensorBlock, Boolean> sensorStatus = new Dictionary<Sandbox.ModAPI.Ingame.IMySensorBlock, bool>(); private long abortStartTimeStamp = 0L; public override void Close() { // MyAPIGateway.Utilities.MessageEntered -= Utilities_MessageEntered; } public override void Init(Sandbox.Common.ObjectBuilders.MyObjectBuilder_EntityBase objectBuilder) { Entity.NeedsUpdate |= MyEntityUpdateEnum.EACH_10TH_FRAME; m_objectBuilder = objectBuilder; if (Entity as IMyCubeBlock != null && Debugging) { IMyCubeBlock block = Entity as IMyCubeBlock; if (block.BlockDefinition.SubtypeName.Contains("AirlockRKR")) { LOG = new Logger("textPanel", Debugging); } } //if (Entity as Sandbox.ModAPI.IMyDoor == null) { // return; //} // IMyProgrammableBlock progBlock = Entity as IMyProgrammableBlock; //if (objectBuilder.SubtypeId.Equals("SmallProgrammableBlockRKR") || objectBuilder.SubtypeId.Equals("LargeProgrammableBlockRKR")) //{ //} // MyAPIGateway.Utilities.MessageEntered += Utilities_MessageEntered; } public override void MarkForClose() { } public override void UpdateAfterSimulation() { } public override void UpdateAfterSimulation10() { } public override void UpdateAfterSimulation100() { } public override void UpdateBeforeSimulation() { } public override void UpdateBeforeSimulation10() { if (Entity as IMyCubeBlock != null && Entity as Sandbox.ModAPI.Ingame.IMyTerminalBlock != null) { IMyCubeBlock block = Entity as IMyCubeBlock; Sandbox.ModAPI.Ingame.IMyGridTerminalSystem gridTerminal = getGridTerminal(Entity); if (block.BlockDefinition.SubtypeName.Contains("AirlockRKR") && gridTerminal != null && (Entity as IMyCubeBlock).IsWorking) { String name = (Entity as IMyTerminalBlock).CustomName; String[] nameSplit = name.Split('#'); if (nameSplit.Length == 2 && nameSplit[1] != null) { String configLCDName = nameSplit[1]; Config config = new ConfigReader(gridTerminal, Entity as Sandbox.ModAPI.Ingame.IMyTerminalBlock, configLCDName).readConfig(); if (config.isStatusPanelValid() && !Debugging) { LOG = new Logger(config.statusPanel); } //MyAPIGateway.Utilities.ShowNotification(config.isStatusPanelValid() ? "status Panel gefunden" : "kein status Panel", 10000, MyFontEnum.Red); if (LOG != null && !Debugging && config.isStatusPanelValid()) { LOG.Clear(config.statusPanel); LOG.log(config.statusPanel, "Uhrzeit: " + DateTime.Now.ToLongTimeString(), ErrorSeverity.Notice); LOG.log(config.statusPanel, "Konfigurationspanel: " + configLCDName, ErrorSeverity.Notice); } else if (LOG != null && Debugging && gridTerminal != null) { LOG.Clear(gridTerminal); LOG.log(gridTerminal, "Uhrzeit: " + DateTime.Now.ToLongTimeString(), ErrorSeverity.Notice); LOG.log(gridTerminal, "Konfigurationspanel: " + configLCDName, ErrorSeverity.Notice); LOG.log(gridTerminal, "Progress: " + this.progress.ToString() + "(" + this.progress.Equals(Control.Status.Standby) + ")", ErrorSeverity.Notice); } if (config.isValid()) { if (LOG != null && config.isStatusPanelValid()) { LOG.log(config.statusPanel, "Schleusendruck: " + Utils.getPressure(config.sluiceVents[0]) + "%", ErrorSeverity.Notice); } List<Control.Event> currentEvents = new List<Control.Event>(); if (this.abortStartTimeStamp != 0L && DateTime.Now.Ticks >= new DateTime(this.abortStartTimeStamp).AddMilliseconds(config.abortMilliseconds).Ticks) { currentEvents.Add(Control.Event.AbortTimerDown); } currentEvents.AddList(Utils.getSensorStatusChanges(this.sensorStatus, config)); if (LOG != null && Debugging && gridTerminal != null) { foreach (Control.Event currentEvent in currentEvents) { LOG.log(gridTerminal, currentEvent.ToString(), ErrorSeverity.Error); } LOG.log(gridTerminal, "Doors1 " + Utils.isOneDoorOpen(config.doors1), ErrorSeverity.Notice); LOG.log(gridTerminal, "Doors2 " + Utils.isOneDoorOpen(config.doors2), ErrorSeverity.Notice); } this.progress = Control.run(currentEvents, this.progress, config); if ((this.abortStartTimeStamp == 0L) && (this.progress.Equals(Control.Status.leaveProgress) || this.progress.Equals(Control.Status.leaveSchleuse) || this.progress.Equals(Control.Status.enterProgress) || this.progress.Equals(Control.Status.enterSchleuse))) { this.abortStartTimeStamp = DateTime.Now.Ticks; } else if (this.progress.Equals(Control.Status.leavePressurize) || this.progress.Equals(Control.Status.Standby) || this.progress.Equals(Control.Status.enterPressurize)) { this.abortStartTimeStamp = 0L; } } else { if (LOG != null && config.isStatusPanelValid()) { LOG.log(config.statusPanel, "Konfiguration ist " + (config.isValid() ? "" : "nicht ") + "valide", ErrorSeverity.Notice); LOG.log(config.statusPanel, "Doors1 " + (config.isDoors1Valid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(config.statusPanel, "Sensors1 " + (config.isSensors1Valid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(config.statusPanel, "SluiceVents " + (config.isSluiceVentsValid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(config.statusPanel, "SluiceSensors " + (config.isSluiceSensorsValid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(config.statusPanel, "Doors2 " + (config.isDoors2Valid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(config.statusPanel, "Sensors2 " + (config.isSensors2Valid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(config.statusPanel, "Vents " + (config.isVentsValid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(config.statusPanel, "Lights " + (config.lightsFound() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); } else if (LOG != null && Debugging && gridTerminal != null) { LOG.log(gridTerminal, "Konfiguration ist " + (config.isValid() ? "" : "nicht ") + "valide", ErrorSeverity.Notice); LOG.log(gridTerminal, "Doors1 " + (config.isDoors1Valid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(gridTerminal, "Doors2 " + (config.isDoors2Valid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(gridTerminal, "Vents " + (config.isVentsValid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(gridTerminal, "SluiceVents " + (config.isSluiceVentsValid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(gridTerminal, "Sensors1 " + (config.isSensors1Valid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(gridTerminal, "SluiceSensors " + (config.isSluiceSensorsValid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); LOG.log(gridTerminal, "Sensors2 " + (config.isSensors2Valid() ? "ok" : "nicht gefunden"), ErrorSeverity.Notice); } this.progress = Control.Status.Standby; this.abortStartTimeStamp = 0L; this.sensorStatus.Clear(); } } } else { this.progress = Control.Status.Standby; this.abortStartTimeStamp = 0L; this.sensorStatus.Clear(); } } } public override void UpdateBeforeSimulation100() { } public override void UpdateOnceBeforeFrame() { } public override Sandbox.Common.ObjectBuilders.MyObjectBuilder_EntityBase GetObjectBuilder(bool copy = false) { return m_objectBuilder; } public void listActions(Sandbox.ModAPI.Ingame.IMyTerminalBlock block, Logger log, Config config) { List<ITerminalAction> actions = new List<ITerminalAction>(); block.GetActions(actions); for (int i = 0; i < actions.Count; i++) { log.log(config.statusPanel, actions[i].Name.ToString() + "(" + actions[i].Id + ")", ErrorSeverity.Notice); } } public void listProperties(Sandbox.ModAPI.Ingame.IMyTerminalBlock block, Logger log, Config config) { List<ITerminalProperty> properties = new List<ITerminalProperty>(); block.GetProperties(properties); for (int i = 0; i < properties.Count; i++) { log.log(config.statusPanel, properties[i].Id, ErrorSeverity.Notice); } } public static Sandbox.ModAPI.Ingame.IMyGridTerminalSystem getGridTerminal(VRage.ModAPI.IMyEntity Entity) { return Sandbox.ModAPI.MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((Entity as IMyCubeBlock).CubeGrid); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Xunit; using System.Collections.Immutable; using Microsoft.DotNet.CodeFormatting.Rules; namespace Microsoft.DotNet.CodeFormatting.Tests { /// <summary> /// A test which runs all rules on a given piece of code /// </summary> public sealed class CombinationTest : CodeFormattingTestBase { private FormattingEngineImplementation _formattingEngine; public CombinationTest() { _formattingEngine = (FormattingEngineImplementation)FormattingEngine.Create(); _formattingEngine.CopyrightHeader = ImmutableArray.Create("// header"); _formattingEngine.AllowTables = true; _formattingEngine.FormatLogger = new EmptyFormatLogger(); _formattingEngine.PreprocessorConfigurations = ImmutableArray<string[]>.Empty; } private void DisableAllRules() { foreach (var rule in _formattingEngine.AllRules) { _formattingEngine.ToggleRuleEnabled(rule, enabled: false); } } private void ToggleRule(string name, bool enabled) { var rule = _formattingEngine.AllRules.Where(x => x.Name == name).Single(); _formattingEngine.ToggleRuleEnabled(rule, enabled); } protected override async Task<Document> RewriteDocumentAsync(Document document) { var solution = await _formattingEngine.FormatCoreAsync( document.Project.Solution, new[] { document.Id }, CancellationToken.None); return solution.GetDocument(document.Id); } [Fact] public void FieldUse() { var text = @" class C { int field; void M() { N(this.field); } }"; var expected = @" internal class C { private int _field; private void M() { N(_field); } }"; Verify(text, expected, runFormatter: false); } /// <summary> /// Ensure the engine respects the rule map /// </summary> [Fact] public void FieldOnly() { var text = @" class C { int field; void M() { N(this.field); } }"; var expected = @" class C { int _field; void M() { N(this._field); } }"; DisableAllRules(); ToggleRule(PrivateFieldNamingRule.Name, enabled: true); Verify(text, expected, runFormatter: false); } [Fact] public void FieldNameExcluded() { var text = @" class C { int field; void M() { N(this.field); } }"; var expected = @" internal class C { private int field; private void M() { N(field); } }"; ToggleRule(PrivateFieldNamingRule.Name, enabled: false); Verify(text, expected, runFormatter: false); } [Fact] public void FieldAssignment() { var text = @" class C { int field; void M() { this.field = 42; } }"; var expected = @" internal class C { private int _field; private void M() { _field = 42; } }"; Verify(text, expected, runFormatter: false); } [Fact] public void PreprocessorSymbolNotDefined() { var text = @" class C { #if DOG void M() { } #endif }"; var expected = @" internal class C { #if DOG void M() { } #endif }"; Verify(text, expected, runFormatter: false); } [Fact] public void PreprocessorSymbolDefined() { var text = @" internal class C { #if DOG internal void M() { } #endif }"; var expected = @" internal class C { #if DOG internal void M() { } #endif }"; _formattingEngine.PreprocessorConfigurations = ImmutableArray.CreateRange(new[] { new[] { "DOG" } }); Verify(text, expected, runFormatter: false); } [Fact] public void TableCode() { var text = @" class C { void G() { } #if !DOTNET_FORMATTER void M() { } #endif }"; var expected = @" internal class C { private void G() { } #if !DOTNET_FORMATTER void M() { } #endif }"; Verify(text, expected, runFormatter: false); } /// <summary> /// Make sure the code which deals with additional configurations respects the /// table exception. /// </summary> [Fact] public void TableCodeAndAdditionalConfiguration() { var text = @" class C { #if TEST void G(){ } #endif #if !DOTNET_FORMATTER void M() { } #endif }"; var expected = @" internal class C { #if TEST void G() { } #endif #if !DOTNET_FORMATTER void M() { } #endif }"; _formattingEngine.PreprocessorConfigurations = ImmutableArray.CreateRange(new[] { new[] { "TEST" } }); Verify(text, expected, runFormatter: false); } [Fact] public void WhenBlocks() { var source = @" internal class C { private void M() { try { if(x){ G(); } } catch(Exception e)when(H(e)) { } } }"; var expected = @" internal class C { private void M() { try { if (x) { G(); } } catch (Exception e) when (H(e)) { } } }"; Verify(source, expected, runFormatter: false); } [Fact] public void CSharpHeaderCorrectAfterMovingUsings() { var source = @" namespace Microsoft.Build.UnitTests { using System; using System.Reflection; public class Test { public void RequiredRuntimeAttribute() {} } }"; var expected = @" using System; using System.Reflection; namespace Microsoft.Build.UnitTests { public class Test { public void RequiredRuntimeAttribute() { } } }"; // Using location rule is off by default. ToggleRule(UsingLocationRule.Name, enabled: true); Verify(source, expected); } [Fact] public void Issue268() { var text = @" using System.Collections.Generic; internal class C { private void M<TValue>() { Dictionary<string, Stack<TValue>> dict = new Dictionary<string, Stack<TValue>>(); dict.TryGetValue(""key"", out Stack<TValue> stack); } }"; Verify(text, expected:text); } [Fact] public void Issue272() { var text = @" using System.Collections.Generic; internal class C { private object myVariable; private void M() { Dictionary<string, object> dict = new Dictionary<string, object>() { { ""key"", new object() } }; dict.TryGetValue(""key"", out object myVariable); this.myVariable = myVariable; } }"; var expected = @" using System.Collections.Generic; internal class C { private object _myVariable; private void M() { Dictionary<string, object> dict = new Dictionary<string, object>() { { ""key"", new object() } }; dict.TryGetValue(""key"", out object myVariable); _myVariable = myVariable; } }"; Verify(text, expected); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Security.Principal; using NUnit.Framework; namespace NUnit.TestData.TestFixtureTests { /// <summary> /// Classes used for testing NUnit /// </summary> [TestFixture] public class RegularFixtureWithOneTest { [Test] public void OneTest() { } } [TestFixture] public class NoDefaultCtorFixture { public NoDefaultCtorFixture(int index) { } [Test] public void OneTest() { } } [TestFixture(7,3)] public class FixtureWithArgsSupplied { public FixtureWithArgsSupplied(int x, int y) { } [Test] public void OneTest() { } } [TestFixture(7, 3)] [TestFixture(8, 4)] public class FixtureWithMultipleArgsSupplied { public FixtureWithMultipleArgsSupplied(int x, int y) { } [Test] public void OneTest() { } } [TestFixture] public class BadCtorFixture { public BadCtorFixture() { throw new Exception(); } [Test] public void OneTest() { } } [TestFixture] public class FixtureWithTestFixtureAttribute { [Test] public void SomeTest() { } } public class FixtureWithoutTestFixtureAttributeContainingTest { [Test] public void SomeTest() { } } public class FixtureWithoutTestFixtureAttributeContainingTestCase { [TestCase(42)] public void SomeTest(int x) { } } [TestFixture] public class FixtureWithParameterizedTestAndArgsSupplied { [TestCase(42, "abc")] public void SomeTest(int x, string y) { } } [TestFixture] public class FixtureWithParameterizedTestAndMultipleArgsSupplied { [TestCase(42, "abc")] [TestCase(24, "cba")] public void SomeTest(int x, string y) { } } public class FixtureWithoutTestFixtureAttributeContainingTestCaseSource { [TestCaseSource("data")] public void SomeTest(int x) { } } public class FixtureWithoutTestFixtureAttributeContainingTheory { [Theory] public void SomeTest(int x) { } } public static class StaticFixtureWithoutTestFixtureAttribute { [Test] public static void StaticTest() { } } [TestFixture] public class MultipleSetUpAttributes { [SetUp] public void Init1() { } [SetUp] public void Init2() { } [Test] public void OneTest() { } } [TestFixture] public class MultipleTearDownAttributes { [TearDown] public void Destroy1() { } [TearDown] public void Destroy2() { } [Test] public void OneTest() { } } [TestFixture] [Ignore("testing ignore a fixture")] public class FixtureUsingIgnoreAttribute { [Test] public void Success() { } public class SubFixture { [Test] public void Success() { } } } [TestFixture(Ignore = "testing ignore a fixture")] public class FixtureUsingIgnoreProperty { [Test] public void Success() { } } [TestFixture(IgnoreReason = "testing ignore a fixture")] public class FixtureUsingIgnoreReasonProperty { [Test] public void Success() { } } [TestFixture] public class OuterClass { [TestFixture] public class NestedTestFixture { [TestFixture] public class DoublyNestedTestFixture { [Test] public void Test() { } } } } [TestFixture] public abstract class AbstractTestFixture { [TearDown] public void Destroy1() { } [Test] public void SomeTest() { } } public class DerivedFromAbstractTestFixture : AbstractTestFixture { } [TestFixture] public class BaseClassTestFixture { [Test] public void Success() { } } public abstract class AbstractDerivedTestFixture : BaseClassTestFixture { [Test] public void Test() { } } public class DerivedFromAbstractDerivedTestFixture : AbstractDerivedTestFixture { } [TestFixture] public abstract class AbstractBaseFixtureWithAttribute { } [TestFixture] public abstract class AbstractDerivedFixtureWithSecondAttribute : AbstractBaseFixtureWithAttribute { } public class DoubleDerivedClassWithTwoInheritedAttributes : AbstractDerivedFixtureWithSecondAttribute { } [TestFixture] public class MultipleFixtureSetUpAttributes { [OneTimeSetUp] public void Init1() { } [OneTimeSetUp] public void Init2() { } [Test] public void OneTest() { } } [TestFixture] public class MultipleFixtureTearDownAttributes { [OneTimeTearDown] public void Destroy1() { } [OneTimeTearDown] public void Destroy2() { } [Test] public void OneTest() { } } // Base class used to ensure following classes // all have at least one test public class OneTestBase { [Test] public void OneTest() { } } [TestFixture] public class PrivateSetUp : OneTestBase { [SetUp] private void Setup() { } } [TestFixture] public class ProtectedSetUp : OneTestBase { [SetUp] protected void Setup() { } } [TestFixture] public class StaticSetUp : OneTestBase { [SetUp] public static void Setup() { } } [TestFixture] public class SetUpWithReturnValue : OneTestBase { [SetUp] public int Setup() { return 0; } } [TestFixture] public class SetUpWithParameters : OneTestBase { [SetUp] public void Setup(int j) { } } [TestFixture] public class PrivateTearDown : OneTestBase { [TearDown] private void Teardown() { } } [TestFixture] public class ProtectedTearDown : OneTestBase { [TearDown] protected void Teardown() { } } [TestFixture] public class StaticTearDown : OneTestBase { [SetUp] public static void TearDown() { } } [TestFixture] public class TearDownWithReturnValue : OneTestBase { [TearDown] public int Teardown() { return 0; } } [TestFixture] public class TearDownWithParameters : OneTestBase { [TearDown] public void Teardown(int j) { } } [TestFixture] public class PrivateFixtureSetUp : OneTestBase { [OneTimeSetUp] private void Setup() { } } [TestFixture] public class ProtectedFixtureSetUp : OneTestBase { [OneTimeSetUp] protected void Setup() { } } [TestFixture] public class StaticFixtureSetUp : OneTestBase { [OneTimeSetUp] public static void Setup() { } } [TestFixture] public class FixtureSetUpWithReturnValue : OneTestBase { [OneTimeSetUp] public int Setup() { return 0; } } [TestFixture] public class FixtureSetUpWithParameters : OneTestBase { [OneTimeSetUp] public void Setup(int j) { } } [TestFixture] public class PrivateFixtureTearDown : OneTestBase { [OneTimeTearDown] private void Teardown() { } } [TestFixture] public class ProtectedFixtureTearDown : OneTestBase { [OneTimeTearDown] protected void Teardown() { } } [TestFixture] public class StaticFixtureTearDown : OneTestBase { [OneTimeTearDown] public static void Teardown() { } } [TestFixture] public class FixtureTearDownWithReturnValue : OneTestBase { [OneTimeTearDown] public int Teardown() { return 0; } } [TestFixture] public class FixtureTearDownWithParameters : OneTestBase { [OneTimeTearDown] public void Teardown(int j) { } } [TestFixture] public class FixtureThatChangesTheCurrentPrincipal { [Test] public void ChangeCurrentPrincipal() { IIdentity identity = new GenericIdentity("NUnit"); GenericPrincipal principal = new GenericPrincipal( identity, new string[] { } ); System.Threading.Thread.CurrentPrincipal = principal; } } [TestFixture(typeof(int))] [TestFixture(typeof(string))] public class GenericFixtureWithProperArgsProvided<T> { [Test] public void SomeTest() { } } public class GenericFixtureWithNoTestFixtureAttribute<T> { [Test] public void SomeTest() { } } [TestFixture] public class GenericFixtureWithNoArgsProvided<T> { [Test] public void SomeTest() { } } [TestFixture] public abstract class AbstractFixtureBase { [Test] public void SomeTest() { } } public class GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<T> : AbstractFixtureBase { } [TestFixture(typeof(int))] [TestFixture(typeof(string))] public class GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<T> : AbstractFixtureBase { } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookNamesCollectionRequest. /// </summary> public partial class WorkbookNamesCollectionRequest : BaseRequest, IWorkbookNamesCollectionRequest { /// <summary> /// Constructs a new WorkbookNamesCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookNamesCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified WorkbookNamedItem to the collection via POST. /// </summary> /// <param name="workbookNamedItem">The WorkbookNamedItem to add.</param> /// <returns>The created WorkbookNamedItem.</returns> public System.Threading.Tasks.Task<WorkbookNamedItem> AddAsync(WorkbookNamedItem workbookNamedItem) { return this.AddAsync(workbookNamedItem, CancellationToken.None); } /// <summary> /// Adds the specified WorkbookNamedItem to the collection via POST. /// </summary> /// <param name="workbookNamedItem">The WorkbookNamedItem to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookNamedItem.</returns> public System.Threading.Tasks.Task<WorkbookNamedItem> AddAsync(WorkbookNamedItem workbookNamedItem, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<WorkbookNamedItem>(workbookNamedItem, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IWorkbookNamesCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IWorkbookNamesCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<WorkbookNamesCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamesCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamesCollectionRequest Expand(Expression<Func<WorkbookNamedItem, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamesCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamesCollectionRequest Select(Expression<Func<WorkbookNamedItem, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamesCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamesCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamesCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamesCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
using System; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Steamworks.Data; namespace Steamworks { internal unsafe class ISteamRemoteStorage : SteamInterface { internal ISteamRemoteStorage( bool IsGameServer ) { SetupInterface( IsGameServer ); } [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamRemoteStorage_v016", CallingConvention = Platform.CC)] internal static extern IntPtr SteamAPI_SteamRemoteStorage_v016(); public override IntPtr GetUserInterfacePointer() => SteamAPI_SteamRemoteStorage_v016(); #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileWrite", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _FileWrite( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, IntPtr pvData, int cubData ); #endregion internal bool FileWrite( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, IntPtr pvData, int cubData ) { var returnValue = _FileWrite( Self, pchFile, pvData, cubData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileRead", CallingConvention = Platform.CC)] private static extern int _FileRead( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, IntPtr pvData, int cubDataToRead ); #endregion internal int FileRead( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, IntPtr pvData, int cubDataToRead ) { var returnValue = _FileRead( Self, pchFile, pvData, cubDataToRead ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileWriteAsync", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _FileWriteAsync( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, IntPtr pvData, uint cubData ); #endregion internal CallResult<RemoteStorageFileWriteAsyncComplete_t> FileWriteAsync( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, IntPtr pvData, uint cubData ) { var returnValue = _FileWriteAsync( Self, pchFile, pvData, cubData ); return new CallResult<RemoteStorageFileWriteAsyncComplete_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileReadAsync", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _FileReadAsync( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, uint nOffset, uint cubToRead ); #endregion internal CallResult<RemoteStorageFileReadAsyncComplete_t> FileReadAsync( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, uint nOffset, uint cubToRead ) { var returnValue = _FileReadAsync( Self, pchFile, nOffset, cubToRead ); return new CallResult<RemoteStorageFileReadAsyncComplete_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileReadAsyncComplete", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _FileReadAsyncComplete( IntPtr self, SteamAPICall_t hReadCall, IntPtr pvBuffer, uint cubToRead ); #endregion internal bool FileReadAsyncComplete( SteamAPICall_t hReadCall, IntPtr pvBuffer, uint cubToRead ) { var returnValue = _FileReadAsyncComplete( Self, hReadCall, pvBuffer, cubToRead ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileForget", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _FileForget( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ); #endregion internal bool FileForget( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ) { var returnValue = _FileForget( Self, pchFile ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileDelete", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _FileDelete( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ); #endregion internal bool FileDelete( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ) { var returnValue = _FileDelete( Self, pchFile ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileShare", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _FileShare( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ); #endregion internal CallResult<RemoteStorageFileShareResult_t> FileShare( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ) { var returnValue = _FileShare( Self, pchFile ); return new CallResult<RemoteStorageFileShareResult_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_SetSyncPlatforms", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetSyncPlatforms( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, RemoteStoragePlatform eRemoteStoragePlatform ); #endregion internal bool SetSyncPlatforms( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile, RemoteStoragePlatform eRemoteStoragePlatform ) { var returnValue = _SetSyncPlatforms( Self, pchFile, eRemoteStoragePlatform ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileWriteStreamOpen", CallingConvention = Platform.CC)] private static extern UGCFileWriteStreamHandle_t _FileWriteStreamOpen( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ); #endregion internal UGCFileWriteStreamHandle_t FileWriteStreamOpen( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ) { var returnValue = _FileWriteStreamOpen( Self, pchFile ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileWriteStreamWriteChunk", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _FileWriteStreamWriteChunk( IntPtr self, UGCFileWriteStreamHandle_t writeHandle, IntPtr pvData, int cubData ); #endregion internal bool FileWriteStreamWriteChunk( UGCFileWriteStreamHandle_t writeHandle, IntPtr pvData, int cubData ) { var returnValue = _FileWriteStreamWriteChunk( Self, writeHandle, pvData, cubData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileWriteStreamClose", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _FileWriteStreamClose( IntPtr self, UGCFileWriteStreamHandle_t writeHandle ); #endregion internal bool FileWriteStreamClose( UGCFileWriteStreamHandle_t writeHandle ) { var returnValue = _FileWriteStreamClose( Self, writeHandle ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileWriteStreamCancel", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _FileWriteStreamCancel( IntPtr self, UGCFileWriteStreamHandle_t writeHandle ); #endregion internal bool FileWriteStreamCancel( UGCFileWriteStreamHandle_t writeHandle ) { var returnValue = _FileWriteStreamCancel( Self, writeHandle ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FileExists", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _FileExists( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ); #endregion internal bool FileExists( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ) { var returnValue = _FileExists( Self, pchFile ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_FilePersisted", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _FilePersisted( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ); #endregion internal bool FilePersisted( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ) { var returnValue = _FilePersisted( Self, pchFile ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetFileSize", CallingConvention = Platform.CC)] private static extern int _GetFileSize( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ); #endregion internal int GetFileSize( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ) { var returnValue = _GetFileSize( Self, pchFile ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetFileTimestamp", CallingConvention = Platform.CC)] private static extern long _GetFileTimestamp( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ); #endregion internal long GetFileTimestamp( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ) { var returnValue = _GetFileTimestamp( Self, pchFile ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetSyncPlatforms", CallingConvention = Platform.CC)] private static extern RemoteStoragePlatform _GetSyncPlatforms( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ); #endregion internal RemoteStoragePlatform GetSyncPlatforms( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchFile ) { var returnValue = _GetSyncPlatforms( Self, pchFile ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetFileCount", CallingConvention = Platform.CC)] private static extern int _GetFileCount( IntPtr self ); #endregion internal int GetFileCount() { var returnValue = _GetFileCount( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetFileNameAndSize", CallingConvention = Platform.CC)] private static extern Utf8StringPointer _GetFileNameAndSize( IntPtr self, int iFile, ref int pnFileSizeInBytes ); #endregion internal string GetFileNameAndSize( int iFile, ref int pnFileSizeInBytes ) { var returnValue = _GetFileNameAndSize( Self, iFile, ref pnFileSizeInBytes ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetQuota", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetQuota( IntPtr self, ref ulong pnTotalBytes, ref ulong puAvailableBytes ); #endregion internal bool GetQuota( ref ulong pnTotalBytes, ref ulong puAvailableBytes ) { var returnValue = _GetQuota( Self, ref pnTotalBytes, ref puAvailableBytes ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_IsCloudEnabledForAccount", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _IsCloudEnabledForAccount( IntPtr self ); #endregion internal bool IsCloudEnabledForAccount() { var returnValue = _IsCloudEnabledForAccount( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_IsCloudEnabledForApp", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _IsCloudEnabledForApp( IntPtr self ); #endregion internal bool IsCloudEnabledForApp() { var returnValue = _IsCloudEnabledForApp( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_SetCloudEnabledForApp", CallingConvention = Platform.CC)] private static extern void _SetCloudEnabledForApp( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bEnabled ); #endregion internal void SetCloudEnabledForApp( [MarshalAs( UnmanagedType.U1 )] bool bEnabled ) { _SetCloudEnabledForApp( Self, bEnabled ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_UGCDownload", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _UGCDownload( IntPtr self, UGCHandle_t hContent, uint unPriority ); #endregion internal CallResult<RemoteStorageDownloadUGCResult_t> UGCDownload( UGCHandle_t hContent, uint unPriority ) { var returnValue = _UGCDownload( Self, hContent, unPriority ); return new CallResult<RemoteStorageDownloadUGCResult_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetUGCDownloadProgress", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetUGCDownloadProgress( IntPtr self, UGCHandle_t hContent, ref int pnBytesDownloaded, ref int pnBytesExpected ); #endregion internal bool GetUGCDownloadProgress( UGCHandle_t hContent, ref int pnBytesDownloaded, ref int pnBytesExpected ) { var returnValue = _GetUGCDownloadProgress( Self, hContent, ref pnBytesDownloaded, ref pnBytesExpected ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetUGCDetails", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetUGCDetails( IntPtr self, UGCHandle_t hContent, ref AppId pnAppID, [In,Out] ref char[] ppchName, ref int pnFileSizeInBytes, ref SteamId pSteamIDOwner ); #endregion internal bool GetUGCDetails( UGCHandle_t hContent, ref AppId pnAppID, [In,Out] ref char[] ppchName, ref int pnFileSizeInBytes, ref SteamId pSteamIDOwner ) { var returnValue = _GetUGCDetails( Self, hContent, ref pnAppID, ref ppchName, ref pnFileSizeInBytes, ref pSteamIDOwner ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_UGCRead", CallingConvention = Platform.CC)] private static extern int _UGCRead( IntPtr self, UGCHandle_t hContent, IntPtr pvData, int cubDataToRead, uint cOffset, UGCReadAction eAction ); #endregion internal int UGCRead( UGCHandle_t hContent, IntPtr pvData, int cubDataToRead, uint cOffset, UGCReadAction eAction ) { var returnValue = _UGCRead( Self, hContent, pvData, cubDataToRead, cOffset, eAction ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetCachedUGCCount", CallingConvention = Platform.CC)] private static extern int _GetCachedUGCCount( IntPtr self ); #endregion internal int GetCachedUGCCount() { var returnValue = _GetCachedUGCCount( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetCachedUGCHandle", CallingConvention = Platform.CC)] private static extern UGCHandle_t _GetCachedUGCHandle( IntPtr self, int iCachedContent ); #endregion internal UGCHandle_t GetCachedUGCHandle( int iCachedContent ) { var returnValue = _GetCachedUGCHandle( Self, iCachedContent ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_UGCDownloadToLocation", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _UGCDownloadToLocation( IntPtr self, UGCHandle_t hContent, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLocation, uint unPriority ); #endregion internal CallResult<RemoteStorageDownloadUGCResult_t> UGCDownloadToLocation( UGCHandle_t hContent, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLocation, uint unPriority ) { var returnValue = _UGCDownloadToLocation( Self, hContent, pchLocation, unPriority ); return new CallResult<RemoteStorageDownloadUGCResult_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetLocalFileChangeCount", CallingConvention = Platform.CC)] private static extern int _GetLocalFileChangeCount( IntPtr self ); #endregion internal int GetLocalFileChangeCount() { var returnValue = _GetLocalFileChangeCount( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_GetLocalFileChange", CallingConvention = Platform.CC)] private static extern Utf8StringPointer _GetLocalFileChange( IntPtr self, int iFile, ref RemoteStorageLocalFileChange pEChangeType, ref RemoteStorageFilePathType pEFilePathType ); #endregion internal string GetLocalFileChange( int iFile, ref RemoteStorageLocalFileChange pEChangeType, ref RemoteStorageFilePathType pEFilePathType ) { var returnValue = _GetLocalFileChange( Self, iFile, ref pEChangeType, ref pEFilePathType ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_BeginFileWriteBatch", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _BeginFileWriteBatch( IntPtr self ); #endregion internal bool BeginFileWriteBatch() { var returnValue = _BeginFileWriteBatch( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamRemoteStorage_EndFileWriteBatch", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _EndFileWriteBatch( IntPtr self ); #endregion internal bool EndFileWriteBatch() { var returnValue = _EndFileWriteBatch( Self ); return returnValue; } } }
using System; using System.Data; using System.Data.SqlClient; using Appleseed.Framework.Settings; namespace Appleseed.Framework.Content.Data { /// <summary> /// IBS Tasks module /// Class that encapsulates all data logic necessary to add/query/delete /// tasks within the Portal database. /// Written by: ??? (the guy did not write his name in the original code) /// Moved into Appleseed by Jakob Hansen, [email protected] /// EHN - By Mike Stone Change Description field to ntext to remove the 3000 char limit /// </summary> public class TasksDB { /// <summary> /// GetTasks /// NOTE: A DataSet is returned from this method to allow this method to support /// both desktop and mobile Web UI. /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns>A DataSet</returns> public DataSet GetTasks(int moduleID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlDataAdapter myCommand = new SqlDataAdapter("rb_GetTasks", myConnection); myCommand.SelectCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.SelectCommand.Parameters.Add(parameterModuleID); // Create and Fill the DataSet DataSet myDataSet = new DataSet(); try { myCommand.Fill(myDataSet); } finally { myConnection.Close(); //by Manu fix close bug #2 } // Return the DataSet return myDataSet; } /// <summary> /// GetSingleTask /// </summary> /// <param name="itemID">ItemID</param> /// <returns>A SqlDataReader</returns> public SqlDataReader GetSingleTask(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSingleTask", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// Deletes the task. /// </summary> /// <param name="itemID">The item ID.</param> public void DeleteTask(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DeleteTask", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); // Open the database connection and execute SQL Command myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } /// <summary> /// Adds the task. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="itemID">The item ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="title">The title.</param> /// <param name="startDate">The start date.</param> /// <param name="description">The description.</param> /// <param name="status">The status.</param> /// <param name="priority">The priority.</param> /// <param name="assignedto">The assignedto.</param> /// <param name="dueDate">The due date.</param> /// <param name="percentComplete">The percent complete.</param> /// <returns></returns> public int AddTask(int moduleID, int itemID, string userName, string title, DateTime startDate, string description, string status, string priority, string assignedto, DateTime dueDate, int percentComplete) { if (userName.Length < 1) { userName = "unknown"; } // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_AddTask", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterStatus = new SqlParameter("@Status", SqlDbType.NVarChar, 20); parameterStatus.Value = status; myCommand.Parameters.Add(parameterStatus); SqlParameter parameterPercentComplete = new SqlParameter("@PercentComplete", SqlDbType.Int, 4); parameterPercentComplete.Value = percentComplete; myCommand.Parameters.Add(parameterPercentComplete); SqlParameter parameterPriority = new SqlParameter("@Priority", SqlDbType.NVarChar, 20); parameterPriority.Value = priority; myCommand.Parameters.Add(parameterPriority); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); SqlParameter parameterAssignedTo = new SqlParameter("@AssignedTo", SqlDbType.NVarChar, 100); parameterAssignedTo.Value = assignedto; myCommand.Parameters.Add(parameterAssignedTo); SqlParameter parameterStartDate = new SqlParameter("@StartDate", SqlDbType.DateTime, 8); parameterStartDate.Value = startDate; myCommand.Parameters.Add(parameterStartDate); SqlParameter parameterDueDate = new SqlParameter("@DueDate", SqlDbType.DateTime, 8); parameterDueDate.Value = dueDate; myCommand.Parameters.Add(parameterDueDate); SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NText); parameterDescription.Value = description; myCommand.Parameters.Add(parameterDescription); // Open the database connection and execute SQL Command myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } // Return the new Task ItemID return (int) parameterItemID.Value; } /// <summary> /// Updates the task. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="itemID">The item ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="title">The title.</param> /// <param name="startDate">The start date.</param> /// <param name="description">The description.</param> /// <param name="status">The status.</param> /// <param name="priority">The priority.</param> /// <param name="assignedto">The assignedto.</param> /// <param name="dueDate">The due date.</param> /// <param name="percentComplete">The percent complete.</param> public void UpdateTask(int moduleID, int itemID, string userName, string title, DateTime startDate, string description, string status, string priority, string assignedto, DateTime dueDate, int percentComplete) { if (userName.Length < 1) { userName = "unknown"; } // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_UpdateTask", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterStatus = new SqlParameter("@Status", SqlDbType.NVarChar, 20); parameterStatus.Value = status; myCommand.Parameters.Add(parameterStatus); SqlParameter parameterPercentComplete = new SqlParameter("@PercentComplete", SqlDbType.Int, 4); parameterPercentComplete.Value = percentComplete; myCommand.Parameters.Add(parameterPercentComplete); SqlParameter parameterPriority = new SqlParameter("@Priority", SqlDbType.NVarChar, 20); parameterPriority.Value = priority; myCommand.Parameters.Add(parameterPriority); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); SqlParameter parameterAssignedTo = new SqlParameter("@AssignedTo", SqlDbType.NVarChar, 100); parameterAssignedTo.Value = assignedto; myCommand.Parameters.Add(parameterAssignedTo); SqlParameter parameterStartDate = new SqlParameter("@StartDate", SqlDbType.DateTime, 8); parameterStartDate.Value = startDate; myCommand.Parameters.Add(parameterStartDate); SqlParameter parameterDueDate = new SqlParameter("@DueDate", SqlDbType.DateTime, 8); parameterDueDate.Value = dueDate; myCommand.Parameters.Add(parameterDueDate); SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NText); parameterDescription.Value = description; myCommand.Parameters.Add(parameterDescription); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Reflection; using System.Text; #if NET_2_0 using System.Collections.Generic; #endif namespace NUnit.Framework.Constraints { #region CollectionConstraint /// <summary> /// CollectionConstraint is the abstract base class for /// constraints that operate on collections. /// </summary> public abstract class CollectionConstraint : Constraint { /// <summary> /// Construct an empty CollectionConstraint /// </summary> public CollectionConstraint() { } /// <summary> /// Construct a CollectionConstraint /// </summary> /// <param name="arg"></param> public CollectionConstraint(object arg) : base(arg) { } /// <summary> /// Determines whether the specified enumerable is empty. /// </summary> /// <param name="enumerable">The enumerable.</param> /// <returns> /// <c>true</c> if the specified enumerable is empty; otherwise, <c>false</c>. /// </returns> protected static bool IsEmpty( IEnumerable enumerable ) { ICollection collection = enumerable as ICollection; if ( collection != null ) return collection.Count == 0; else return !enumerable.GetEnumerator().MoveNext(); } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override bool Matches(object actual) { this.actual = actual; IEnumerable enumerable = actual as IEnumerable; if ( enumerable == null ) throw new ArgumentException( "The actual value must be an IEnumerable", "actual" ); return doMatch( enumerable ); } /// <summary> /// Protected method to be implemented by derived classes /// </summary> /// <param name="collection"></param> /// <returns></returns> protected abstract bool doMatch(IEnumerable collection); } #endregion #region CollectionItemsEqualConstraint /// <summary> /// CollectionItemsEqualConstraint is the abstract base class for all /// collection constraints that apply some notion of item equality /// as a part of their operation. /// </summary> public abstract class CollectionItemsEqualConstraint : CollectionConstraint { private NUnitEqualityComparer comparer = NUnitEqualityComparer.Default; /// <summary> /// Construct an empty CollectionConstraint /// </summary> public CollectionItemsEqualConstraint() { } /// <summary> /// Construct a CollectionConstraint /// </summary> /// <param name="arg"></param> public CollectionItemsEqualConstraint(object arg) : base(arg) { } #region Modifiers /// <summary> /// Flag the constraint to ignore case and return self. /// </summary> public CollectionItemsEqualConstraint IgnoreCase { get { comparer.IgnoreCase = true; return this; } } /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using(IComparer comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } #if NET_2_0 /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using<T>(IComparer<T> comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } /// <summary> /// Flag the constraint to use the supplied Comparison object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using<T>(Comparison<T> comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using(IEqualityComparer comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using<T>(IEqualityComparer<T> comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } #endif #endregion /// <summary> /// Compares two collection members for equality /// </summary> protected bool ItemsEqual(object x, object y) { return comparer.ObjectsEqual(x, y); } /// <summary> /// Return a new CollectionTally for use in making tests /// </summary> /// <param name="c">The collection to be included in the tally</param> protected CollectionTally Tally(IEnumerable c) { return new CollectionTally(comparer, c); } /// <summary> /// CollectionTally counts (tallies) the number of /// occurences of each object in one or more enumerations. /// </summary> protected internal class CollectionTally { // Internal list used to track occurences private ArrayList list = new ArrayList(); private NUnitEqualityComparer comparer; /// <summary> /// Construct a CollectionTally object from a comparer and a collection /// </summary> public CollectionTally(NUnitEqualityComparer comparer, IEnumerable c) { this.comparer = comparer; foreach (object o in c) list.Add(o); } /// <summary> /// The number of objects remaining in the tally /// </summary> public int Count { get { return list.Count; } } private bool ItemsEqual(object expected, object actual) { return comparer.ObjectsEqual(expected, actual); } /// <summary> /// Try to remove an object from the tally /// </summary> /// <param name="o">The object to remove</param> /// <returns>True if successful, false if the object was not found</returns> public bool TryRemove(object o) { for (int index = 0; index < list.Count; index++) if (ItemsEqual(list[index], o)) { list.RemoveAt(index); return true; } return false; } /// <summary> /// Try to remove a set of objects from the tally /// </summary> /// <param name="c">The objects to remove</param> /// <returns>True if successful, false if any object was not found</returns> public bool TryRemove(IEnumerable c) { foreach (object o in c) if (!TryRemove(o)) return false; return true; } } } #endregion #region EmptyCollectionConstraint /// <summary> /// EmptyCollectionConstraint tests whether a collection is empty. /// </summary> public class EmptyCollectionConstraint : CollectionConstraint { /// <summary> /// Check that the collection is empty /// </summary> /// <param name="collection"></param> /// <returns></returns> protected override bool doMatch(IEnumerable collection) { return IsEmpty( collection ); } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.Write( "<empty>" ); } } #endregion #region UniqueItemsConstraint /// <summary> /// UniqueItemsConstraint tests whether all the items in a /// collection are unique. /// </summary> public class UniqueItemsConstraint : CollectionItemsEqualConstraint { /// <summary> /// Check that all items are unique. /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { ArrayList list = new ArrayList(); foreach (object o1 in actual) { foreach( object o2 in list ) if ( ItemsEqual(o1, o2) ) return false; list.Add(o1); } return true; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.Write("all items unique"); } } #endregion #region CollectionContainsConstraint /// <summary> /// CollectionContainsConstraint is used to test whether a collection /// contains an expected object as a member. /// </summary> public class CollectionContainsConstraint : CollectionItemsEqualConstraint { private object expected; /// <summary> /// Construct a CollectionContainsConstraint /// </summary> /// <param name="expected"></param> public CollectionContainsConstraint(object expected) : base(expected) { this.expected = expected; this.DisplayName = "contains"; } /// <summary> /// Test whether the expected item is contained in the collection /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { foreach (object obj in actual) if (ItemsEqual(obj, expected)) return true; return false; } /// <summary> /// Write a descripton of the constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("collection containing"); writer.WriteExpectedValue(expected); } } #endregion #region CollectionEquivalentConstraint /// <summary> /// CollectionEquivalentCOnstraint is used to determine whether two /// collections are equivalent. /// </summary> public class CollectionEquivalentConstraint : CollectionItemsEqualConstraint { private IEnumerable expected; /// <summary> /// Construct a CollectionEquivalentConstraint /// </summary> /// <param name="expected"></param> public CollectionEquivalentConstraint(IEnumerable expected) : base(expected) { this.expected = expected; this.DisplayName = "equivalent"; } /// <summary> /// Test whether two collections are equivalent /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { // This is just an optimization if( expected is ICollection && actual is ICollection ) if( ((ICollection)actual).Count != ((ICollection)expected).Count ) return false; CollectionTally tally = Tally(expected); return tally.TryRemove(actual) && tally.Count == 0; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("equivalent to"); writer.WriteExpectedValue(expected); } } #endregion #region CollectionSubsetConstraint /// <summary> /// CollectionSubsetConstraint is used to determine whether /// one collection is a subset of another /// </summary> public class CollectionSubsetConstraint : CollectionItemsEqualConstraint { private IEnumerable expected; /// <summary> /// Construct a CollectionSubsetConstraint /// </summary> /// <param name="expected">The collection that the actual value is expected to be a subset of</param> public CollectionSubsetConstraint(IEnumerable expected) : base(expected) { this.expected = expected; this.DisplayName = "subsetof"; } /// <summary> /// Test whether the actual collection is a subset of /// the expected collection provided. /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { return Tally(expected).TryRemove( actual ); } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate( "subset of" ); writer.WriteExpectedValue(expected); } } #endregion #region CollectionOrderedConstraint /// <summary> /// CollectionOrderedConstraint is used to test whether a collection is ordered. /// </summary> public class CollectionOrderedConstraint : CollectionConstraint { private ComparisonAdapter comparer = ComparisonAdapter.Default; private string comparerName; private string propertyName; private bool descending; /// <summary> /// Construct a CollectionOrderedConstraint /// </summary> public CollectionOrderedConstraint() { this.DisplayName = "ordered"; } ///<summary> /// If used performs a reverse comparison ///</summary> public CollectionOrderedConstraint Descending { get { descending = true; return this; } } /// <summary> /// Modifies the constraint to use an IComparer and returns self. /// </summary> public CollectionOrderedConstraint Using(IComparer comparer) { this.comparer = ComparisonAdapter.For( comparer ); this.comparerName = comparer.GetType().FullName; return this; } #if NET_2_0 /// <summary> /// Modifies the constraint to use an IComparer&lt;T&gt; and returns self. /// </summary> public CollectionOrderedConstraint Using<T>(IComparer<T> comparer) { this.comparer = ComparisonAdapter.For(comparer); this.comparerName = comparer.GetType().FullName; return this; } /// <summary> /// Modifies the constraint to use a Comparison&lt;T&gt; and returns self. /// </summary> public CollectionOrderedConstraint Using<T>(Comparison<T> comparer) { this.comparer = ComparisonAdapter.For(comparer); this.comparerName = comparer.GetType().FullName; return this; } #endif /// <summary> /// Modifies the constraint to test ordering by the value of /// a specified property and returns self. /// </summary> public CollectionOrderedConstraint By(string propertyName) { this.propertyName = propertyName; return this; } /// <summary> /// Test whether the collection is ordered /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { object previous = null; int index = 0; foreach(object obj in actual) { object objToCompare = obj; if (obj == null) throw new ArgumentNullException("actual", "Null value at index " + index.ToString()); if (this.propertyName != null) { PropertyInfo prop = obj.GetType().GetProperty(propertyName); objToCompare = prop.GetValue(obj, null); if (objToCompare == null) throw new ArgumentNullException("actual", "Null property value at index " + index.ToString()); } if (previous != null) { //int comparisonResult = comparer.Compare(al[i], al[i + 1]); int comparisonResult = comparer.Compare(previous, objToCompare); if (descending && comparisonResult < 0) return false; if (!descending && comparisonResult > 0) return false; } previous = objToCompare; index++; } return true; } /// <summary> /// Write a description of the constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { if (propertyName == null) writer.Write("collection ordered"); else { writer.WritePredicate("collection ordered by"); writer.WriteExpectedValue(propertyName); } if (descending) writer.WriteModifier("descending"); } /// <summary> /// Returns the string representation of the constraint. /// </summary> /// <returns></returns> public override string ToString() { StringBuilder sb = new StringBuilder("<ordered"); if (propertyName != null) sb.Append("by " + propertyName); if (descending) sb.Append(" descending"); if (comparerName != null) sb.Append(" " + comparerName); sb.Append(">"); return sb.ToString(); } } #endregion }
/* * Copyright 2012-2021 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using System; using System.Runtime.InteropServices; // Note: Code in this file is maintained manually. namespace Net.Pkcs11Interop.LowLevelAPI41 { /// <summary> /// Structure which contains a Cryptoki version and a function pointer to each function in the Cryptoki API /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] internal struct CK_FUNCTION_LIST { /// <summary> /// Cryptoki version /// </summary> internal CK_VERSION version; /// <summary> /// Pointer to C_Initialize /// </summary> internal IntPtr C_Initialize; /// <summary> /// Pointer to C_Finalize /// </summary> internal IntPtr C_Finalize; /// <summary> /// Pointer to C_GetInfo /// </summary> internal IntPtr C_GetInfo; /// <summary> /// Pointer to C_GetFunctionList /// </summary> internal IntPtr C_GetFunctionList; /// <summary> /// Pointer to C_GetSlotList /// </summary> internal IntPtr C_GetSlotList; /// <summary> /// Pointer to C_GetSlotInfo /// </summary> internal IntPtr C_GetSlotInfo; /// <summary> /// Pointer to C_GetTokenInfo /// </summary> internal IntPtr C_GetTokenInfo; /// <summary> /// Pointer to C_GetMechanismList /// </summary> internal IntPtr C_GetMechanismList; /// <summary> /// Pointer to C_GetMechanismInfo /// </summary> internal IntPtr C_GetMechanismInfo; /// <summary> /// Pointer to C_InitToken /// </summary> internal IntPtr C_InitToken; /// <summary> /// Pointer to C_InitPIN /// </summary> internal IntPtr C_InitPIN; /// <summary> /// Pointer to C_SetPIN /// </summary> internal IntPtr C_SetPIN; /// <summary> /// Pointer to C_OpenSession /// </summary> internal IntPtr C_OpenSession; /// <summary> /// Pointer to C_CloseSession /// </summary> internal IntPtr C_CloseSession; /// <summary> /// Pointer to C_CloseAllSessions /// </summary> internal IntPtr C_CloseAllSessions; /// <summary> /// Pointer to C_GetSessionInfo /// </summary> internal IntPtr C_GetSessionInfo; /// <summary> /// Pointer to C_GetOperationState /// </summary> internal IntPtr C_GetOperationState; /// <summary> /// Pointer to C_SetOperationState /// </summary> internal IntPtr C_SetOperationState; /// <summary> /// Pointer to C_Login /// </summary> internal IntPtr C_Login; /// <summary> /// Pointer to C_Logout /// </summary> internal IntPtr C_Logout; /// <summary> /// Pointer to C_CreateObject /// </summary> internal IntPtr C_CreateObject; /// <summary> /// Pointer to C_CopyObject /// </summary> internal IntPtr C_CopyObject; /// <summary> /// Pointer to C_DestroyObject /// </summary> internal IntPtr C_DestroyObject; /// <summary> /// Pointer to C_GetObjectSize /// </summary> internal IntPtr C_GetObjectSize; /// <summary> /// Pointer to C_GetAttributeValue /// </summary> internal IntPtr C_GetAttributeValue; /// <summary> /// Pointer to C_SetAttributeValue /// </summary> internal IntPtr C_SetAttributeValue; /// <summary> /// Pointer to C_FindObjectsInit /// </summary> internal IntPtr C_FindObjectsInit; /// <summary> /// Pointer to C_FindObjects /// </summary> internal IntPtr C_FindObjects; /// <summary> /// Pointer to C_FindObjectsFinal /// </summary> internal IntPtr C_FindObjectsFinal; /// <summary> /// Pointer to C_EncryptInit /// </summary> internal IntPtr C_EncryptInit; /// <summary> /// Pointer to C_Encrypt /// </summary> internal IntPtr C_Encrypt; /// <summary> /// Pointer to C_EncryptUpdate /// </summary> internal IntPtr C_EncryptUpdate; /// <summary> /// Pointer to C_EncryptFinal /// </summary> internal IntPtr C_EncryptFinal; /// <summary> /// Pointer to C_DecryptInit /// </summary> internal IntPtr C_DecryptInit; /// <summary> /// Pointer to C_Decrypt /// </summary> internal IntPtr C_Decrypt; /// <summary> /// Pointer to C_DecryptUpdate /// </summary> internal IntPtr C_DecryptUpdate; /// <summary> /// Pointer to C_DecryptFinal /// </summary> internal IntPtr C_DecryptFinal; /// <summary> /// Pointer to C_DigestInit /// </summary> internal IntPtr C_DigestInit; /// <summary> /// Pointer to C_Digest /// </summary> internal IntPtr C_Digest; /// <summary> /// Pointer to C_DigestUpdate /// </summary> internal IntPtr C_DigestUpdate; /// <summary> /// Pointer to C_DigestKey /// </summary> internal IntPtr C_DigestKey; /// <summary> /// Pointer to C_DigestFinal /// </summary> internal IntPtr C_DigestFinal; /// <summary> /// Pointer to C_SignInit /// </summary> internal IntPtr C_SignInit; /// <summary> /// Pointer to C_Sign /// </summary> internal IntPtr C_Sign; /// <summary> /// Pointer to C_SignUpdate /// </summary> internal IntPtr C_SignUpdate; /// <summary> /// Pointer to C_SignFinal /// </summary> internal IntPtr C_SignFinal; /// <summary> /// Pointer to C_SignRecoverInit /// </summary> internal IntPtr C_SignRecoverInit; /// <summary> /// Pointer to C_SignRecover /// </summary> internal IntPtr C_SignRecover; /// <summary> /// Pointer to C_VerifyInit /// </summary> internal IntPtr C_VerifyInit; /// <summary> /// Pointer to C_Verify /// </summary> internal IntPtr C_Verify; /// <summary> /// Pointer to C_VerifyUpdate /// </summary> internal IntPtr C_VerifyUpdate; /// <summary> /// Pointer to C_VerifyFinal /// </summary> internal IntPtr C_VerifyFinal; /// <summary> /// Pointer to C_VerifyRecoverInit /// </summary> internal IntPtr C_VerifyRecoverInit; /// <summary> /// Pointer to C_VerifyRecover /// </summary> internal IntPtr C_VerifyRecover; /// <summary> /// Pointer to C_DigestEncryptUpdate /// </summary> internal IntPtr C_DigestEncryptUpdate; /// <summary> /// Pointer to C_DecryptDigestUpdate /// </summary> internal IntPtr C_DecryptDigestUpdate; /// <summary> /// Pointer to C_SignEncryptUpdate /// </summary> internal IntPtr C_SignEncryptUpdate; /// <summary> /// Pointer to C_DecryptVerifyUpdate /// </summary> internal IntPtr C_DecryptVerifyUpdate; /// <summary> /// Pointer to C_GenerateKey /// </summary> internal IntPtr C_GenerateKey; /// <summary> /// Pointer to C_GenerateKeyPair /// </summary> internal IntPtr C_GenerateKeyPair; /// <summary> /// Pointer to C_WrapKey /// </summary> internal IntPtr C_WrapKey; /// <summary> /// Pointer to C_UnwrapKey /// </summary> internal IntPtr C_UnwrapKey; /// <summary> /// Pointer to C_DeriveKey /// </summary> internal IntPtr C_DeriveKey; /// <summary> /// Pointer to C_SeedRandom /// </summary> internal IntPtr C_SeedRandom; /// <summary> /// Pointer to C_GenerateRandom /// </summary> internal IntPtr C_GenerateRandom; /// <summary> /// Pointer to C_GetFunctionStatus /// </summary> internal IntPtr C_GetFunctionStatus; /// <summary> /// Pointer to C_CancelFunction /// </summary> internal IntPtr C_CancelFunction; /// <summary> /// Pointer to C_WaitForSlotEvent /// </summary> internal IntPtr C_WaitForSlotEvent; } }
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 SiaqodbCloudService.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; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql.LegacySdk; using Microsoft.Azure.Management.Sql.LegacySdk.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql.LegacySdk { /// <summary> /// Represents all the operations for managing recommended indexes on Azure /// SQL Databases. Contains operations to retrieve recommended index and /// update state. /// </summary> internal partial class RecommendedIndexOperations : IServiceOperations<SqlManagementClient>, IRecommendedIndexOperations { /// <summary> /// Initializes a new instance of the RecommendedIndexOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RecommendedIndexOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Returns details on recommended index. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL database. /// </param> /// <param name='schemaName'> /// Required. The name of the Azure SQL database schema. /// </param> /// <param name='tableName'> /// Required. The name of the Azure SQL database table. /// </param> /// <param name='indexName'> /// Required. The name of the Azure SQL database recommended index. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get recommended index request. /// </returns> public async Task<RecommendedIndexGetResponse> GetAsync(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string indexName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (schemaName == null) { throw new ArgumentNullException("schemaName"); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (indexName == null) { throw new ArgumentNullException("indexName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("schemaName", schemaName); tracingParameters.Add("tableName", tableName); tracingParameters.Add("indexName", indexName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/schemas/"; url = url + Uri.EscapeDataString(schemaName); url = url + "/tables/"; url = url + Uri.EscapeDataString(tableName); url = url + "/recommendedIndexes/"; url = url + Uri.EscapeDataString(indexName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RecommendedIndexGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RecommendedIndexGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { RecommendedIndex recommendedIndexInstance = new RecommendedIndex(); result.RecommendedIndex = recommendedIndexInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { RecommendedIndexProperties propertiesInstance = new RecommendedIndexProperties(); recommendedIndexInstance.Properties = propertiesInstance; JToken actionValue = propertiesValue["action"]; if (actionValue != null && actionValue.Type != JTokenType.Null) { string actionInstance = ((string)actionValue); propertiesInstance.Action = actionInstance; } JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken createdValue = propertiesValue["created"]; if (createdValue != null && createdValue.Type != JTokenType.Null) { DateTime createdInstance = ((DateTime)createdValue); propertiesInstance.Created = createdInstance; } JToken lastModifiedValue = propertiesValue["lastModified"]; if (lastModifiedValue != null && lastModifiedValue.Type != JTokenType.Null) { DateTime lastModifiedInstance = ((DateTime)lastModifiedValue); propertiesInstance.LastModified = lastModifiedInstance; } JToken indexTypeValue = propertiesValue["indexType"]; if (indexTypeValue != null && indexTypeValue.Type != JTokenType.Null) { string indexTypeInstance = ((string)indexTypeValue); propertiesInstance.IndexType = indexTypeInstance; } JToken schemaValue = propertiesValue["schema"]; if (schemaValue != null && schemaValue.Type != JTokenType.Null) { string schemaInstance = ((string)schemaValue); propertiesInstance.Schema = schemaInstance; } JToken tableValue = propertiesValue["table"]; if (tableValue != null && tableValue.Type != JTokenType.Null) { string tableInstance = ((string)tableValue); propertiesInstance.Table = tableInstance; } JToken columnsArray = propertiesValue["columns"]; if (columnsArray != null && columnsArray.Type != JTokenType.Null) { foreach (JToken columnsValue in ((JArray)columnsArray)) { propertiesInstance.Columns.Add(((string)columnsValue)); } } JToken includedColumnsArray = propertiesValue["includedColumns"]; if (includedColumnsArray != null && includedColumnsArray.Type != JTokenType.Null) { foreach (JToken includedColumnsValue in ((JArray)includedColumnsArray)) { propertiesInstance.IncludedColumns.Add(((string)includedColumnsValue)); } } JToken indexScriptValue = propertiesValue["indexScript"]; if (indexScriptValue != null && indexScriptValue.Type != JTokenType.Null) { string indexScriptInstance = ((string)indexScriptValue); propertiesInstance.IndexScript = indexScriptInstance; } JToken estimatedImpactArray = propertiesValue["estimatedImpact"]; if (estimatedImpactArray != null && estimatedImpactArray.Type != JTokenType.Null) { foreach (JToken estimatedImpactValue in ((JArray)estimatedImpactArray)) { OperationImpact operationImpactInstance = new OperationImpact(); propertiesInstance.EstimatedImpact.Add(operationImpactInstance); JToken nameValue = estimatedImpactValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); operationImpactInstance.Name = nameInstance; } JToken unitValue = estimatedImpactValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { string unitInstance = ((string)unitValue); operationImpactInstance.Unit = unitInstance; } JToken changeValueAbsoluteValue = estimatedImpactValue["changeValueAbsolute"]; if (changeValueAbsoluteValue != null && changeValueAbsoluteValue.Type != JTokenType.Null) { double changeValueAbsoluteInstance = ((double)changeValueAbsoluteValue); operationImpactInstance.ChangeValueAbsolute = changeValueAbsoluteInstance; } JToken changeValueRelativeValue = estimatedImpactValue["changeValueRelative"]; if (changeValueRelativeValue != null && changeValueRelativeValue.Type != JTokenType.Null) { double changeValueRelativeInstance = ((double)changeValueRelativeValue); operationImpactInstance.ChangeValueRelative = changeValueRelativeInstance; } } } JToken reportedImpactArray = propertiesValue["reportedImpact"]; if (reportedImpactArray != null && reportedImpactArray.Type != JTokenType.Null) { foreach (JToken reportedImpactValue in ((JArray)reportedImpactArray)) { OperationImpact operationImpactInstance2 = new OperationImpact(); propertiesInstance.ReportedImpact.Add(operationImpactInstance2); JToken nameValue2 = reportedImpactValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); operationImpactInstance2.Name = nameInstance2; } JToken unitValue2 = reportedImpactValue["unit"]; if (unitValue2 != null && unitValue2.Type != JTokenType.Null) { string unitInstance2 = ((string)unitValue2); operationImpactInstance2.Unit = unitInstance2; } JToken changeValueAbsoluteValue2 = reportedImpactValue["changeValueAbsolute"]; if (changeValueAbsoluteValue2 != null && changeValueAbsoluteValue2.Type != JTokenType.Null) { double changeValueAbsoluteInstance2 = ((double)changeValueAbsoluteValue2); operationImpactInstance2.ChangeValueAbsolute = changeValueAbsoluteInstance2; } JToken changeValueRelativeValue2 = reportedImpactValue["changeValueRelative"]; if (changeValueRelativeValue2 != null && changeValueRelativeValue2.Type != JTokenType.Null) { double changeValueRelativeInstance2 = ((double)changeValueRelativeValue2); operationImpactInstance2.ChangeValueRelative = changeValueRelativeInstance2; } } } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); recommendedIndexInstance.Id = idInstance; } JToken nameValue3 = responseDoc["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); recommendedIndexInstance.Name = nameInstance3; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); recommendedIndexInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); recommendedIndexInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); recommendedIndexInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// We execute or cancel index operations by updating index state. /// Allowed state transitions are :Active -> Pending /// - Start index creation processPending -> Active /// - Cancel index creationActive/Pending -> Ignored /// - Ignore index recommendation so it will no longer show /// in active recommendationsIgnored -> Active - /// Restore index recommendationSuccess -> Pending Revert - /// Revert index that has been createdPending Revert -> Revert /// Canceled - Cancel index revert operation /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database. /// </param> /// <param name='schemaName'> /// Required. The name of the Azure SQL Database schema. /// </param> /// <param name='tableName'> /// Required. The name of the Azure SQL Database table. /// </param> /// <param name='indexName'> /// Required. The name of the Azure SQL Database recommended index. /// </param> /// <param name='parameters'> /// Required. The required parameters for updating index state. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get recommended index request. /// </returns> public async Task<RecommendedIndexUpdateResponse> UpdateAsync(string resourceGroupName, string serverName, string databaseName, string schemaName, string tableName, string indexName, RecommendedIndexUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (schemaName == null) { throw new ArgumentNullException("schemaName"); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (indexName == null) { throw new ArgumentNullException("indexName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("schemaName", schemaName); tracingParameters.Add("tableName", tableName); tracingParameters.Add("indexName", indexName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/schemas/"; url = url + Uri.EscapeDataString(schemaName); url = url + "/tables/"; url = url + Uri.EscapeDataString(tableName); url = url + "/recommendedIndexes/"; url = url + Uri.EscapeDataString(indexName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject recommendedIndexUpdateParametersValue = new JObject(); requestDoc = recommendedIndexUpdateParametersValue; JObject propertiesValue = new JObject(); recommendedIndexUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.State != null) { propertiesValue["state"] = parameters.Properties.State; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RecommendedIndexUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RecommendedIndexUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } RecommendedIndex recommendedIndexInstance = new RecommendedIndex(); result.RecommendedIndex = recommendedIndexInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { RecommendedIndexProperties propertiesInstance = new RecommendedIndexProperties(); recommendedIndexInstance.Properties = propertiesInstance; JToken actionValue = propertiesValue2["action"]; if (actionValue != null && actionValue.Type != JTokenType.Null) { string actionInstance = ((string)actionValue); propertiesInstance.Action = actionInstance; } JToken stateValue = propertiesValue2["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken createdValue = propertiesValue2["created"]; if (createdValue != null && createdValue.Type != JTokenType.Null) { DateTime createdInstance = ((DateTime)createdValue); propertiesInstance.Created = createdInstance; } JToken lastModifiedValue = propertiesValue2["lastModified"]; if (lastModifiedValue != null && lastModifiedValue.Type != JTokenType.Null) { DateTime lastModifiedInstance = ((DateTime)lastModifiedValue); propertiesInstance.LastModified = lastModifiedInstance; } JToken indexTypeValue = propertiesValue2["indexType"]; if (indexTypeValue != null && indexTypeValue.Type != JTokenType.Null) { string indexTypeInstance = ((string)indexTypeValue); propertiesInstance.IndexType = indexTypeInstance; } JToken schemaValue = propertiesValue2["schema"]; if (schemaValue != null && schemaValue.Type != JTokenType.Null) { string schemaInstance = ((string)schemaValue); propertiesInstance.Schema = schemaInstance; } JToken tableValue = propertiesValue2["table"]; if (tableValue != null && tableValue.Type != JTokenType.Null) { string tableInstance = ((string)tableValue); propertiesInstance.Table = tableInstance; } JToken columnsArray = propertiesValue2["columns"]; if (columnsArray != null && columnsArray.Type != JTokenType.Null) { foreach (JToken columnsValue in ((JArray)columnsArray)) { propertiesInstance.Columns.Add(((string)columnsValue)); } } JToken includedColumnsArray = propertiesValue2["includedColumns"]; if (includedColumnsArray != null && includedColumnsArray.Type != JTokenType.Null) { foreach (JToken includedColumnsValue in ((JArray)includedColumnsArray)) { propertiesInstance.IncludedColumns.Add(((string)includedColumnsValue)); } } JToken indexScriptValue = propertiesValue2["indexScript"]; if (indexScriptValue != null && indexScriptValue.Type != JTokenType.Null) { string indexScriptInstance = ((string)indexScriptValue); propertiesInstance.IndexScript = indexScriptInstance; } JToken estimatedImpactArray = propertiesValue2["estimatedImpact"]; if (estimatedImpactArray != null && estimatedImpactArray.Type != JTokenType.Null) { foreach (JToken estimatedImpactValue in ((JArray)estimatedImpactArray)) { OperationImpact operationImpactInstance = new OperationImpact(); propertiesInstance.EstimatedImpact.Add(operationImpactInstance); JToken nameValue = estimatedImpactValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); operationImpactInstance.Name = nameInstance; } JToken unitValue = estimatedImpactValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { string unitInstance = ((string)unitValue); operationImpactInstance.Unit = unitInstance; } JToken changeValueAbsoluteValue = estimatedImpactValue["changeValueAbsolute"]; if (changeValueAbsoluteValue != null && changeValueAbsoluteValue.Type != JTokenType.Null) { double changeValueAbsoluteInstance = ((double)changeValueAbsoluteValue); operationImpactInstance.ChangeValueAbsolute = changeValueAbsoluteInstance; } JToken changeValueRelativeValue = estimatedImpactValue["changeValueRelative"]; if (changeValueRelativeValue != null && changeValueRelativeValue.Type != JTokenType.Null) { double changeValueRelativeInstance = ((double)changeValueRelativeValue); operationImpactInstance.ChangeValueRelative = changeValueRelativeInstance; } } } JToken reportedImpactArray = propertiesValue2["reportedImpact"]; if (reportedImpactArray != null && reportedImpactArray.Type != JTokenType.Null) { foreach (JToken reportedImpactValue in ((JArray)reportedImpactArray)) { OperationImpact operationImpactInstance2 = new OperationImpact(); propertiesInstance.ReportedImpact.Add(operationImpactInstance2); JToken nameValue2 = reportedImpactValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); operationImpactInstance2.Name = nameInstance2; } JToken unitValue2 = reportedImpactValue["unit"]; if (unitValue2 != null && unitValue2.Type != JTokenType.Null) { string unitInstance2 = ((string)unitValue2); operationImpactInstance2.Unit = unitInstance2; } JToken changeValueAbsoluteValue2 = reportedImpactValue["changeValueAbsolute"]; if (changeValueAbsoluteValue2 != null && changeValueAbsoluteValue2.Type != JTokenType.Null) { double changeValueAbsoluteInstance2 = ((double)changeValueAbsoluteValue2); operationImpactInstance2.ChangeValueAbsolute = changeValueAbsoluteInstance2; } JToken changeValueRelativeValue2 = reportedImpactValue["changeValueRelative"]; if (changeValueRelativeValue2 != null && changeValueRelativeValue2.Type != JTokenType.Null) { double changeValueRelativeInstance2 = ((double)changeValueRelativeValue2); operationImpactInstance2.ChangeValueRelative = changeValueRelativeInstance2; } } } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); recommendedIndexInstance.Id = idInstance; } JToken nameValue3 = responseDoc["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); recommendedIndexInstance.Name = nameInstance3; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); recommendedIndexInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); recommendedIndexInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); recommendedIndexInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Data.SqlClient { internal sealed partial class SNILoadHandle : SafeHandle { internal static readonly SNILoadHandle SingletonInstance = new SNILoadHandle(); internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate ReadAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(ReadDispatcher); internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate WriteAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(WriteDispatcher); private readonly UInt32 _sniStatus = TdsEnums.SNI_UNINITIALIZED; private readonly EncryptionOptions _encryptionOption; private SNILoadHandle() : base(IntPtr.Zero, true) { // From security review - SafeHandle guarantees this is only called once. // The reason for the safehandle is guaranteed initialization and termination of SNI to // ensure SNI terminates and cleans up properly. try { } finally { _sniStatus = SNINativeMethodWrapper.SNIInitialize(); UInt32 value = 0; // VSDevDiv 479597: If initialize fails, don't call QueryInfo. if (TdsEnums.SNI_SUCCESS == _sniStatus) { // Query OS to find out whether encryption is supported. SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, ref value); } _encryptionOption = (value == 0) ? EncryptionOptions.NOT_SUP : EncryptionOptions.OFF; base.handle = (IntPtr)1; // Initialize to non-zero dummy variable. } } public override bool IsInvalid { get { return (IntPtr.Zero == base.handle); } } override protected bool ReleaseHandle() { if (base.handle != IntPtr.Zero) { if (TdsEnums.SNI_SUCCESS == _sniStatus) { LocalDBAPI.ReleaseDLLHandles(); SNINativeMethodWrapper.SNITerminate(); } base.handle = IntPtr.Zero; } return true; } public UInt32 Status { get { return _sniStatus; } } public EncryptionOptions Options { get { return _encryptionOption; } } private static void ReadDispatcher(IntPtr key, IntPtr packet, UInt32 error) { // This is the app-domain dispatcher for all async read callbacks, It // simply gets the state object from the key that it is passed, and // calls the state object's read callback. Debug.Assert(IntPtr.Zero != key, "no key passed to read callback dispatcher?"); if (IntPtr.Zero != key) { // NOTE: we will get a null ref here if we don't get a key that // contains a GCHandle to TDSParserStateObject; that is // very bad, and we want that to occur so we can catch it. GCHandle gcHandle = (GCHandle)key; TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target; if (null != stateObj) { stateObj.ReadAsyncCallback(IntPtr.Zero, packet, error); } } } private static void WriteDispatcher(IntPtr key, IntPtr packet, UInt32 error) { // This is the app-domain dispatcher for all async write callbacks, It // simply gets the state object from the key that it is passed, and // calls the state object's write callback. Debug.Assert(IntPtr.Zero != key, "no key passed to write callback dispatcher?"); if (IntPtr.Zero != key) { // NOTE: we will get a null ref here if we don't get a key that // contains a GCHandle to TDSParserStateObject; that is // very bad, and we want that to occur so we can catch it. GCHandle gcHandle = (GCHandle)key; TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target; if (null != stateObj) { stateObj.WriteAsyncCallback(IntPtr.Zero, packet, error); } } } } internal sealed class SNIHandle : SafeHandle { private readonly UInt32 _status = TdsEnums.SNI_UNINITIALIZED; private readonly bool _fSync = false; // creates a physical connection internal SNIHandle( SNINativeMethodWrapper.ConsumerInfo myInfo, string serverName, byte[] spnBuffer, bool ignoreSniOpenTimeout, int timeout, out byte[] instanceName, bool flushCache, bool fSync, bool fParallel) : base(IntPtr.Zero, true) { try { } finally { _fSync = fSync; instanceName = new byte[256]; // Size as specified by netlibs. if (ignoreSniOpenTimeout) { timeout = Timeout.Infinite; // -1 == native SNIOPEN_TIMEOUT_VALUE / INFINITE } _status = SNINativeMethodWrapper.SNIOpenSyncEx(myInfo, serverName, ref base.handle, spnBuffer, instanceName, flushCache, fSync, timeout, fParallel); } } // constructs SNI Handle for MARS session internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, SNIHandle parent) : base(IntPtr.Zero, true) { try { } finally { _status = SNINativeMethodWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync); } } public override bool IsInvalid { get { return (IntPtr.Zero == base.handle); } } override protected bool ReleaseHandle() { // NOTE: The SafeHandle class guarantees this will be called exactly once. IntPtr ptr = base.handle; base.handle = IntPtr.Zero; if (IntPtr.Zero != ptr) { if (0 != SNINativeMethodWrapper.SNIClose(ptr)) { return false; // SNIClose should never fail. } } return true; } internal UInt32 Status { get { return _status; } } } internal sealed class SNIPacket : SafeHandle { internal SNIPacket(SafeHandle sniHandle) : base(IntPtr.Zero, true) { SNINativeMethodWrapper.SNIPacketAllocate(sniHandle, SNINativeMethodWrapper.IOType.WRITE, ref base.handle); if (IntPtr.Zero == base.handle) { throw SQL.SNIPacketAllocationFailure(); } } public override bool IsInvalid { get { return (IntPtr.Zero == base.handle); } } override protected bool ReleaseHandle() { // NOTE: The SafeHandle class guarantees this will be called exactly once. IntPtr ptr = base.handle; base.handle = IntPtr.Zero; if (IntPtr.Zero != ptr) { SNINativeMethodWrapper.SNIPacketRelease(ptr); } return true; } } internal sealed class WritePacketCache : IDisposable { private bool _disposed; private Stack<SNIPacket> _packets; public WritePacketCache() { _disposed = false; _packets = new Stack<SNIPacket>(); } public SNIPacket Take(SNIHandle sniHandle) { SNIPacket packet; if (_packets.Count > 0) { // Success - reset the packet packet = _packets.Pop(); SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI); } else { // Failed to take a packet - create a new one packet = new SNIPacket(sniHandle); } return packet; } public void Add(SNIPacket packet) { if (!_disposed) { _packets.Push(packet); } else { // If we're disposed, then get rid of any packets added to us packet.Dispose(); } } public void Clear() { while (_packets.Count > 0) { _packets.Pop().Dispose(); } } public void Dispose() { if (!_disposed) { _disposed = true; Clear(); } } } }
using System; using System.Collections.ObjectModel; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Web; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Aspose.Barcode.Live.Demos.UI.Services; using Aspose.Barcode.Live.Demos.UI.Models; namespace Aspose.Barcode.Live.Demos.UI.Config { public class BasePage : BaseRootPage { private string _product; /// <summary> /// Product name (e.g. words, cells) /// </summary> public string Product { get { if (string.IsNullOrEmpty(_product)) { if (Page.RouteData.Values["Product"] != null) { _product = Page.RouteData.Values["Product"].ToString().ToLower(); } } return _product; } set => _product = value; } private string _feature; /// <summary> /// Product name (e.g. words, cells) /// </summary> public string Feature { get { if (_feature == null) if (Page.RouteData.Values.ContainsKey("Feature")) _feature = Page.RouteData.Values["Feature"].ToString().ToLower(); else _feature = ""; return _feature; } set => _feature = value; } public string _pageProductTitle; /// <summary> /// Product title (e.g. Aspose.Words) /// </summary> public string PageProductTitle { get { if (_pageProductTitle == null) _pageProductTitle = Resources["Aspose" + TitleCase(Product)]; return _pageProductTitle; } } private string _productH1 = ""; public string ProductH1 { get { return _productH1; } } private string _productH4 = ""; public string ProductH4 { get { return _productH4; } } private string _extension1 = ""; public string Extension1 { get { return _extension1; } } private int _appURLID = 0; public int AppURLID { get { return _appURLID; } } private string _extension1Description = ""; public string Extension1Description { get { return _extension1Description; } } protected override void OnLoad(EventArgs e) { if (Resources != null) { Page.Title = Resources["ApplicationTitle"]; } base.OnLoad(e); } /// <summary> /// Set validation for RegularExpressionValidators, InputFile and ViewStates using Resources[Product + "ValidationExpression"] /// </summary> private void SetAccept(string validationExpression, params HtmlInputFile[] inpufiles) { var accept = validationExpression.ToLower().Replace("|", ","); foreach (var inpufile in inpufiles) inpufile.Attributes.Add("accept", accept.ToLower().Replace("|", ",")); } /// <summary> /// Set validation for RegularExpressionValidators and ViewStates using Resources[Product + "ValidationExpression"]. /// If the 'ControlToValidate' option is HtmlInputFile, it sets accept an attribute to that control /// </summary> /// <param name="validators"></param> protected void SetValidation(params RegularExpressionValidator[] validators) { var validationExpression = ""; var validFileExtensions = ""; // Check for format like .Doc if (Page.RouteData.Values["Format"] != null) { validFileExtensions = Page.RouteData.Values["Format"].ToString().ToUpper(); validationExpression = "." + validFileExtensions.ToLower(); } else { validationExpression = Resources[Product + "ValidationExpression"]; validFileExtensions = GetValidFileExtensions(validationExpression); } SetValidation(validationExpression, validators); ViewState["product"] = Product; ViewState["validFileExtensions"] = validFileExtensions; } protected void SetValidationExpression(string validationExpression, params RegularExpressionValidator[] validators) { var validFileExtensions = GetValidFileExtensions(validationExpression); SetValidation(validationExpression, validators); ViewState["product"] = Product; ViewState["validFileExtensions"] = validFileExtensions; } /// <summary> /// Set validation for RegularExpressionValidators, InputFile and ViewStates using validationExpression /// </summary> protected string SetValidation(string validationExpression, params RegularExpressionValidator[] validators) { // Check for format if format is available then valid expression will be only format for auto generated URLs if (Page.RouteData.Values["Format"] != null) { validationExpression = "." + Page.RouteData.Values["Format"].ToString().ToLower(); } var validFileExtensions = GetValidFileExtensions(validationExpression); foreach (var v in validators) { v.ValidationExpression = @"(.*?)(" + validationExpression.ToLower() + "|" + validationExpression.ToUpper() + ")$"; v.ErrorMessage = Resources["InvalidFileExtension"] + " " + validFileExtensions; if (!string.IsNullOrEmpty(v.ControlToValidate)) { var control = v.FindControl(v.ControlToValidate); if (control is HtmlInputFile inpufile) SetAccept(validationExpression, inpufile); } } return validFileExtensions; } /// <summary> /// Get the text of valid file extensions /// e.g. DOC, DOCX, DOT, DOTX, RTF or ODT /// </summary> /// <param name="validationExpression"></param> /// <returns></returns> protected string GetValidFileExtensions(string validationExpression) { var validFileExtensions = validationExpression.Replace(".", "").Replace("|", ", ").ToUpper(); var index = validFileExtensions.LastIndexOf(","); if (index != -1) { var substr = validFileExtensions.Substring(index); var str = substr.Replace(",", " or"); validFileExtensions = validFileExtensions.Replace(substr, str); } return validFileExtensions; } /// <summary> /// Check for null and ContentLength of the PostedFile /// </summary> /// <param name="fileInputs"></param> /// <returns></returns> protected bool CheckFileInputs(params HtmlInputFile[] fileInputs) { return fileInputs.All(x => x != null && x.PostedFile.ContentLength > 0); } /// <summary> /// Save uploaded file to the directory /// </summary> /// <returns>SaveLocation with filename</returns> private string SaveUploadedFile(string directory, HtmlInputFile fileInput) { var fn = Path.GetFileName(fileInput.PostedFile.FileName); // Edge browser sents a full path for a filename var saveLocation = Path.Combine(directory, fn); fileInput.PostedFile.SaveAs(saveLocation); return saveLocation; } /// <summary> /// Check response for null and StatusCode. Call action if everything is fine or show error message if not /// </summary> /// <param name="response"></param> /// <param name="controlErrorMessage"></param> /// <param name="action"></param> protected void PerformResponse(Response response, HtmlGenericControl controlErrorMessage, Action<Response> action) { if (response == null) throw new Exception(Resources["ResponseTime"]); if (response.StatusCode == 200 && response.FileProcessingErrorCode == 0) action(response); else ShowErrorMessage(controlErrorMessage, response); } /// <summary> /// Check FileProcessingErrorCode of the response and show the error message /// </summary> /// <param name="control"></param> /// <param name="response"></param> protected void ShowErrorMessage(HtmlGenericControl control, Response response) { string txt; switch (response.FileProcessingErrorCode) { case FileProcessingErrorCode.NoImagesFound: txt = Resources["NoImagesFoundMessage"]; break; case FileProcessingErrorCode.NoSearchResults: txt = Resources["NoSearchResultsMessage"]; break; case FileProcessingErrorCode.WrongRegExp: txt = Resources["WrongRegExpMessage"]; break; default: txt = response.Status; break; } ShowErrorMessage(control, txt); } protected void SetFormatInformations(string format, HtmlControl dvAppProductSection, HtmlControl dvHowToSection, HtmlControl dvExtensionDescription ) { if (Page.RouteData.Values[format] != null) { // Populate contents from database based on URL string _url = HttpContext.Current.Request.Url.AbsolutePath.ToLower(); if (dvAppProductSection != null) { dvAppProductSection.Visible = false; } //Page.Title = hMainTitle.InnerText; // Resources["PerformOCR"]; } } protected void ShowErrorMessage(HtmlGenericControl control, string message) { if(message.ToLower().Contains("password")) { if ("pdf words cells slides note".Contains(Product.ToLower()) && !AppRelativeVirtualPath.ToLower().Contains("unlock")) { string asposeUrl = "/" + Product + "/unlock"; message = "Your file seems to be encrypted. Please use our <a style=\"color:yellow\" href=\"" + asposeUrl + "\">" + PageProductTitle + " Unlock</a> app to remove the password."; } } control.Visible = true; control.InnerHtml = message; control.Attributes.Add("class", "alert alert-danger"); } protected void ShowSuccessMessage(HtmlGenericControl control, string message) { control.Visible = true; control.InnerHtml = message; control.Attributes.Add("class", "alert alert-success"); } protected void CheckReturnFromViewer(Action<Response> action) { if (Request.QueryString["folderName"] != null && Request.QueryString["fileName"] != null) { var response = new Response() { FileName = Request.QueryString["fileName"], FolderName = Request.QueryString["folderName"] }; action(response); } } protected string TitleCase(string value) { return new CultureInfo("en-US", false).TextInfo.ToTitleCase(value); } } }
using System; using System.Collections; using System.Runtime.InteropServices; using System.Windows.Forms; using Imports; namespace Scanning { partial class TwainDataSourceManager { class LibTwain32 { [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSMparent([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr refptr); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSMident([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwIdentity idds); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSMstatus([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwStatus dsmstat); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSuserif([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, TwUserInterface guif); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSevent([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref TwEvent evt); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSstatus([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwStatus dsmstat); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DScap([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwCapability capa); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSiinf([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwImageInfo imginf); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSilayout([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwImageLayout value); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSixfer([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr hbitmap); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DSpxfer([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwPendingXfers pxfr); [DllImport("twain_32.dll", EntryPoint = "#1")] public static extern TwRC DScustomData([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwCustomDsData data); } [Flags] enum TwDG : short { Control = 0x0001, Image = 0x0002, Audio = 0x0004 } enum TwDAT : short { Null = 0x0000, Capability = 0x0001, Event = 0x0002, Identity = 0x0003, Parent = 0x0004, PendingXfers = 0x0005, SetupMemXfer = 0x0006, SetupFileXfer = 0x0007, Status = 0x0008, UserInterface = 0x0009, XferGroup = 0x000a, TwunkIdentity = 0x000b, CustomDSData = 0x000c, DeviceEvent = 0x000d, FileSystem = 0x000e, PassThru = 0x000f, ImageInfo = 0x0101, ImageLayout = 0x0102, ImageMemXfer = 0x0103, ImageNativeXfer = 0x0104, ImageFileXfer = 0x0105, CieColor = 0x0106, GrayResponse = 0x0107, RGBResponse = 0x0108, JpegCompression = 0x0109, Palette8 = 0x010a, ExtImageInfo = 0x010b, SetupFileXfer2 = 0x0301 } enum TwMSG : short { Null = 0x0000, Get = 0x0001, GetCurrent = 0x0002, GetDefault = 0x0003, GetFirst = 0x0004, GetNext = 0x0005, Set = 0x0006, Reset = 0x0007, QuerySupport = 0x0008, XFerReady = 0x0101, CloseDSReq = 0x0102, CloseDSOK = 0x0103, DeviceEvent = 0x0104, CheckStatus = 0x0201, OpenDSM = 0x0301, CloseDSM = 0x0302, OpenDS = 0x0401, CloseDS = 0x0402, UserSelect = 0x0403, DisableDS = 0x0501, EnableDS = 0x0502, EnableDSUIOnly = 0x0503, ProcessEvent = 0x0601, EndXfer = 0x0701, StopFeeder = 0x0702, ChangeDirectory = 0x0801, CreateDirectory = 0x0802, Delete = 0x0803, FormatMedia = 0x0804, GetClose = 0x0805, GetFirstFile = 0x0806, GetInfo = 0x0807, GetNextFile = 0x0808, Rename = 0x0809, Copy = 0x080A, AutoCaptureDir = 0x080B, PassThru = 0x0901 } enum TwRC : short { Success = 0x0000, Failure = 0x0001, CheckStatus = 0x0002, Cancel = 0x0003, DSEvent = 0x0004, NotDSEvent = 0x0005, XferDone = 0x0006, EndOfList = 0x0007, InfoNotSupported = 0x0008, DataNotAvailable = 0x0009 } enum TwCC : short { Success = 0x0000, Bummer = 0x0001, LowMemory = 0x0002, NoDS = 0x0003, MaxConnections = 0x0004, OperationError = 0x0005, BadCap = 0x0006, BadProtocol = 0x0009, BadValue = 0x000a, SeqError = 0x000b, BadDest = 0x000c, CapUnsupported = 0x000d, CapBadOperation = 0x000e, CapSeqError = 0x000f, Denied = 0x0010, FileExists = 0x0011, FileNotFound = 0x0012, NotEmpty = 0x0013, PaperJam = 0x0014, PaperDoubleFeed = 0x0015, FileWriteError = 0x0016, CheckDeviceOnline = 0x0017 } enum TwOn : short { Array = 0x0003, Enum = 0x0004, One = 0x0005, Range = 0x0006, DontCare = -1 } enum TwType : short { Int8 = 0x0000, Int16 = 0x0001, Int32 = 0x0002, UInt8 = 0x0003, UInt16 = 0x0004, UInt32 = 0x0005, Bool = 0x0006, Fix32 = 0x0007, Frame = 0x0008, Str32 = 0x0009, Str64 = 0x000a, Str128 = 0x000b, Str255 = 0x000c, Str1024 = 0x000d, Str512 = 0x000e, DontCare16 = -1 // 0xFFFF } enum TwCap : short { // all data sources are REQUIRED to support these capabilities XferCount = 0x0001, // image data sources are REQUIRED to support these capabilities ICompression = 0x0100, IPixelType = 0x0101, IUnits = 0x0102, IXferMech = 0x0103, // all data sources MAY support these capabilities Author = 0x1000, Caption = 0x1001, FeederEnabled = 0x1002, FeederLoaded = 0x1003, Timedate = 0x1004, SupportedCapabilities = 0x1005, Extendedcaps = 0x1006, AutoFeed = 0x1007, ClearPage = 0x1008, FeedPage = 0x1009, RewindPage = 0x100a, Indicators = 0x100b, SupportedCapsExt = 0x100c, PaperDetectable = 0x100d, UIControllable = 0x100e, DeviceOnline = 0x100f, AutoScan = 0x1010, ThumbnailsEnabled = 0x1011, Duplex = 0x1012, DuplexEnabled = 0x1013, Enabledsuionly = 0x1014, CustomdsData = 0x1015, Endorser = 0x1016, JobControl = 0x1017, Alarms = 0x1018, AlarmVolume = 0x1019, AutomaticCapture = 0x101a, TimeBeforeFirstCapture = 0x101b, TimeBetweenCaptures = 0x101c, ClearBuffers = 0x101d, MaxBatchBuffers = 0x101e, DeviceTimeDate = 0x101f, PowerSupply = 0x1020, CameraPreviewUI = 0x1021, DeviceEvent = 0x1022, SerialNumber = 0x1024, Printer = 0x1026, PrinterEnabled = 0x1027, PrinterIndex = 0x1028, PrinterMode = 0x1029, PrinterString = 0x102a, PrinterSuffix = 0x102b, Language = 0x102c, FeederAlignment = 0x102d, FeederOrder = 0x102e, ReAcquireAllowed = 0x1030, BatteryMinutes = 0x1032, BatteryPercentage = 0x1033, CameraSide = 0x1034, Segmented = 0x1035, CameraEnabled = 0x1036, CameraOrder = 0x1037, MicrEnabled = 0x1038, FeederPrep = 0x1039, Feederpocket = 0x103a, // image data sources MAY support these capabilities Autobright = 0x1100, Brightness = 0x1101, Contrast = 0x1103, CustHalftone = 0x1104, ExposureTime = 0x1105, Filter = 0x1106, Flashused = 0x1107, Gamma = 0x1108, Halftones = 0x1109, Highlight = 0x110a, ImageFileFormat = 0x110c, LampState = 0x110d, LightSource = 0x110e, Orientation = 0x1110, PhysicalWidth = 0x1111, PhysicalHeight = 0x1112, Shadow = 0x1113, Frames = 0x1114, XNativeResolution = 0x1116, YNativeResolution = 0x1117, XResolution = 0x1118, YResolution = 0x1119, MaxFrames = 0x111a, Tiles = 0x111b, Bitorder = 0x111c, Ccittkfactor = 0x111d, Lightpath = 0x111e, Pixelflavor = 0x111f, Planarchunky = 0x1120, Rotation = 0x1121, SupportedSizes = 0x1122, Threshold = 0x1123, Xscaling = 0x1124, Yscaling = 0x1125, Bitordercodes = 0x1126, Pixelflavorcodes = 0x1127, Jpegpixeltype = 0x1128, Timefill = 0x112a, BitDepth = 0x112b, BitDepthReduction = 0x112c, Undefinedimagesize = 0x112d, Imagedataset = 0x112e, Extimageinfo = 0x112f, Minimumheight = 0x1130, Minimumwidth = 0x1131, Fliprotation = 0x1136, Barcodedetectionenabled = 0x1137, Supportedbarcodetypes = 0x1138, Barcodemaxsearchpriorities = 0x1139, Barcodesearchpriorities = 0x113a, Barcodesearchmode = 0x113b, Barcodemaxretries = 0x113c, Barcodetimeout = 0x113d, Zoomfactor = 0x113e, Patchcodedetectionenabled = 0x113f, Supportedpatchcodetypes = 0x1140, Patchcodemaxsearchpriorities = 0x1141, Patchcodesearchpriorities = 0x1142, Patchcodesearchmode = 0x1143, Patchcodemaxretries = 0x1144, Patchcodetimeout = 0x1145, Flashused2 = 0x1146, Imagefilter = 0x1147, Noisefilter = 0x1148, Overscan = 0x1149, Automaticborderdetection = 0x1150, Automaticdeskew = 0x1151, Automaticrotate = 0x1152, Jpegquality = 0x1153, Feedertype = 0x1154, Iccprofile = 0x1155, Autosize = 0x1156, AutomaticCropUsesFrame = 0x1157, AutomaticLengthDetection = 0x1158, AutomaticColorEnabled = 0x1159, AutomaticColorNonColorPixelType = 0x115a, ColorManagementEnabled = 0x115b, ImageMerge = 0x115c, ImageMergeHeightThreshold = 0x115d, SupoortedExtImageInfo = 0x115e, Audiofileformat = 0x1201, Xfermech = 0x1202 } enum TwCapPixelType : short { BW = 0, Gray = 1, RGB = 2, Palette = 3, CMY = 4, CMYK = 5, YUV = 6, YUVK = 7, CIEXYZ = 8, LAB = 9, SRGB = 10, SCRGB = 11, INFRARED = 16 } enum TwCapPageType : short { None = 0, A4 = 1, JISB5 = 2, UsLetter = 3, UsLegal = 4, A5 = 5, ISOB4 = 6, ISOB6 = 7, B = 8, UsLedger = 9, UsExecutive = 10, A3 = 11, ISOB3 = 12, A6 = 13, C4 = 14, C5 = 15, C6 = 16, _4A0 = 17, _2A0 = 18, A0 = 19, A1 = 20, A2 = 21, A7 = 22, A8 = 23, A9 = 24, A10 = 25, ISOB0 = 26, ISOB1 = 27, ISOB2 = 28, ISOB5 = 29, ISOB7 = 30, ISOB8 = 31, ISOB9 = 32, ISOB10 = 33, JISB0 = 34, JISB1 = 35, JISB2 = 36, JISB3 = 37, JISB4 = 38, JISB6 = 39, JISB7 = 40, JISB8 = 41, JISB9 = 42, JISB10 = 43, C0 = 44, C1 = 45, C2 = 46, C3 = 47, C7 = 48, C8 = 49, C9 = 50, C10 = 51, UsStatement = 52, BusinessCard = 53, MaxSize = 54, } enum TwCapBitDepthReductionType : short { THRESHOLD = 0, HALFTONE, CUSTHALFTONE, DIFFUSION, DYNAMICTHRESHOLD } enum Language : short { USA = 13 } enum Country : short { USA = 1 } class TwProtocol { public const short Major = 1; public const short Minor = 9; } // ------------------- STRUCTS -------------------------------------------- [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] class TwIdentity { public IntPtr Id; public TwVersion Version; public short ProtocolMajor; public short ProtocolMinor; public int SupportedGroups; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 34)] public string Manufacturer; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 34)] public string ProductFamily; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 34)] public string ProductName; public TwIdentity() { Id = IntPtr.Zero; } public override string ToString() { return ProductName; } } [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] struct TwVersion { public short MajorNum; public short MinorNum; public Language Language; public Country Country; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 34)] public string Info; } [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwUserInterface { public short ShowUI; // bool is strictly 32 bit, so use short public short ModalUI; public IntPtr ParentHand; } [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwStatus { public TwCC ConditionCode; public short Reserved; } [StructLayout(LayoutKind.Sequential, Pack = 2)] struct TwEvent { public IntPtr EventPtr; public TwMSG Message; } // On Windows, TwEvent.EventPtr will point to this structure [StructLayout(LayoutKind.Sequential, Pack = 4)] struct WINMSG { public IntPtr hwnd; public int message; public IntPtr wParam; public IntPtr lParam; public int time; public int x; public int y; } [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwImageInfo { public int XResolution; public int YResolution; public int ImageWidth; public int ImageLength; public short SamplesPerPixel; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public short[] BitsPerSample; public short BitsPerPixel; public short Planar; public short PixelType; public short Compression; } [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwFrame { private UInt32 fLeft; private UInt32 fTop; private UInt32 fRight; private UInt32 fBottom; public float Left { get { return TwainUtils.FloatFromFix32(fLeft); } set { fLeft = TwainUtils.Fix32FromFloat(value); } } public float Top { get { return TwainUtils.FloatFromFix32(fTop); } set { fTop = TwainUtils.Fix32FromFloat(value); } } public float Right { get { return TwainUtils.FloatFromFix32(fRight); } set { fRight = TwainUtils.Fix32FromFloat(value); } } public float Bottom { get { return TwainUtils.FloatFromFix32(fBottom); } set { fBottom = TwainUtils.Fix32FromFloat(value); } } } [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwImageLayout { public TwFrame Frame; public UInt32 DocumentNumber; public UInt32 PageNumber; public UInt32 FrameNumber; } [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwPendingXfers { public short Count; public int EOJ; } [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwCustomDsData { public UInt32 InfoLength; public IntPtr hData; } [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwContainer { virtual public TwType GetValueType(IntPtr handle) { return TwType.DontCare16; } virtual public object GetCurrentValue(IntPtr handle) { return null; } virtual public void SetCurrentValue(IntPtr handle, object value) { } virtual public int GetNumItems(IntPtr handle) { return 0; } virtual public object GetItem(IntPtr handle, int index) { return null; } virtual public int GetCurrentItemIndex(IntPtr handle) { return -1; } virtual public object GetMinValue(IntPtr handle) { return null; } virtual public object GetMaxValue(IntPtr handle) { return null; } virtual public object GetStepSize(IntPtr handle) { return null; } protected int SizeOf(TwType type) { int result; switch(type) { case TwType.Bool: { result = sizeof(bool); } break; case TwType.Fix32: { result = sizeof(float); } break; case TwType.UInt16: { result = sizeof(UInt16); } break; default: case TwType.DontCare16: { result = 0; } break; } return result; } protected UInt32 ToRawData(TwType type, object value) { UInt32 result; switch(type) { case TwType.Bool: { result = (UInt32)(((bool)value) ? 1 : 0); } break; case TwType.Fix32: { result = TwainUtils.Fix32FromFloat((float)value); } break; case TwType.UInt16: { result = (UInt32)(UInt16)value; } break; default: case TwType.DontCare16: { result = 0; } break; } return result; } protected object FromRawData(TwType type, UInt32 rawData) { // Convert data types that fit within 4 bytes // Extract the raw data of the correct size from the 4 byte field object result; switch(type) { case TwType.Bool: { byte data = (byte)(rawData & 0x000000ff); result = (bool)(data != 0); } break; case TwType.Fix32: { result = TwainUtils.FloatFromFix32(rawData); } break; default: case TwType.UInt16: { result = (UInt16)(rawData & 0x0000ffff); } break; } return result; } } // Capability container for one value. [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwOneValue : TwContainer { [MarshalAs(UnmanagedType.U2)] public TwType ItemType; public UInt32 Item; public TwOneValue() { ItemType = TwType.DontCare16; Item = 0; } public TwOneValue(TwType valueType, object value) { ItemType = valueType; Item = ToRawData(valueType, value); } override public TwType GetValueType(IntPtr handle) { return ItemType; } override public object GetCurrentValue(IntPtr handle) { return FromRawData(ItemType, Item); } } // Capability container for enumerated value. [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwEnumeration : TwContainer { [MarshalAs(UnmanagedType.U2)] public TwType ItemType; public UInt32 NumItems; public UInt32 CurrentIndex; public UInt32 DefaultIndex; override public TwType GetValueType(IntPtr handle) { return ItemType; } override public object GetCurrentValue(IntPtr handle) { return GetItem(handle, GetCurrentItemIndex(handle)); } override public int GetNumItems(IntPtr handle) { return (int)NumItems; } override public object GetItem(IntPtr handle, int index) { int offset = index * SizeOf(ItemType); IntPtr pItem = (IntPtr)(handle.ToInt64() + Marshal.SizeOf(this) + offset); uint bytes = (uint)Marshal.PtrToStructure(pItem, typeof(uint)); return FromRawData(ItemType, bytes); } override public int GetCurrentItemIndex(IntPtr handle) { return (int)CurrentIndex; } } // Capability container for enumerated value. [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwArray : TwContainer { [MarshalAs(UnmanagedType.U2)] public TwType ItemType; public UInt32 NumItems; override public TwType GetValueType(IntPtr handle) { return ItemType; } override public int GetNumItems(IntPtr handle) { return (int)NumItems; } override public object GetItem(IntPtr handle, int index) { int offset = index * SizeOf(ItemType); IntPtr pItem = (IntPtr)(handle.ToInt64() + Marshal.SizeOf(this) + offset); uint bytes = (uint)Marshal.PtrToStructure(pItem, typeof(uint)); return FromRawData(ItemType, bytes); } } // Capability container for range of value. [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwRange : TwContainer { [MarshalAs(UnmanagedType.U2)] public TwType ItemType; public UInt32 MinValue; public UInt32 MaxValue; public UInt32 StepSize; public UInt32 DefaultValue; public UInt32 CurrentValue; override public TwType GetValueType(IntPtr handle) { return ItemType; } override public object GetCurrentValue(IntPtr handle) { return FromRawData(ItemType, CurrentValue); } override public void SetCurrentValue(IntPtr handle, object value) { CurrentValue = ToRawData(ItemType, value); try { IntPtr pv = LibKernel32.GlobalLock(handle); Marshal.StructureToPtr(this, pv, true); } finally { LibKernel32.GlobalUnlock(handle); } } override public object GetMinValue(IntPtr handle) { return FromRawData(ItemType, MinValue); } override public object GetMaxValue(IntPtr handle) { return FromRawData(ItemType, MaxValue); } override public object GetStepSize(IntPtr handle) { return FromRawData(ItemType, StepSize); } } [StructLayout(LayoutKind.Sequential, Pack = 2)] class TwCapability { public TwCap CapabilityType; public TwOn ContainerType; public IntPtr Handle; public TwCapability(TwCap cap) : this(cap, TwType.DontCare16, null) { } public TwCapability(TwCap cap, TwType valueType, object value) { CapabilityType = cap; ContainerType = TwOn.One; value = CastFromCapabilityType(value); TwOneValue container = new TwOneValue(valueType, value); Handle = LibKernel32.GlobalAlloc(0x42, Marshal.SizeOf(container)); try { IntPtr pv = LibKernel32.GlobalLock(Handle); Marshal.StructureToPtr(container, pv, true); } finally { LibKernel32.GlobalUnlock(Handle); } } ~TwCapability() { if(Handle != IntPtr.Zero) { LibKernel32.GlobalFree(Handle); } } private TwContainer GetContainer() { TwContainer result; IntPtr pv = LibKernel32.GlobalLock(Handle); try { if(ContainerType == TwOn.One) { result = (TwContainer)Marshal.PtrToStructure(pv, typeof(TwOneValue)); } else if(ContainerType == TwOn.Enum) { result = (TwContainer)Marshal.PtrToStructure(pv, typeof(TwEnumeration)); } else if(ContainerType == TwOn.Array) { result = (TwContainer)Marshal.PtrToStructure(pv, typeof(TwArray)); } else if(ContainerType == TwOn.Range) { result = (TwContainer)Marshal.PtrToStructure(pv, typeof(TwRange)); } else { result = new TwContainer(); } } finally { LibKernel32.GlobalUnlock(Handle); } return result; } private object CastToCapabilityType(object item) { if(item != null) { switch(CapabilityType) { case TwCap.SupportedSizes: { item = (TwCapPageType)(UInt16)item; } break; case TwCap.IPixelType: { item = (TwCapPixelType)(UInt16)item; } break; case TwCap.SupportedCapabilities: { item = (TwCap)(UInt16)item; } break; case TwCap.BitDepthReduction: { item = (TwCapBitDepthReductionType)(UInt16)item; } break; case TwCap.BitDepth: { item = (UInt16)item; } break; } } return item; } private object CastFromCapabilityType(object item) { if(item != null) { switch(CapabilityType) { case TwCap.SupportedSizes: { item = (UInt16)(TwCapPageType)item; } break; case TwCap.IPixelType: { item = (UInt16)(TwCapPixelType)item; } break; case TwCap.SupportedCapabilities: { item = (UInt16)(TwCap)item; } break; case TwCap.BitDepthReduction: { item = (UInt16)(TwCapBitDepthReductionType)item; } break; case TwCap.BitDepth: { item = (UInt16)item; } break; } } return item; } public TwType GetValueType() { return GetContainer().GetValueType(Handle); } public object GetMinValue() { return GetContainer().GetMinValue(Handle); } public object GetMaxValue() { return GetContainer().GetMaxValue(Handle); } public object GetStepSize() { return GetContainer().GetStepSize(Handle); } public object GetCurrentValue() { return CastToCapabilityType(GetContainer().GetCurrentValue(Handle)); } public void SetCurrentValue(object value) { GetContainer().SetCurrentValue(Handle, CastFromCapabilityType(value)); } public int GetNumItems() { return GetContainer().GetNumItems(Handle); } public object GetItem(int index) { return CastToCapabilityType(GetContainer().GetItem(Handle, index)); } public int GetCurrentItemIndex() { return GetContainer().GetCurrentItemIndex(Handle); } } } }
/* * 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 OpenMetaverse; using OpenSim.Framework; using System.Reflection; using System.Text; namespace OpenSim.Region.CoreModules.World.Estate { /// <summary> /// Estate management console commands. /// </summary> public class EstateManagementCommands { protected EstateManagementModule m_module; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public EstateManagementCommands(EstateManagementModule module) { m_module = module; } public void Close() { } public void Initialise() { // m_log.DebugFormat("[ESTATE MODULE]: Setting up estate commands for region {0}", m_module.Scene.RegionInfo.RegionName); m_module.Scene.AddCommand("Regions", m_module, "set terrain texture", "set terrain texture <number> <uuid> [<x>] [<y>]", "Sets the terrain <number> to <uuid>, if <x> or <y> are specified, it will only " + "set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" + " that coordinate.", consoleSetTerrainTexture); m_module.Scene.AddCommand("Regions", m_module, "set terrain heights", "set terrain heights <corner> <min> <max> [<x>] [<y>]", "Sets the terrain texture heights on corner #<corner> to <min>/<max>, if <x> or <y> are specified, it will only " + "set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" + " that coordinate. Corner # SW = 0, NW = 1, SE = 2, NE = 3, all corners = -1.", consoleSetTerrainHeights); m_module.Scene.AddCommand("Regions", m_module, "set water height", "set water height <height> [<x>] [<y>]", "Sets the water height in meters. If <x> and <y> are specified, it will only set it on regions with a matching coordinate. " + "Specify -1 in <x> or <y> to wildcard that coordinate.", consoleSetWaterHeight); m_module.Scene.AddCommand( "Estates", m_module, "estate show", "estate show", "Shows all estates on the simulator.", ShowEstatesCommand); } #region CommandHandlers protected void consoleSetTerrainHeights(string module, string[] args) { string num = args[3]; string min = args[4]; string max = args[5]; int x = (args.Length > 6 ? int.Parse(args[6]) : -1); int y = (args.Length > 7 ? int.Parse(args[7]) : -1); if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x) { if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y) { int corner = int.Parse(num); float lowValue = float.Parse(min, Culture.NumberFormatInfo); float highValue = float.Parse(max, Culture.NumberFormatInfo); m_log.Debug("[ESTATEMODULE]: Setting terrain heights " + m_module.Scene.RegionInfo.RegionName + string.Format(" (C{0}, {1}-{2}", corner, lowValue, highValue)); switch (corner) { case -1: m_module.Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2SW = highValue; m_module.Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2NW = highValue; m_module.Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2SE = highValue; m_module.Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2NE = highValue; break; case 0: m_module.Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2SW = highValue; break; case 1: m_module.Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2NW = highValue; break; case 2: m_module.Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2SE = highValue; break; case 3: m_module.Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2NE = highValue; break; } m_module.Scene.RegionInfo.RegionSettings.Save(); m_module.TriggerRegionInfoChange(); m_module.sendRegionHandshakeToAll(); } } } protected void consoleSetTerrainTexture(string module, string[] args) { string num = args[3]; string uuid = args[4]; int x = (args.Length > 5 ? int.Parse(args[5]) : -1); int y = (args.Length > 6 ? int.Parse(args[6]) : -1); if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x) { if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y) { int corner = int.Parse(num); UUID texture = UUID.Parse(uuid); m_log.Debug("[ESTATEMODULE]: Setting terrain textures for " + m_module.Scene.RegionInfo.RegionName + string.Format(" (C#{0} = {1})", corner, texture)); switch (corner) { case 0: m_module.Scene.RegionInfo.RegionSettings.TerrainTexture1 = texture; break; case 1: m_module.Scene.RegionInfo.RegionSettings.TerrainTexture2 = texture; break; case 2: m_module.Scene.RegionInfo.RegionSettings.TerrainTexture3 = texture; break; case 3: m_module.Scene.RegionInfo.RegionSettings.TerrainTexture4 = texture; break; } m_module.Scene.RegionInfo.RegionSettings.Save(); m_module.TriggerRegionInfoChange(); m_module.sendRegionHandshakeToAll(); } } } protected void consoleSetWaterHeight(string module, string[] args) { string heightstring = args[3]; int x = (args.Length > 4 ? int.Parse(args[4]) : -1); int y = (args.Length > 5 ? int.Parse(args[5]) : -1); if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x) { if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y) { double selectedheight = double.Parse(heightstring); m_log.Debug("[ESTATEMODULE]: Setting water height in " + m_module.Scene.RegionInfo.RegionName + " to " + string.Format(" {0}", selectedheight)); m_module.Scene.RegionInfo.RegionSettings.WaterHeight = selectedheight; m_module.Scene.RegionInfo.RegionSettings.Save(); m_module.TriggerRegionInfoChange(); m_module.sendRegionHandshakeToAll(); } } } protected void ShowEstatesCommand(string module, string[] cmd) { StringBuilder report = new StringBuilder(); RegionInfo ri = m_module.Scene.RegionInfo; EstateSettings es = ri.EstateSettings; report.AppendFormat("Estate information for region {0}\n", ri.RegionName); report.AppendFormat( "{0,-20} {1,-7} {2,-20}\n", "Estate Name", "ID", "Owner"); report.AppendFormat( "{0,-20} {1,-7} {2,-20}\n", es.EstateName, es.EstateID, m_module.UserManager.GetUserName(es.EstateOwner)); MainConsole.Instance.Output(report.ToString()); } #endregion CommandHandlers } }
#pragma warning disable 1591 using AjaxControlToolkit.Design; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web; using System.Web.UI.HtmlControls; using System.Web.UI; using System.IO; using System.Web.UI.WebControls; using System.Drawing; namespace AjaxControlToolkit { /// <summary> /// AsyncFileUpload is an ASP.NET AJAX Control that allows you to asynchronously upload files to the server. /// The file uploading results can be checked both on the server and client sides. /// </summary> [Designer(typeof(AsyncFileUploadDesigner))] [RequiredScript(typeof(CommonToolkitScripts))] [ClientScriptResource("Sys.Extended.UI.AsyncFileUpload", AjaxControlToolkit.Constants.AsyncFileUploadName)] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), AjaxControlToolkit.Constants.AsyncFileUploadName + AjaxControlToolkit.Constants.IconPostfix)] public class AsyncFileUpload : ScriptControlBase { public static class Constants { public const string FileUploadIDKey = "AsyncFileUploadID", InternalErrorInvalidIFrame = "The ExtendedFileUpload control has encountered an error with the uploader in this page. Please refresh the page and try again.", fileUploadGUID = "b3b89160-3224-476e-9076-70b500c816cf"; public static class Errors { public const string NoFiles = "No files are attached to the upload.", FileNull = "The file attached is invalid.", NoFileName = "The file attached has an invalid filename.", InputStreamNull = "The file attached could not be read.", EmptyContentLength = "The file attached is empty."; } public static class StatusMessages { public const string UploadSuccessful = "The file uploaded successfully."; } } HttpPostedFile _postedFile = null; HtmlInputFile _inputFile = null; string _lastError = String.Empty; string _hiddenFieldID = String.Empty; string _innerTBID = String.Empty; bool _persistFile = false; bool _failedValidation = false; AsyncFileUploaderStyle _controlStyle = AsyncFileUploaderStyle.Traditional; public AsyncFileUpload() : base(true, HtmlTextWriterTag.Div) { } /// <summary> /// Fires when the file is successfully uploaded. /// </summary> [Bindable(true)] [Category("Server Events")] public event EventHandler<AsyncFileUploadEventArgs> UploadedComplete; /// <summary> /// Fires when the uploaded file is corrupted. /// </summary> [Bindable(true)] [Category("Server Events")] public event EventHandler<AsyncFileUploadEventArgs> UploadedFileError; bool IsDesignMode { get { return (HttpContext.Current == null); } } HttpPostedFile CurrentFile { get { return _persistFile ? PersistentStoreManager.Instance.GetFileFromSession(ClientID) : _postedFile; } } /// <summary> /// The name of a javascript function executed on the client side if the file upload started. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadStarted")] public string OnClientUploadStarted { get { return (string)(ViewState["OnClientUploadStarted"] ?? String.Empty); } set { ViewState["OnClientUploadStarted"] = value; } } /// <summary> /// The name of a javascript function executed on the client side after a file is successfully uploaded. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadComplete")] public string OnClientUploadComplete { get { return (string)(ViewState["OnClientUploadComplete"] ?? String.Empty); } set { ViewState["OnClientUploadComplete"] = value; } } /// <summary> /// The name of a javascript function executed on the client side if the file upload failed. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadError")] public string OnClientUploadError { get { return (string)(ViewState["OnClientUploadError"] ?? String.Empty); } set { ViewState["OnClientUploadError"] = value; } } /// <summary> /// Uploaded file bytes /// </summary> [BrowsableAttribute(false)] public byte[] FileBytes { get { PopulateObjectPriorToRender(ClientID); var file = CurrentFile; if(file != null) { try { return GetBytesFromStream(file.InputStream); } catch { } } return null; } } /// <summary> /// ID of a control that is shown while the file is being uploaded. /// </summary> [Category("Behavior")] [Description("ID of Throbber")] [DefaultValue("")] public string ThrobberID { get { return (string)(ViewState["ThrobberID"] ?? string.Empty); } set { ViewState["ThrobberID"] = value; } } /// <summary> /// The control's background color on upload complete. The default value is Lime. /// </summary> [Category("Appearance")] [TypeConverter(typeof(WebColorConverter))] [Description("Control's background color on upload complete.")] [DefaultValue(typeof(Color), "Lime")] public Color CompleteBackColor { get { return (Color)(ViewState["CompleteBackColor"] ?? Color.Lime); } set { ViewState["CompleteBackColor"] = value; } } /// <summary> /// The control's background color when uploading is in progress. /// The default value is White. /// </summary> [Category("Appearance")] [TypeConverter(typeof(WebColorConverter))] [Description("Control's background color when uploading is in progress.")] [DefaultValue(typeof(Color), "White")] public Color UploadingBackColor { get { return (Color)(ViewState["UploadingBackColor"] ?? Color.White); } set { ViewState["UploadingBackColor"] = value; } } /// <summary> /// The control's background color on an upload error. /// The default value is Red. /// </summary> [Category("Appearance")] [TypeConverter(typeof(WebColorConverter))] [Description("Control's background color on upload error.")] [DefaultValue(typeof(Color), "Red")] public Color ErrorBackColor { get { return (Color)(ViewState["ErrorBackColor"] ?? Color.Red); } set { ViewState["ErrorBackColor"] = value; } } /// <summary> /// The control's width (Unit). /// The default value is 355px. /// </summary> [DefaultValue(typeof(Unit), "")] [Category("Layout")] public override Unit Width { get { return base.Width; } set { base.Width = value; } } /// <summary> /// Whether validation is failed /// </summary> [BrowsableAttribute(false)] public bool FailedValidation { get { return _failedValidation; } set { _failedValidation = value; } } /// <summary> /// The control's appearance style (Traditional, Modern). The default value is Traditional. /// </summary> [Bindable(true)] [Category("Appearance")] [BrowsableAttribute(true)] [DefaultValue(AsyncFileUploaderStyle.Traditional)] public AsyncFileUploaderStyle UploaderStyle { get { return _controlStyle; } set { _controlStyle = value; } } /// <summary> /// A HttpPostedFile object that provides access to the uploaded file /// </summary> [BrowsableAttribute(false)] public HttpPostedFile PostedFile { get { PopulateObjectPriorToRender(ClientID); return CurrentFile; } } /// <summary> /// A bool value indicating whether the control contains a file /// </summary> [BrowsableAttribute(false)] public bool HasFile { get { PopulateObjectPriorToRender(ClientID); if(_persistFile) { return PersistentStoreManager.Instance.FileExists(ClientID); } return (_postedFile != null); } } /// <summary> /// Gets the name of a file on the client that is uploaded using the control. /// </summary> [BrowsableAttribute(false)] public string FileName { get { PopulateObjectPriorToRender(ClientID); if(_persistFile) { return Path.GetFileName(PersistentStoreManager.Instance.GetFileName(ClientID)); } else if(_postedFile != null) { return Path.GetFileName(_postedFile.FileName); } return String.Empty; } } /// <summary> /// Gets the name of a file on the client that is uploaded using the control. /// </summary> [BrowsableAttribute(false)] public string ContentType { get { PopulateObjectPriorToRender(ClientID); if(_persistFile) { return PersistentStoreManager.Instance.GetContentType(ClientID); } else if(_postedFile != null) { return _postedFile.ContentType; } return String.Empty; } } /// <summary> /// Gets a Stream object that points to an uploaded file to prepare for reading the content of the file. /// </summary> [BrowsableAttribute(false)] public Stream FileContent { get { PopulateObjectPriorToRender(ClientID); var file = CurrentFile; if(file == null || file.InputStream == null) return null; return file.InputStream; } } /// <summary> /// Whether a file is being uploaded. /// </summary> [BrowsableAttribute(false)] public bool IsUploading { get { return (Page.Request.QueryString[Constants.FileUploadIDKey] != null); } } /// <summary> /// Whether a file is stored in session. /// The default value is false. /// </summary> [Bindable(true)] [BrowsableAttribute(true)] [DefaultValue(false)] public bool PersistFile { get { return _persistFile; } set { _persistFile = value; } } /// <summary> /// Clears all uploaded files of a current control from session. /// </summary> public void ClearAllFilesFromPersistedStore() { PersistentStoreManager.Instance.ClearAllFilesFromSession(this.ClientID); } /// <summary> /// Clears all uploaded files of current control from session /// </summary> public void ClearFileFromPersistedStore() { PersistentStoreManager.Instance.RemoveFileFromSession(this.ClientID); } /// <summary> /// Saves the content of an uploaded file. /// </summary> /// <param name="fileName" type="String">Uploaded file name</param> public void SaveAs(string fileName) { PopulateObjectPriorToRender(this.ClientID); var file = CurrentFile; file.SaveAs(fileName); } void PopulateObjectPriorToRender(string controlId) { bool exists; if(_persistFile) exists = PersistentStoreManager.Instance.FileExists(controlId); else exists = (_postedFile != null); if((!exists) && (this.Page != null && this.Page.Request.Files.Count != 0)) ReceivedFile(controlId); } protected virtual void OnUploadedFileError(AsyncFileUploadEventArgs e) { if(UploadedFileError != null) UploadedFileError(this, e); } protected virtual void OnUploadedComplete(AsyncFileUploadEventArgs e) { if(UploadedComplete != null) UploadedComplete(this, e); } void ReceivedFile(string sendingControlID) { AsyncFileUploadEventArgs eventArgs = null; _lastError = String.Empty; if(this.Page.Request.Files.Count > 0) { HttpPostedFile file = null; if(sendingControlID == null || sendingControlID == String.Empty) { file = this.Page.Request.Files[0]; } else { foreach(string uploadedFile in this.Page.Request.Files) { var fileToUse = uploadedFile; var straggler = "$ctl02"; if(fileToUse.EndsWith(straggler)) fileToUse = fileToUse.Remove(fileToUse.Length - straggler.Length); if(fileToUse.Replace("$", "_").EndsWith(sendingControlID)) { file = this.Page.Request.Files[uploadedFile]; break; } } } if(file == null) { _lastError = Constants.Errors.FileNull; eventArgs = new AsyncFileUploadEventArgs( AsyncFileUploadState.Failed, Constants.Errors.FileNull, String.Empty, String.Empty ); OnUploadedFileError(eventArgs); } else if(file.FileName == String.Empty) { _lastError = Constants.Errors.NoFileName; eventArgs = new AsyncFileUploadEventArgs( AsyncFileUploadState.Unknown, Constants.Errors.NoFileName, file.FileName, file.ContentLength.ToString() ); OnUploadedFileError(eventArgs); } else if(file.InputStream == null) { _lastError = Constants.Errors.NoFileName; eventArgs = new AsyncFileUploadEventArgs( AsyncFileUploadState.Failed, Constants.Errors.NoFileName, file.FileName, file.ContentLength.ToString() ); OnUploadedFileError(eventArgs); } else if(file.ContentLength < 1) { _lastError = Constants.Errors.EmptyContentLength; eventArgs = new AsyncFileUploadEventArgs( AsyncFileUploadState.Unknown, Constants.Errors.EmptyContentLength, file.FileName, file.ContentLength.ToString() ); OnUploadedFileError(eventArgs); } else { eventArgs = new AsyncFileUploadEventArgs( AsyncFileUploadState.Success, String.Empty, file.FileName, file.ContentLength.ToString() ); if(_persistFile) { GC.SuppressFinalize(file); PersistentStoreManager.Instance.AddFileToSession(this.ClientID, file.FileName, file); } else { _postedFile = file; } OnUploadedComplete(eventArgs); } } } public byte[] GetBytesFromStream(Stream stream) { var buffer = new byte[32768]; using(var ms = new MemoryStream()) { stream.Seek(0, SeekOrigin.Begin); while(true) { int read = stream.Read(buffer, 0, buffer.Length); if(read <= 0) { return ms.ToArray(); } ms.Write(buffer, 0, read); } } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); string sendingControlID = this.Page.Request.QueryString[Constants.FileUploadIDKey]; if(sendingControlID == null || sendingControlID == this.ClientID) { ReceivedFile(this.ClientID); if(sendingControlID != null && sendingControlID.StartsWith(this.ClientID)) { string result; if(_lastError == String.Empty) { var bytes = this.FileBytes; if(bytes != null) result = bytes.Length.ToString() + "------" + ContentType; else result = String.Empty; } else { result = "error------" + _lastError; } TextWriter output = Page.Response.Output; output.Write("<div id='" + ClientID + "'>"); output.Write(result); output.Write("</div>"); } } } internal void CreateChilds() { Controls.Clear(); CreateChildControls(); } protected override void CreateChildControls() { PersistentStoreManager.Instance.ExtendedFileUploadGUID = Constants.fileUploadGUID; string sendingControlID = null; if(!IsDesignMode) sendingControlID = this.Page.Request.QueryString[Constants.FileUploadIDKey]; if(IsDesignMode || String.IsNullOrEmpty(sendingControlID)) { this._hiddenFieldID = GenerateHtmlInputHiddenControl(); string lastFileName = String.Empty; if(_persistFile) { if(PersistentStoreManager.Instance.FileExists(this.ClientID)) lastFileName = PersistentStoreManager.Instance.GetFileName(this.ClientID); } else if(_postedFile != null) { lastFileName = _postedFile.FileName; } GenerateHtmlInputFileControl(lastFileName); } } protected string GenerateHtmlInputHiddenControl() { var field = new HiddenField(); Controls.Add(field); return field.ClientID; } protected string GenerateHtmlInputFileControl(string lastFileName) { var div = new HtmlGenericControl("div"); Controls.Add(div); if(this.UploaderStyle == AsyncFileUploaderStyle.Modern) { var bgImageUrl = ToolkitResourceManager.GetImageHref(AjaxControlToolkit.Constants.AsyncFileUploadImage, this); var style = "background:url(" + bgImageUrl + ") no-repeat 100% 1px; height:24px; margin:0px; text-align:right;"; if(!Width.IsEmpty) style += "min-width:" + Width.ToString() + ";width:" + Width.ToString() + " !important;"; else style += "width:355px;"; div.Attributes.Add("style", style); } if(!(this.UploaderStyle == AsyncFileUploaderStyle.Modern && IsDesignMode)) { _inputFile = new HtmlInputFile(); if(!this.Enabled) _inputFile.Disabled = true; div.Controls.Add(_inputFile); _inputFile.Attributes.Add("id", _inputFile.Name.Replace("$", "_")); if(this.UploaderStyle != AsyncFileUploaderStyle.Modern) { if(BackColor != Color.Empty) _inputFile.Style[HtmlTextWriterStyle.BackgroundColor] = ColorTranslator.ToHtml(BackColor); if(!Width.IsEmpty) _inputFile.Style[HtmlTextWriterStyle.Width] = Width.ToString(); else _inputFile.Style[HtmlTextWriterStyle.Width] = "355px"; } } if(this.UploaderStyle == AsyncFileUploaderStyle.Modern) { var style = "opacity:0.0; -moz-opacity: 0.0; filter: alpha(opacity=00); font-size:14px;"; if(!Width.IsEmpty) style += "width:" + Width.ToString() + ";"; if(_inputFile != null) _inputFile.Attributes.Add("style", style); var textBox = new TextBox(); if(!IsDesignMode) { var div1 = new HtmlGenericControl("div"); div.Controls.Add(div1); style = "margin-top:-23px;text-align:left;"; div1.Attributes.Add("style", style); div1.Attributes.Add("type", "text"); div1.Controls.Add(textBox); style = "height:17px; font-size:12px; font-family:Tahoma;"; } else { div.Controls.Add(textBox); style = "height:23px; font-size:12px; font-family:Tahoma;"; } if(!Width.IsEmpty && Width.ToString().IndexOf("px") > 0) style += "width:" + (int.Parse(Width.ToString().Substring(0, Width.ToString().IndexOf("px"))) - 107).ToString() + "px;"; else style += "width:248px;"; if(lastFileName != String.Empty || this._failedValidation) { if((this.FileBytes != null && this.FileBytes.Length > 0) && (!this._failedValidation)) { style += "background-color:#00FF00;"; } else { this._failedValidation = false; style += "background-color:#FF0000;"; } textBox.Text = lastFileName; } else if(BackColor != Color.Empty) { style += "background-color:" + ColorTranslator.ToHtml(BackColor) + ";"; } textBox.ReadOnly = true; textBox.Attributes.Add("style", style); this._innerTBID = textBox.ClientID; } else if(IsDesignMode) { Controls.Clear(); Controls.Add(_inputFile); } return div.ClientID; } protected override void DescribeComponent(ScriptComponentDescriptor descriptor) { base.DescribeComponent(descriptor); if(!IsDesignMode) { if(this._hiddenFieldID != String.Empty) descriptor.AddElementProperty("hiddenField", this._hiddenFieldID); if(this._innerTBID != String.Empty) descriptor.AddElementProperty("innerTB", this._innerTBID); if(this._inputFile != null) descriptor.AddElementProperty("inputFile", this._inputFile.Name.Replace("$", "_")); descriptor.AddProperty("postBackUrl", this.Page.Request.RawUrl); descriptor.AddProperty("formName", Path.GetFileName(this.Page.Form.Name)); if(CompleteBackColor != Color.Empty) descriptor.AddProperty("completeBackColor", ColorTranslator.ToHtml(CompleteBackColor)); if(ErrorBackColor != Color.Empty) descriptor.AddProperty("errorBackColor", ColorTranslator.ToHtml(ErrorBackColor)); if(UploadingBackColor != Color.Empty) descriptor.AddProperty("uploadingBackColor", ColorTranslator.ToHtml(UploadingBackColor)); if(ThrobberID != string.Empty) { var control = this.FindControl(ThrobberID); if(control != null) descriptor.AddElementProperty("throbber", control.ClientID); } } } protected override Style CreateControlStyle() { return new AsyncFileUploadStyleWrapper(ViewState); } sealed class AsyncFileUploadStyleWrapper : Style { public AsyncFileUploadStyleWrapper(StateBag state) : base(state) { } protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) { base.FillStyleAttributes(attributes, urlResolver); attributes.Remove(HtmlTextWriterStyle.BackgroundColor); attributes.Remove(HtmlTextWriterStyle.Width); } } } } #pragma warning restore 1591
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.Sql; using Microsoft.WindowsAzure.Management.Sql.Models; namespace Microsoft.WindowsAzure { /// <summary> /// This is the main client class for interacting with the Azure SQL /// Database REST APIs. /// </summary> public static partial class DatabaseCopyOperationsExtensions { /// <summary> /// Starts a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the SQL Server where the source database /// resides. /// </param> /// <param name='databaseName'> /// Required. The name of the source database. /// </param> /// <param name='parameters'> /// Required. The additional parameters for the create database copy /// operation. /// </param> /// <returns> /// Represents a response to the create request. /// </returns> public static DatabaseCopyCreateResponse Create(this IDatabaseCopyOperations operations, string serverName, string databaseName, DatabaseCopyCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).CreateAsync(serverName, databaseName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Starts a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the SQL Server where the source database /// resides. /// </param> /// <param name='databaseName'> /// Required. The name of the source database. /// </param> /// <param name='parameters'> /// Required. The additional parameters for the create database copy /// operation. /// </param> /// <returns> /// Represents a response to the create request. /// </returns> public static Task<DatabaseCopyCreateResponse> CreateAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName, DatabaseCopyCreateParameters parameters) { return operations.CreateAsync(serverName, databaseName, parameters, CancellationToken.None); } /// <summary> /// Stops a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to stop. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Delete(this IDatabaseCopyOperations operations, string serverName, string databaseName, Guid databaseCopyName) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).DeleteAsync(serverName, databaseName, databaseCopyName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Stops a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to stop. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName, Guid databaseCopyName) { return operations.DeleteAsync(serverName, databaseName, databaseCopyName, CancellationToken.None); } /// <summary> /// Retrieves information about a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to retrieve. /// </param> /// <returns> /// Represents a response to the get request. /// </returns> public static DatabaseCopyGetResponse Get(this IDatabaseCopyOperations operations, string serverName, string databaseName, string databaseCopyName) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).GetAsync(serverName, databaseName, databaseCopyName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieves information about a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to retrieve. /// </param> /// <returns> /// Represents a response to the get request. /// </returns> public static Task<DatabaseCopyGetResponse> GetAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName, string databaseCopyName) { return operations.GetAsync(serverName, databaseName, databaseCopyName, CancellationToken.None); } /// <summary> /// Retrieves the list of SQL Server database copies for a database. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the database server to be queried. /// </param> /// <param name='databaseName'> /// Required. The name of the database to be queried. /// </param> /// <returns> /// Represents the response containing the list of database copies for /// a given database. /// </returns> public static DatabaseCopyListResponse List(this IDatabaseCopyOperations operations, string serverName, string databaseName) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).ListAsync(serverName, databaseName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieves the list of SQL Server database copies for a database. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the database server to be queried. /// </param> /// <param name='databaseName'> /// Required. The name of the database to be queried. /// </param> /// <returns> /// Represents the response containing the list of database copies for /// a given database. /// </returns> public static Task<DatabaseCopyListResponse> ListAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName) { return operations.ListAsync(serverName, databaseName, CancellationToken.None); } /// <summary> /// Updates a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to update. /// </param> /// <param name='parameters'> /// Required. The additional parameters for the update database copy /// operation. /// </param> /// <returns> /// Represents a response to the update request. /// </returns> public static DatabaseCopyUpdateResponse Update(this IDatabaseCopyOperations operations, string serverName, string databaseName, Guid databaseCopyName, DatabaseCopyUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).UpdateAsync(serverName, databaseName, databaseCopyName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to update. /// </param> /// <param name='parameters'> /// Required. The additional parameters for the update database copy /// operation. /// </param> /// <returns> /// Represents a response to the update request. /// </returns> public static Task<DatabaseCopyUpdateResponse> UpdateAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName, Guid databaseCopyName, DatabaseCopyUpdateParameters parameters) { return operations.UpdateAsync(serverName, databaseName, databaseCopyName, parameters, CancellationToken.None); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal delegate BoundStatement GenerateMethodBody(EEMethodSymbol method, DiagnosticBag diagnostics); /// <summary> /// Synthesized expression evaluation method. /// </summary> internal sealed class EEMethodSymbol : MethodSymbol { // We only create a single EE method (per EE type) that represents an arbitrary expression, // whose lowering may produce synthesized members (lambdas, dynamic sites, etc). // We may thus assume that the method ordinal is always 0. // // Consider making the implementation more flexible in order to avoid this assumption. // In future we might need to compile multiple expression and then we'll need to assign // a unique method ordinal to each of them to avoid duplicate synthesized member names. private const int _methodOrdinal = 0; internal readonly TypeMap TypeMap; internal readonly MethodSymbol SubstitutedSourceMethod; internal readonly ImmutableArray<LocalSymbol> Locals; internal readonly ImmutableArray<LocalSymbol> LocalsForBinding; private readonly EENamedTypeSymbol _container; private readonly string _name; private readonly ImmutableArray<Location> _locations; private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<ParameterSymbol> _parameters; private readonly ParameterSymbol _thisParameter; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; /// <summary> /// Invoked at most once to generate the method body. /// (If the compilation has no errors, it will be invoked /// exactly once, otherwise it may be skipped.) /// </summary> private readonly GenerateMethodBody _generateMethodBody; private TypeSymbol _lazyReturnType; // NOTE: This is only used for asserts, so it could be conditional on DEBUG. private readonly ImmutableArray<TypeParameterSymbol> _allTypeParameters; internal EEMethodSymbol( EENamedTypeSymbol container, string name, Location location, MethodSymbol sourceMethod, ImmutableArray<LocalSymbol> sourceLocals, ImmutableArray<LocalSymbol> sourceLocalsForBinding, ImmutableDictionary<string, DisplayClassVariable> sourceDisplayClassVariables, GenerateMethodBody generateMethodBody) { Debug.Assert(sourceMethod.IsDefinition); Debug.Assert(sourceMethod.ContainingSymbol == container.SubstitutedSourceType.OriginalDefinition); Debug.Assert(sourceLocals.All(l => l.ContainingSymbol == sourceMethod)); _container = container; _name = name; _locations = ImmutableArray.Create(location); // What we want is to map all original type parameters to the corresponding new type parameters // (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: // 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. // 2) The map cannot be constructed until all new type parameters exist. // Our solution is to pass each new type parameter a lazy reference to the type map. We then // initialize the map as soon as the new type parameters are available - and before they are // handed out - so that there is never a period where they can require the type map and find // it uninitialized. var sourceMethodTypeParameters = sourceMethod.TypeParameters; var allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters); var getTypeMap = new Func<TypeMap>(() => this.TypeMap); _typeParameters = sourceMethodTypeParameters.SelectAsArray( (tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap), (object)null); _allTypeParameters = container.TypeParameters.Concat(_typeParameters); this.TypeMap = new TypeMap(allSourceTypeParameters, _allTypeParameters); EENamedTypeSymbol.VerifyTypeParameters(this, _typeParameters); var substitutedSourceType = container.SubstitutedSourceType; this.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType); if (sourceMethod.Arity > 0) { this.SubstitutedSourceMethod = this.SubstitutedSourceMethod.Construct(_typeParameters.As<TypeSymbol>()); } TypeParameterChecker.Check(this.SubstitutedSourceMethod, _allTypeParameters); // Create a map from original parameter to target parameter. var parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(); var substitutedSourceThisParameter = this.SubstitutedSourceMethod.ThisParameter; var substitutedSourceHasThisParameter = (object)substitutedSourceThisParameter != null; if (substitutedSourceHasThisParameter) { _thisParameter = MakeParameterSymbol(0, GeneratedNames.ThisProxyFieldName(), substitutedSourceThisParameter); Debug.Assert(_thisParameter.Type == this.SubstitutedSourceMethod.ContainingType); parameterBuilder.Add(_thisParameter); } var ordinalOffset = (substitutedSourceHasThisParameter ? 1 : 0); foreach (var substitutedSourceParameter in this.SubstitutedSourceMethod.Parameters) { var ordinal = substitutedSourceParameter.Ordinal + ordinalOffset; Debug.Assert(ordinal == parameterBuilder.Count); var parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter); parameterBuilder.Add(parameter); } _parameters = parameterBuilder.ToImmutableAndFree(); var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var localsMap = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocals) { var local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); localsBuilder.Add(local); } this.Locals = localsBuilder.ToImmutableAndFree(); localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocalsForBinding) { LocalSymbol local; if (!localsMap.TryGetValue(sourceLocal, out local)) { local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); } localsBuilder.Add(local); } this.LocalsForBinding = localsBuilder.ToImmutableAndFree(); // Create a map from variable name to display class field. var displayClassVariables = PooledDictionary<string, DisplayClassVariable>.GetInstance(); foreach (var pair in sourceDisplayClassVariables) { var variable = pair.Value; var oldDisplayClassInstance = variable.DisplayClassInstance; // Note: the code path for DisplayClassInstanceFromLocal is equivalent to calling // oldDisplayClassInstance.ToOtherMethod, except that doing that would produce // a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding. var oldDisplayClassInstanceFromLocal = oldDisplayClassInstance as DisplayClassInstanceFromLocal; var newDisplayClassInstance = (oldDisplayClassInstanceFromLocal == null) ? oldDisplayClassInstance.ToOtherMethod(this, this.TypeMap) : new DisplayClassInstanceFromLocal((EELocalSymbol)localsMap[oldDisplayClassInstanceFromLocal.Local]); variable = variable.SubstituteFields(newDisplayClassInstance, this.TypeMap); displayClassVariables.Add(pair.Key, variable); } _displayClassVariables = displayClassVariables.ToImmutableDictionary(); displayClassVariables.Free(); localsMap.Free(); _generateMethodBody = generateMethodBody; } private ParameterSymbol MakeParameterSymbol(int ordinal, string name, ParameterSymbol sourceParameter) { return new SynthesizedParameterSymbol(this, sourceParameter.Type, ordinal, sourceParameter.RefKind, name, sourceParameter.CustomModifiers); } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.Ordinary; } } public override string Name { get { return _name; } } public override int Arity { get { return _typeParameters.Length; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return true; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData GetDllImportData() { return null; } internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } internal override bool TryGetThisParameter(out ParameterSymbol thisParameter) { thisParameter = null; return true; } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return this.SubstitutedSourceMethod.IsVararg; } } public override bool ReturnsVoid { get { return this.ReturnType.SpecialType == SpecialType.System_Void; } } public override bool IsAsync { get { return false; } } public override TypeSymbol ReturnType { get { if (_lazyReturnType == null) { throw new InvalidOperationException(); } return _lazyReturnType; } } public override ImmutableArray<TypeSymbol> TypeArguments { get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { throw ExceptionUtilities.Unreachable; } internal override Cci.CallingConvention CallingConvention { get { Debug.Assert(this.IsStatic); var cc = Cci.CallingConvention.Default; if (this.IsVararg) { cc |= Cci.CallingConvention.ExtraArguments; } if (this.IsGenericMethod) { cc |= Cci.CallingConvention.Generic; } return cc; } } internal override bool GenerateDebugInfo { get { return false; } } public override Symbol ContainingSymbol { get { return _container; } } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { throw ExceptionUtilities.Unreachable; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Internal; } } public override bool IsStatic { get { return true; } } public override bool IsVirtual { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } internal override ObsoleteAttributeData ObsoleteAttributeData { get { throw ExceptionUtilities.Unreachable; } } internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics) { var body = _generateMethodBody(this, diagnostics); var compilation = compilationState.Compilation; _lazyReturnType = CalculateReturnType(compilation, body); // Can't do this until the return type has been computed. TypeParameterChecker.Check(this, _allTypeParameters); if (diagnostics.HasAnyErrors()) { return; } DiagnosticsPass.IssueDiagnostics(compilation, body, diagnostics, this); if (diagnostics.HasAnyErrors()) { return; } // Check for use-site diagnostics (e.g. missing types in the signature). DiagnosticInfo useSiteDiagnosticInfo = null; this.CalculateUseSiteDiagnostic(ref useSiteDiagnosticInfo); if (useSiteDiagnosticInfo != null && useSiteDiagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnosticInfo, this.Locations[0]); return; } var declaredLocals = PooledHashSet<LocalSymbol>.GetInstance(); try { // Rewrite local declaration statement. body = (BoundStatement)LocalDeclarationRewriter.Rewrite(compilation, _container, declaredLocals, body); // Verify local declaration names. foreach (var local in declaredLocals) { Debug.Assert(local.Locations.Length > 0); var name = local.Name; if (name.StartsWith("$", StringComparison.Ordinal)) { diagnostics.Add(ErrorCode.ERR_UnexpectedCharacter, local.Locations[0], name[0]); return; } } // Rewrite references to placeholder "locals". body = (BoundStatement)PlaceholderLocalRewriter.Rewrite(compilation, _container, declaredLocals, body, diagnostics); if (diagnostics.HasAnyErrors()) { return; } } finally { declaredLocals.Free(); } var syntax = body.Syntax; var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance(); statementsBuilder.Add(body); // Insert an implicit return statement if necessary. if (body.Kind != BoundKind.ReturnStatement) { statementsBuilder.Add(new BoundReturnStatement(syntax, expressionOpt: null)); } var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var localsSet = PooledHashSet<LocalSymbol>.GetInstance(); foreach (var local in this.LocalsForBinding) { Debug.Assert(!localsSet.Contains(local)); localsBuilder.Add(local); localsSet.Add(local); } foreach (var local in this.Locals) { if (!localsSet.Contains(local)) { localsBuilder.Add(local); } } localsSet.Free(); body = new BoundBlock(syntax, localsBuilder.ToImmutableAndFree(), statementsBuilder.ToImmutableAndFree()) { WasCompilerGenerated = true }; Debug.Assert(!diagnostics.HasAnyErrors()); Debug.Assert(!body.HasErrors); bool sawLambdas; bool sawAwaitInExceptionHandler; body = LocalRewriter.Rewrite( compilation: this.DeclaringCompilation, method: this, methodOrdinal: _methodOrdinal, containingType: _container, statement: body, compilationState: compilationState, previousSubmissionFields: null, allowOmissionOfConditionalCalls: false, diagnostics: diagnostics, sawLambdas: out sawLambdas, sawAwaitInExceptionHandler: out sawAwaitInExceptionHandler); Debug.Assert(!sawAwaitInExceptionHandler); if (body.HasErrors) { return; } // Variables may have been captured by lambdas in the original method // or in the expression, and we need to preserve the existing values of // those variables in the expression. This requires rewriting the variables // in the expression based on the closure classes from both the original // method and the expression, and generating a preamble that copies // values into the expression closure classes. // // Consider the original method: // static void M() // { // int x, y, z; // ... // F(() => x + y); // } // and the expression in the EE: "F(() => x + z)". // // The expression is first rewritten using the closure class and local <1> // from the original method: F(() => <1>.x + z) // Then lambda rewriting introduces a new closure class that includes // the locals <1> and z, and a corresponding local <2>: F(() => <2>.<1>.x + <2>.z) // And a preamble is added to initialize the fields of <2>: // <2> = new <>c__DisplayClass0(); // <2>.<1> = <1>; // <2>.z = z; // Rewrite "this" and "base" references to parameter in this method. // Rewrite variables within body to reference existing display classes. body = (BoundStatement)CapturedVariableRewriter.Rewrite( this.SubstitutedSourceMethod.IsStatic ? null : _parameters[0], compilation.Conversions, _displayClassVariables, body, diagnostics); if (body.HasErrors) { Debug.Assert(false, "Please add a test case capturing whatever caused this assert."); return; } if (diagnostics.HasAnyErrors()) { return; } if (sawLambdas) { var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance(); var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance(); body = LambdaRewriter.Rewrite( loweredBody: body, thisType: this.SubstitutedSourceMethod.ContainingType, thisParameter: _thisParameter, method: this, methodOrdinal: _methodOrdinal, closureDebugInfoBuilder: closureDebugInfoBuilder, lambdaDebugInfoBuilder: lambdaDebugInfoBuilder, slotAllocatorOpt: null, compilationState: compilationState, diagnostics: diagnostics, assignLocals: true); // we don't need this information: closureDebugInfoBuilder.Free(); lambdaDebugInfoBuilder.Free(); } // Insert locals from the original method, // followed by any new locals. var block = (BoundBlock)body; var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in this.Locals) { Debug.Assert(!(local is EELocalSymbol) || (((EELocalSymbol)local).Ordinal == localBuilder.Count)); localBuilder.Add(local); } foreach (var local in block.Locals) { var oldLocal = local as EELocalSymbol; if (oldLocal != null) { Debug.Assert(localBuilder[oldLocal.Ordinal] == oldLocal); continue; } localBuilder.Add(local); } body = block.Update(localBuilder.ToImmutableAndFree(), block.Statements); TypeParameterChecker.Check(body, _allTypeParameters); compilationState.AddSynthesizedMethod(this, body); } private static TypeSymbol CalculateReturnType(CSharpCompilation compilation, BoundStatement bodyOpt) { if (bodyOpt == null) { // If the method doesn't do anything, then it doesn't return anything. return compilation.GetSpecialType(SpecialType.System_Void); } switch (bodyOpt.Kind) { case BoundKind.ReturnStatement: return ((BoundReturnStatement)bodyOpt).ExpressionOpt.Type; case BoundKind.ExpressionStatement: case BoundKind.LocalDeclaration: case BoundKind.MultipleLocalDeclarations: return compilation.GetSpecialType(SpecialType.System_Void); default: throw ExceptionUtilities.UnexpectedValue(bodyOpt.Kind); } } internal override void AddSynthesizedReturnTypeAttributes(ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedReturnTypeAttributes(ref attributes); if (this.ReturnType.ContainsDynamic()) { var compilation = this.DeclaringCompilation; if ((object)compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor) != null) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(this.ReturnType, this.ReturnTypeCustomModifiers.Length)); } } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return localPosition; } } }
using System; using System.Reflection; using System.Runtime.Serialization; using System.Security; using GameDevWare.Serialization.Serializers; // ReSharper disable once CheckNamespace namespace GameDevWare.Serialization { [Serializable] public class JsonSerializationException : SerializationException { public enum ErrorCode { SerializationException = 1, EmptyMemberName, DiscriminatorNotFirstMemberOfObject, CantCreateInstanceOfType, SerializationGraphIsTooBig, SerializationGraphIsTooDeep, TypeIsNotValid, SerializingUnknownType, SerializingSpecialSystemType, UnexpectedEndOfStream, UnexpectedMemberName, UnexpectedToken, UnknownEscapeSequence, UnknownDiscriminatorValue, SerializationFramesCorruption, StreamIsNotReadable, StreamIsNotWriteable, UnterminatedStringLiteral, UnknownNotation, MemberNameIsNotSpecified, TypeRequiresCustomSerializer } public ErrorCode Code { get; set; } public int LineNumber { get; set; } public int ColumnNumber { get; set; } public ulong CharactersWritten { get; set; } internal JsonSerializationException(string message, ErrorCode errorCode, IJsonReader reader = null) : base(message) { this.Code = errorCode; if (reader != null) this.Update(reader); } internal JsonSerializationException(string message, ErrorCode errorCode, IJsonReader reader, Exception innerException) : base(message, innerException) { this.Code = errorCode; if (reader != null) this.Update(reader); } internal JsonSerializationException(string message, Exception innerException) : base(message, innerException) { this.Code = ErrorCode.SerializationException; } protected JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { this.Code = (ErrorCode)info.GetInt32("Code"); this.LineNumber = info.GetInt32("LineNumber"); this.ColumnNumber = info.GetInt32("ColumnNumber"); this.CharactersWritten = info.GetUInt64("CharactersWritten"); } private void Update(IJsonReader reader) { this.LineNumber = reader.Value.LineNumber; this.ColumnNumber = reader.Value.ColumnNumber; //this.Path = reader.Value.Path; } [SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Code", (int)this.Code); info.AddValue("LineNumber", this.LineNumber); info.AddValue("ColumnNumber", this.ColumnNumber); info.AddValue("CharactersWritten", this.CharactersWritten); base.GetObjectData(info, context); } public static Exception MemberNameIsEmpty(IJsonReader reader) { return new JsonSerializationException ( "An empty member name was deserialized.", ErrorCode.EmptyMemberName, reader ); } public static Exception MemberNameIsNotSet() { return new JsonSerializationException ( "A member name is not set before writing value to object.", ErrorCode.MemberNameIsNotSpecified ); } public static Exception DiscriminatorIsNotFirstMember(IJsonReader reader) { return new JsonSerializationException ( string.Format("Discriminator member '{0}' should be first member of object.", ObjectSerializer.TYPE_MEMBER_NAME), ErrorCode.DiscriminatorNotFirstMemberOfObject, reader ); } public static Exception CantCreateInstanceOfType(Type type) { return new JsonSerializationException ( string.Format("Unable to deserialize instance of '{0}' because ", type.FullName) + (type.GetTypeInfo().IsAbstract ? "it is an abstract type." : "there is no parameterless constructor is defined on type."), ErrorCode.CantCreateInstanceOfType ); } public static Exception SerializationGraphIsTooBig(ulong maxObjects) { return new JsonSerializationException ( string.Format("Serialization graph is too big. Maximum serialized objects is {0}.", maxObjects), ErrorCode.SerializationGraphIsTooBig ); } public static Exception SerializationGraphIsTooDeep(ulong maxDepth) { return new JsonSerializationException ( string.Format("Serialization graph is too deep. Maximum depth is {0}.", maxDepth), ErrorCode.SerializationGraphIsTooDeep) ; } public static Exception TypeIsNotValid(Type type, string problem) { problem = problem.TrimEnd('.'); return new JsonSerializationException ( string.Format("Type '{0}' is not valid for serialization: {1}.", type.Name, problem), ErrorCode.TypeIsNotValid ); } public static Exception SerializingUnknownType(Type type) { return new JsonSerializationException ( string.Format("Attempt to serialize unknown type '{0}' failed.", type.FullName), ErrorCode.SerializingUnknownType ); } public static Exception SerializingSpecialSystemType(Type type) { return new JsonSerializationException ( string.Format("Attempt to serialize special system type '{0}' failed. This type is could be serialized.", type.FullName), ErrorCode.SerializingSpecialSystemType ); } public static Exception UnexpectedEndOfStream(IJsonReader reader) { return new JsonSerializationException ( "Unexpected end of stream while more data is expected.", ErrorCode.UnexpectedEndOfStream, reader ); } public static Exception UnexpectedMemberName(string memberName, string expected, IJsonReader reader) { return new JsonSerializationException ( string.Format("Unexpected member '{0}' is readed while '{1}' is expected.", memberName, expected), ErrorCode.UnexpectedMemberName, reader ); } public static Exception UnexpectedToken(IJsonReader reader, params JsonToken[] expectedTokens) { var tokensStr = default(string); if (expectedTokens.Length == 0) { tokensStr = "<no tokens>"; } else { #if NET40 tokensStr = String.Join(", ", expectedTokens); #else var tokens = expectedTokens.ConvertAll(c => c.ToString()); tokensStr = String.Join(", ", tokens); #endif } if (reader.Token == JsonToken.EndOfStream) { return UnexpectedEndOfStream(reader); } else if (expectedTokens.Length > 1) { return new JsonSerializationException ( string.Format("Unexpected token readed '{0}' while any of '{1}' are expected.", reader.Token, tokensStr), ErrorCode.UnexpectedToken, reader ); } else { return new JsonSerializationException ( string.Format("Unexpected token readed '{0}' while '{1}' is expected.", reader.Token, tokensStr), ErrorCode.UnexpectedToken, reader ); } } public static Exception UnknownEscapeSequence(string escape, IJsonReader reader) { return new JsonSerializationException ( string.Format("An unknown escape sequence '{0}' is readed.", escape), ErrorCode.UnknownEscapeSequence, reader ); } public static Exception SerializationFramesCorruption() { return new JsonSerializationException ( "Serialization frames are corrupted. Probably invalid Push/Pop sequence in TypeSerializers implementation.", ErrorCode.SerializationFramesCorruption ); } public static Exception StreamIsNotReadable() { return new JsonSerializationException ( "Can\'t perform deserialization from stream which doesn\'t support reading.", ErrorCode.StreamIsNotReadable ); } public static Exception StreamIsNotWriteable() { return new JsonSerializationException ( "Can\'t perform serialization to stream which doesn\'t support writing.", ErrorCode.StreamIsNotWriteable ); } public static Exception UnterminatedStringLiteral(IJsonReader reader) { return new JsonSerializationException ( "An unterminated string literal.", ErrorCode.UnterminatedStringLiteral, reader ); } public static Exception UnknownNotation(IJsonReader reader, string notation) { return new JsonSerializationException ( string.Format("An unknown notation '{0}'.", notation), ErrorCode.UnknownNotation, reader ); } public static Exception TypeRequiresCustomSerializer(Type type, Type typeSerializer) { return new JsonSerializationException ( string.Format("Type '{0}' can't be serialized by '{1}' and requires custom {2} registered in Json.DefaultSerializers.", type.FullName, typeSerializer.Name, typeof(TypeSerializer).Name), ErrorCode.TypeRequiresCustomSerializer ); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Outlining; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Text.Tagging; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Tagging { public class AsynchronousTaggerTests : TestBase { /// <summary> /// This hits a special codepath in the product that is optimized for more than 100 spans. /// I'm leaving this test here because it covers that code path (as shown by code coverage) /// </summary> [Fact] [WorkItem(530368)] public void LargeNumberOfSpans() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(@"class Program { void M() { int z = 0; z = z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z; } }")) { Callback tagProducer = (span, cancellationToken) => { return new List<ITagSpan<TestTag>>() { new TagSpan<TestTag>(span, new TestTag()) }; }; var asyncListener = new TaggerOperationListener(); var notificationService = workspace.GetService<IForegroundNotificationService>(); var eventSource = CreateEventSource(); var taggerProvider = new TestTaggerProvider( tagProducer, eventSource, workspace, asyncListener, notificationService); var document = workspace.Documents.First(); var textBuffer = document.TextBuffer; var snapshot = textBuffer.CurrentSnapshot; var tagger = taggerProvider.CreateTagger<TestTag>(textBuffer); using (IDisposable disposable = (IDisposable)tagger) { var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1)); var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans); eventSource.SendUpdateEvent(); asyncListener.CreateWaitTask().PumpingWait(); var tags = tagger.GetTags(snapshotSpans); Assert.Equal(1, tags.Count()); } } } [Fact] public void TestSynchronousOutlining() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile("class Program {\r\n\r\n}")) { var tagProvider = new OutliningTaggerProvider( workspace.GetService<IForegroundNotificationService>(), workspace.GetService<ITextEditorFactoryService>(), workspace.GetService<IEditorOptionsFactoryService>(), workspace.GetService<IProjectionBufferFactoryService>(), (IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>>)workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>()); var document = workspace.Documents.First(); var textBuffer = document.TextBuffer; var tagger = tagProvider.CreateTagger<IOutliningRegionTag>(textBuffer); using (var disposable = (IDisposable)tagger) { // The very first all to get tags should return the single outlining span. var tags = tagger.GetAllTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan()), CancellationToken.None); Assert.Equal(1, tags.Count()); } } } private static TestTaggerEventSource CreateEventSource() { return new TestTaggerEventSource(); } private static Mock<IOptionService> CreateFeatureOptionsMock() { var featureOptions = new Mock<IOptionService>(MockBehavior.Strict); featureOptions.Setup(s => s.GetOption(EditorComponentOnOffOptions.Tagger)).Returns(true); return featureOptions; } private sealed class TaggerOperationListener : AsynchronousOperationListener { } private sealed class TestTag : TextMarkerTag { public TestTag() : base("Test") { } } private delegate List<ITagSpan<TestTag>> Callback(SnapshotSpan span, CancellationToken cancellationToken); private sealed class TestTaggerProvider : AsynchronousTaggerProvider<TestTag> { private readonly Callback _callback; private readonly ITaggerEventSource _eventSource; private readonly Workspace _workspace; private readonly bool _disableCancellation; public TestTaggerProvider( Callback callback, ITaggerEventSource eventSource, Workspace workspace, IAsynchronousOperationListener asyncListener, IForegroundNotificationService notificationService, bool disableCancellation = false) : base(asyncListener, notificationService) { _callback = callback; _eventSource = eventSource; _workspace = workspace; _disableCancellation = disableCancellation; } protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { return _eventSource; } protected override Task ProduceTagsAsync(TaggerContext<TestTag> context, DocumentSnapshotSpan snapshotSpan, int? caretPosition) { var tags = _callback(snapshotSpan.SnapshotSpan, context.CancellationToken); if (tags != null) { foreach (var tag in tags) { context.AddTag(tag); } } return SpecializedTasks.EmptyTask; } } private sealed class TestTaggerEventSource : AbstractTaggerEventSource { public TestTaggerEventSource() : base(delay: TaggerDelay.NearImmediate) { } public void SendUpdateEvent() { this.RaiseChanged(); } public override void Connect() { } public override void Disconnect() { } } } }
// file: Model\StringProperty.cs // // summary: Implements the string property class using System; using System.IO; using numl.Utils; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; namespace numl.Model { /// <summary>Enumeration describing how to split a string property.</summary> public enum StringSplitType { /// <summary> /// Split string into corresponding characters /// </summary> Character, /// <summary> /// Split string into corresponding words /// </summary> Word } /// <summary>Represents a string property.</summary> [XmlRoot("StringProperty"), Serializable] public class StringProperty : Property { /// <summary>Default constructor.</summary> public StringProperty() : base() { // set to default conventions SplitType = StringSplitType.Word; Separator = " "; Dictionary = new string[] { }; Exclude = new string[] { }; AsEnum = false; Type = typeof(string); Discrete = true; } /// <summary>How to separate words (defaults to a space)</summary> /// <value>The separator.</value> public string Separator { get; set; } /// <summary>How to split text.</summary> /// <value>The type of the split.</value> public StringSplitType SplitType { get; set; } /// <summary>generated dictionary (using bag of words model)</summary> /// <value>The dictionary.</value> public string[] Dictionary { get; set; } /// <summary>Exclusion set (stopword removal)</summary> /// <value>The exclude.</value> public string[] Exclude { get; set; } /// <summary>Treat as enumeration.</summary> /// <value>true if as enum, false if not.</value> public bool AsEnum { get; set; } /// <summary>Expansion length (total distinct words)</summary> /// <value>The length.</value> public override int Length { get { return AsEnum ? 1 : Dictionary.Length; } } /// <summary>Expansion column names.</summary> /// <returns>List of distinct words and positions.</returns> public override IEnumerable<string> GetColumns() { if (AsEnum) yield return Name; else foreach (var s in Dictionary) yield return s; } /// <summary>Preprocess data set to create dictionary.</summary> /// <param name="examples">.</param> public override void PreProcess(IEnumerable<object> examples) { var q = from s in examples select Ject.Get(s, Name).ToString(); if (AsEnum) Dictionary = StringHelpers.BuildEnumDictionary(q).Select(kv => kv.Key).ToArray(); else { switch (SplitType) { case StringSplitType.Character: Dictionary = StringHelpers.BuildCharDictionary(q, Exclude).Select(kv => kv.Key).ToArray(); break; case StringSplitType.Word: Dictionary = StringHelpers.BuildWordDictionary(q, Separator, Exclude).Select(kv => kv.Key).ToArray(); break; } } } /// <summary>Convert from number to string.</summary> /// <param name="val">Number.</param> /// <returns>String.</returns> public override object Convert(double val) { if (AsEnum) return Dictionary[(int)val]; else return val.ToString(); } /// <summary>Convert string to list of numbers.</summary> /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception> /// <param name="o">in string.</param> /// <returns>lazy list of numbers.</returns> public override IEnumerable<double> Convert(object o) { // check for valid dictionary if (Dictionary == null || Dictionary.Length == 0) throw new InvalidOperationException(string.Format("{0} dictionaries do not exist.", Name)); // sanitize string string s = ""; if (o == null || string.IsNullOrEmpty(o.ToString()) || string.IsNullOrWhiteSpace(o.ToString())) s = StringHelpers.EMPTY_STRING; else s = o.ToString(); // returns single number if (AsEnum) yield return (double)StringHelpers.GetWordPosition(s, Dictionary, false); // returns list else foreach (double val in StringHelpers.GetWordCount(s, this)) yield return val; } /// <summary>import exclusion list from file.</summary> /// <param name="file">.</param> public void ImportExclusions(string file) { // add exclusions if (!string.IsNullOrEmpty(file) && !string.IsNullOrWhiteSpace(file) && File.Exists(file)) { Regex regex; if (SplitType == StringSplitType.Word) regex = new Regex(@"\w+", RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.IgnoreCase); else regex = new Regex(@"\w", RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.IgnoreCase); List<string> exclusionList = new List<string>(); using (StreamReader sr = new StreamReader(file)) { string line; while ((line = sr.ReadLine()) != null) { var match = regex.Match(line); // found something not already in list... if (match.Success && !exclusionList.Contains(match.Value.Trim().ToUpperInvariant())) exclusionList.Add(match.Value.Trim().ToUpperInvariant()); } } Exclude = exclusionList.OrderBy(s => s).ToArray(); } else Exclude = new string[] { }; } /// <summary>Generates an object from its XML representation.</summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader" /> stream from which the object is /// deserialized.</param> public override void ReadXml(XmlReader reader) { base.ReadXml(reader); Separator = reader.GetAttribute("Separator"); SplitType = (StringSplitType)Enum.Parse(typeof(StringSplitType), reader.GetAttribute("SplitType")); AsEnum = bool.Parse(reader.GetAttribute("AsEnum")); reader.ReadStartElement(); Dictionary = new string[int.Parse(reader.GetAttribute("Length"))]; reader.ReadStartElement("Dictionary"); for (int i = 0; i < Dictionary.Length; i++) Dictionary[i] = reader.ReadElementString("item"); reader.ReadEndElement(); Exclude = new string[int.Parse(reader.GetAttribute("Length"))]; reader.ReadStartElement("Exclude"); for (int i = 0; i < Exclude.Length; i++) Exclude[i] = reader.ReadElementString("item"); } /// <summary>Converts an object into its XML representation.</summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter" /> stream to which the object is /// serialized.</param> public override void WriteXml(XmlWriter writer) { base.WriteXml(writer); writer.WriteAttributeString("Separator", Separator); writer.WriteAttributeString("SplitType", SplitType.ToString()); writer.WriteAttributeString("AsEnum", AsEnum.ToString()); writer.WriteStartElement("Dictionary"); writer.WriteAttributeString("Length", Dictionary.Length.ToString()); for (int i = 0; i < Dictionary.Length; i++) { writer.WriteStartElement("item"); writer.WriteValue(Dictionary[i]); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("Exclude"); writer.WriteAttributeString("Length", Exclude.Length.ToString()); for (int i = 0; i < Exclude.Length; i++) { writer.WriteStartElement("item"); writer.WriteValue(Exclude[i]); writer.WriteEndElement(); } writer.WriteEndElement(); } } }
using System.Threading.Tasks; using System.Xml; using NFluent; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; using WireMock.Types; using WireMock.Util; using Xunit; using Moq; using WireMock.Handlers; using FluentAssertions; #if !NETSTANDARD1_3 using Wmhelp.XPath2; #endif namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithHandlebarsXPathTests { private const string ClientIp = "::1"; private readonly Mock<IFileSystemHandler> _filesystemHandlerMock; private readonly WireMockServerSettings _settings = new WireMockServerSettings(); public ResponseWithHandlebarsXPathTests() { _filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); _filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc"); _settings.FileSystemHandler = _filesystemHandlerMock.Object; } [Fact] public async Task Response_ProvideResponse_Handlebars_XPath_SelectSingleNode_Request_BodyAsString() { // Assign var body = new BodyData { BodyAsString = @"<todo-list> <todo-item id='a1'>abc</todo-item> <todo-item id='a2'>def</todo-item> <todo-item id='a3'>xyz</todo-item> </todo-list>", DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/xml") .WithBody("<response>{{XPath.SelectSingleNode request.body \"/todo-list/todo-item[1]\"}}</response>") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert var nav = new XmlDocument { InnerXml = response.Message.BodyData.BodyAsString }.CreateNavigator(); var node = nav.XPath2SelectSingleNode("/response/todo-item"); Check.That(node.Value).Equals("abc"); Check.That(node.GetAttribute("id", "")).Equals("a1"); } [Fact] public async Task Response_ProvideResponse_Handlebars_XPath_SelectSingleNode_Text_Request_BodyAsString() { // Assign var body = new BodyData { BodyAsString = @"<todo-list> <todo-item id='a1'>abc</todo-item> <todo-item id='a2'>def</todo-item> <todo-item id='a3'>xyz</todo-item> </todo-list>", DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/xml") .WithBody("{{XPath.SelectSingleNode request.body \"/todo-list/todo-item[1]/text()\"}}") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("abc"); } [Fact] public async Task Response_ProvideResponse_Handlebars_XPath_SelectNodes_Request_BodyAsString() { // Assign var body = new BodyData { BodyAsString = @"<todo-list> <todo-item id='a1'>abc</todo-item> <todo-item id='a2'>def</todo-item> <todo-item id='a3'>xyz</todo-item> </todo-list>", DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/xml") .WithBody("<response>{{XPath.SelectNodes request.body \"/todo-list/todo-item\"}}</response>") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert var nav = new XmlDocument { InnerXml = response.Message.BodyData.BodyAsString }.CreateNavigator(); var nodes = nav.XPath2SelectNodes("/response/todo-item"); Check.That(nodes.Count + 1).IsEqualTo(3); } [Fact] public async Task Response_ProvideResponse_Handlebars_XPath_SelectSingleNode_Request_SoapXML_BodyAsString() { // Assign string soap = @" <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:ns=""http://www.Test.nl/XMLHeader/10"" xmlns:req=""http://www.Test.nl/Betalen/COU/Services/RdplDbTknLystByOvkLyst/8/Req""> <soapenv:Header> <ns:TestHeader> <ns:HeaderVersion>10</ns:HeaderVersion> <ns:MessageId>MsgId10</ns:MessageId> <ns:ServiceRequestorDomain>Betalen</ns:ServiceRequestorDomain> <ns:ServiceRequestorId>CRM</ns:ServiceRequestorId> <ns:ServiceProviderDomain>COU</ns:ServiceProviderDomain> <ns:ServiceId>RdplDbTknLystByOvkLyst</ns:ServiceId> <ns:ServiceVersion>8</ns:ServiceVersion> <ns:FaultIndication>N</ns:FaultIndication> <ns:MessageTimestamp>?</ns:MessageTimestamp> </ns:TestHeader> </soapenv:Header> <soapenv:Body> <req:RdplDbTknLystByOvkLyst_REQ> <req:AanleveraarCode>CRM</req:AanleveraarCode> <!--Optional:--> <req:AanleveraarDetail>CRMi</req:AanleveraarDetail> <req:BerichtId>BerId</req:BerichtId> <req:BerichtType>RdplDbTknLystByOvkLyst</req:BerichtType> <!--Optional:--> <req:OpgenomenBedragenGewenstIndicatie>N</req:OpgenomenBedragenGewenstIndicatie> <req:TokenIdLijst> <!--1 to 10 repetitions:--> <req:TokenId>0000083256</req:TokenId> <req:TokenId>0000083259</req:TokenId> </req:TokenIdLijst> </req:RdplDbTknLystByOvkLyst_REQ> </soapenv:Body> </soapenv:Envelope>"; var body = new BodyData { BodyAsString = soap, DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/xml") .WithBody("<response>{{XPath.SelectSingleNode request.body \"//*[local-name()='TokenIdLijst']\"}}</response>") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert response.Message.BodyData.BodyAsString.Should().Contain("TokenIdLijst").And.Contain("0000083256").And.Contain("0000083259"); } [Fact] public async Task Response_ProvideResponse_Handlebars_XPath_Evaluate_Request_BodyAsString() { // Assign var body = new BodyData { BodyAsString = @"<todo-list> <todo-item id='a1'>abc</todo-item> <todo-item id='a2'>def</todo-item> <todo-item id='a3'>xyz</todo-item> </todo-list>", DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/xml") .WithBody("{{XPath.Evaluate request.body \"boolean(/todo-list[count(todo-item) = 3])\"}}") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert Check.That(response.Message.BodyData.BodyAsString).IsEqualIgnoringCase("True"); } [Fact] public async Task Response_ProvideResponse_Handlebars_XPath_Evaluate_Attribute_Request_BodyAsString() { // Assign var body = new BodyData { BodyAsString = @"<todo-list> <todo-item id='a1'>abc</todo-item> <todo-item id='a2'>def</todo-item> <todo-item id='a3'>xyz</todo-item> </todo-list>", DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/xml") .WithBody("{{XPath.Evaluate request.body \"string(/todo-list/todo-item[1]/@id)\"}}") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("a1"); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateDefaultConstructors { public class GenerateDefaultConstructorsTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new GenerateDefaultConstructorsCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestProtectedBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { protected B(int x) { } }", @"class C : B { protected C(int x) : base(x) { } } class B { protected B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPublicBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } class B { public B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestInternalBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPrivateBase() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { } class B { private B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefOutParams() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(ref int x, out string s, params bool[] b) { } }", @"class C : B { internal C(ref int x, out string s, params bool[] b) : base(ref x, out s, b) { } } class B { internal B(ref int x, out string s, params bool[] b) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { protected C(string x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefactoring1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(bool x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll_WithTuples() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C((bool, bool) x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", @"class C : B { public C((bool, bool) x) { } protected C((string, string) x) : base(x) { } internal C((int, int) x) : base(x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestMissing1() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { public C(int x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_1() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(int y) { } } class B { internal B(int x) { } }", @"class C : B { public C(int y) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_2() { await TestInRegularAndScriptAsync( @"class C : [||]B { private C(int y) { } } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } private C(int y) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixCount1() { await TestActionCountAsync( @"class C : [||]B { } class B { public B(int x) { } }", count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] [WorkItem(544070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544070")] public async Task TestException1() { await TestInRegularAndScriptAsync( @"using System; class Program : Excep[||]tion { }", @"using System; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } }", index: 4, ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program() { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException3() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException4() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] public async Task Tuple() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int, string) x) { } }", @"class C : B { public C((int, string) x) : base(x) { } } class B { public B((int, string) x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] public async Task TupleWithNames() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int a, string b) x) { } }", @"class C : B { public C((int a, string b) x) : base(x) { } } class B { public B((int a, string b) x) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass() { await TestInRegularAndScriptAsync( @"class Base { public Base(string value) { } } class [||]Derived : Base { }", @"class Base { public Base(string value) { } } class Derived : Base { public Derived(string value) : base(value) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass2() { await TestInRegularAndScriptAsync( @"class Base { public Base(int a, string value = null) { } } class [||]Derived : Base { }", @"class Base { public Base(int a, string value = null) { } } class Derived : Base { public Derived(int a, string value = null) : base(a, value) { } }"); } [WorkItem(19953, "https://github.com/dotnet/roslyn/issues/19953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestNotOnEnum() { await TestMissingInRegularAndScriptAsync( @"enum [||]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.Collections.Generic; using System.Runtime.InteropServices; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class PfxTests { public static IEnumerable<object[]> BrainpoolCurvesPfx { get { #if NETNATIVE yield break; #else yield return new object[] { TestData.ECDsabrainpoolP160r1_Pfx }; yield return new object[] { TestData.ECDsabrainpoolP160r1_Explicit_Pfx }; #endif } } [Fact] public static void TestConstructor() { byte[] expectedThumbprint = "71cb4e2b02738ad44f8b382c93bd17ba665f9914".HexToByteArray(); using (var c = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { string subject = c.Subject; Assert.Equal("CN=MyName", subject); byte[] thumbPrint = c.GetCertHash(); Assert.Equal(expectedThumbprint, thumbPrint); } } [Fact] public static void EnsurePrivateKeyPreferred() { using (var cert = new X509Certificate2(TestData.ChainPfxBytes, TestData.ChainPfxPassword)) { // While checking cert.HasPrivateKey first is most matching of the test description, asserting // on the certificate's simple name will provide a more diagnosable failure. Assert.Equal("test.local", cert.GetNameInfo(X509NameType.SimpleName, false)); Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey"); } } [Fact] public static void TestRawData() { byte[] expectedRawData = ( "308201e530820152a0030201020210d5b5bc1c458a558845" + "bff51cb4dff31c300906052b0e03021d05003011310f300d" + "060355040313064d794e616d65301e170d31303034303130" + "38303030305a170d3131303430313038303030305a301131" + "0f300d060355040313064d794e616d6530819f300d06092a" + "864886f70d010101050003818d0030818902818100b11e30" + "ea87424a371e30227e933ce6be0e65ff1c189d0d888ec8ff" + "13aa7b42b68056128322b21f2b6976609b62b6bc4cf2e55f" + "f5ae64e9b68c78a3c2dacc916a1bc7322dd353b32898675c" + "fb5b298b176d978b1f12313e3d865bc53465a11cca106870" + "a4b5d50a2c410938240e92b64902baea23eb093d9599e9e3" + "72e48336730203010001a346304430420603551d01043b30" + "39801024859ebf125e76af3f0d7979b4ac7a96a113301131" + "0f300d060355040313064d794e616d658210d5b5bc1c458a" + "558845bff51cb4dff31c300906052b0e03021d0500038181" + "009bf6e2cf830ed485b86d6b9e8dffdcd65efc7ec145cb93" + "48923710666791fcfa3ab59d689ffd7234b7872611c5c23e" + "5e0714531abadb5de492d2c736e1c929e648a65cc9eb63cd" + "84e57b5909dd5ddf5dbbba4a6498b9ca225b6e368b94913b" + "fc24de6b2bd9a26b192b957304b89531e902ffc91b54b237" + "bb228be8afcda26476").HexToByteArray(); using (var c = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { byte[] rawData = c.RawData; Assert.Equal(expectedRawData, rawData); } } [Fact] public static void TestPrivateKey() { using (var c = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { bool hasPrivateKey = c.HasPrivateKey; Assert.True(hasPrivateKey); using (RSA rsa = c.GetRSAPrivateKey()) { byte[] hash = new byte[20]; byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); Assert.Equal(s_expectedSig, sig); } } } [Fact] public static void ExportWithPrivateKey() { using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable)) { const string password = "NotVerySecret"; byte[] pkcs12 = cert.Export(X509ContentType.Pkcs12, password); using (var certFromPfx = new X509Certificate2(pkcs12, password)) { Assert.True(certFromPfx.HasPrivateKey); Assert.Equal(cert, certFromPfx); } } } [Fact] public static void ReadECDsaPrivateKey_WindowsPfx() { using (var cert = new X509Certificate2(TestData.ECDsaP256_DigitalSignature_Pfx_Windows, "Test")) using (ECDsa ecdsa = cert.GetECDsaPrivateKey()) { Assert.NotNull(ecdsa); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { AssertEccAlgorithm(ecdsa, "ECDSA_P256"); } } } [Theory, MemberData(nameof(BrainpoolCurvesPfx))] public static void ReadECDsaPrivateKey_BrainpoolP160r1_Pfx(byte[] pfxData) { try { using (var cert = new X509Certificate2(pfxData, TestData.PfxDataPassword)) { using (ECDsa ecdsa = cert.GetECDsaPrivateKey()) { Assert.NotNull(ecdsa); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { AssertEccAlgorithm(ecdsa, "ECDH"); } } } } catch (CryptographicException) { // Windows 7, Windows 8, Ubuntu 14, CentOS can fail. Verify known good platforms don't fail. Assert.False(PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10); Assert.False(PlatformDetection.IsUbuntu1604); Assert.False(PlatformDetection.IsUbuntu1610); Assert.False(PlatformDetection.IsOSX); return; } } [Fact] public static void ReadECDsaPrivateKey_OpenSslPfx() { using (var cert = new X509Certificate2(TestData.ECDsaP256_DigitalSignature_Pfx_OpenSsl, "Test")) using (ECDsa ecdsa = cert.GetECDsaPrivateKey()) { Assert.NotNull(ecdsa); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // If Windows were to start detecting this case as ECDSA that wouldn't be bad, // but this assert is the only proof that this certificate was made with OpenSSL. // // Windows ECDSA PFX files contain metadata in the private key keybag which identify it // to Windows as ECDSA. OpenSSL doesn't have anywhere to persist that data when // extracting it to the key PEM file, and so no longer has it when putting the PFX // together. But, it also wouldn't have had the Windows-specific metadata when the // key was generated on the OpenSSL side in the first place. // // So, again, it's not important that Windows "mis-detects" this as ECDH. What's // important is that we were able to create an ECDsa object from it. AssertEccAlgorithm(ecdsa, "ECDH_P256"); } } } // Keep the ECDsaCng-ness contained within this helper method so that it doesn't trigger a // FileNotFoundException on Unix. private static void AssertEccAlgorithm(ECDsa ecdsa, string algorithmId) { ECDsaCng cng = ecdsa as ECDsaCng; if (cng != null) { Assert.Equal(algorithmId, cng.Key.Algorithm.Algorithm); } } private static readonly byte[] s_expectedSig = ("44b15120b8c7de19b4968d761600ffb8c54e5d0c1bcaba0880a20ab48912c8fdfa81b28134eabf58f3211a0d1eefdaae115e7872d5a67045c3b62a5da4393940e5a496" + "413a6d55ea6309d0013e90657c83c6e40aa8fafeee66acbb6661c1419011e1fde6f4fcc328bd7e537e4aa2dbe216d8f1f3aa7e5ec60eb9cfdca7a41d74").HexToByteArray(); private static X509Certificate2 Rewrap(this X509Certificate2 c) { X509Certificate2 newC = new X509Certificate2(c.Handle); c.Dispose(); return newC; } } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic.Models { using Azure; using Management; using Logic; using Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// The X12 agreement envelope settings. /// </summary> public partial class X12EnvelopeSettings { /// <summary> /// Initializes a new instance of the X12EnvelopeSettings class. /// </summary> public X12EnvelopeSettings() { } /// <summary> /// Initializes a new instance of the X12EnvelopeSettings class. /// </summary> /// <param name="controlStandardsId">The controls standards id.</param> /// <param name="useControlStandardsIdAsRepetitionCharacter">The value /// indicating whether to use control standards id as repetition /// character.</param> /// <param name="senderApplicationId">The sender application /// id.</param> /// <param name="receiverApplicationId">The receiver application /// id.</param> /// <param name="controlVersionNumber">The control version /// number.</param> /// <param name="interchangeControlNumberLowerBound">The interchange /// control number lower bound.</param> /// <param name="interchangeControlNumberUpperBound">The interchange /// control number upper bound.</param> /// <param name="rolloverInterchangeControlNumber">The value indicating /// whether to rollover interchange control number.</param> /// <param name="enableDefaultGroupHeaders">The value indicating /// whether to enable default group headers.</param> /// <param name="groupControlNumberLowerBound">The group control number /// lower bound.</param> /// <param name="groupControlNumberUpperBound">The group control number /// upper bound.</param> /// <param name="rolloverGroupControlNumber">The value indicating /// whether to rollover group control number.</param> /// <param name="groupHeaderAgencyCode">The group header agency /// code.</param> /// <param name="groupHeaderVersion">The group header version.</param> /// <param name="transactionSetControlNumberLowerBound">The transaction /// set control number lower bound.</param> /// <param name="transactionSetControlNumberUpperBound">The transaction /// set control number upper bound.</param> /// <param name="rolloverTransactionSetControlNumber">The value /// indicating whether to rollover transaction set control /// number.</param> /// <param name="overwriteExistingTransactionSetControlNumber">The /// value indicating whether to overwrite existing transaction set /// control number.</param> /// <param name="groupHeaderDateFormat">The group header date format. /// Possible values include: 'NotSpecified', 'CCYYMMDD', /// 'YYMMDD'</param> /// <param name="groupHeaderTimeFormat">The group header time format. /// Possible values include: 'NotSpecified', 'HHMM', 'HHMMSS', /// 'HHMMSSdd', 'HHMMSSd'</param> /// <param name="usageIndicator">The usage indicator. Possible values /// include: 'NotSpecified', 'Test', 'Information', /// 'Production'</param> /// <param name="functionalGroupId">The functional group id.</param> /// <param name="transactionSetControlNumberPrefix">The transaction set /// control number prefix.</param> /// <param name="transactionSetControlNumberSuffix">The transaction set /// control number suffix.</param> public X12EnvelopeSettings(int controlStandardsId, bool useControlStandardsIdAsRepetitionCharacter, string senderApplicationId, string receiverApplicationId, string controlVersionNumber, int interchangeControlNumberLowerBound, int interchangeControlNumberUpperBound, bool rolloverInterchangeControlNumber, bool enableDefaultGroupHeaders, int groupControlNumberLowerBound, int groupControlNumberUpperBound, bool rolloverGroupControlNumber, string groupHeaderAgencyCode, string groupHeaderVersion, int transactionSetControlNumberLowerBound, int transactionSetControlNumberUpperBound, bool rolloverTransactionSetControlNumber, bool overwriteExistingTransactionSetControlNumber, X12DateFormat groupHeaderDateFormat, X12TimeFormat groupHeaderTimeFormat, UsageIndicator usageIndicator, string functionalGroupId = default(string), string transactionSetControlNumberPrefix = default(string), string transactionSetControlNumberSuffix = default(string)) { ControlStandardsId = controlStandardsId; UseControlStandardsIdAsRepetitionCharacter = useControlStandardsIdAsRepetitionCharacter; SenderApplicationId = senderApplicationId; ReceiverApplicationId = receiverApplicationId; ControlVersionNumber = controlVersionNumber; InterchangeControlNumberLowerBound = interchangeControlNumberLowerBound; InterchangeControlNumberUpperBound = interchangeControlNumberUpperBound; RolloverInterchangeControlNumber = rolloverInterchangeControlNumber; EnableDefaultGroupHeaders = enableDefaultGroupHeaders; FunctionalGroupId = functionalGroupId; GroupControlNumberLowerBound = groupControlNumberLowerBound; GroupControlNumberUpperBound = groupControlNumberUpperBound; RolloverGroupControlNumber = rolloverGroupControlNumber; GroupHeaderAgencyCode = groupHeaderAgencyCode; GroupHeaderVersion = groupHeaderVersion; TransactionSetControlNumberLowerBound = transactionSetControlNumberLowerBound; TransactionSetControlNumberUpperBound = transactionSetControlNumberUpperBound; RolloverTransactionSetControlNumber = rolloverTransactionSetControlNumber; TransactionSetControlNumberPrefix = transactionSetControlNumberPrefix; TransactionSetControlNumberSuffix = transactionSetControlNumberSuffix; OverwriteExistingTransactionSetControlNumber = overwriteExistingTransactionSetControlNumber; GroupHeaderDateFormat = groupHeaderDateFormat; GroupHeaderTimeFormat = groupHeaderTimeFormat; UsageIndicator = usageIndicator; } /// <summary> /// Gets or sets the controls standards id. /// </summary> [JsonProperty(PropertyName = "controlStandardsId")] public int ControlStandardsId { get; set; } /// <summary> /// Gets or sets the value indicating whether to use control standards /// id as repetition character. /// </summary> [JsonProperty(PropertyName = "useControlStandardsIdAsRepetitionCharacter")] public bool UseControlStandardsIdAsRepetitionCharacter { get; set; } /// <summary> /// Gets or sets the sender application id. /// </summary> [JsonProperty(PropertyName = "senderApplicationId")] public string SenderApplicationId { get; set; } /// <summary> /// Gets or sets the receiver application id. /// </summary> [JsonProperty(PropertyName = "receiverApplicationId")] public string ReceiverApplicationId { get; set; } /// <summary> /// Gets or sets the control version number. /// </summary> [JsonProperty(PropertyName = "controlVersionNumber")] public string ControlVersionNumber { get; set; } /// <summary> /// Gets or sets the interchange control number lower bound. /// </summary> [JsonProperty(PropertyName = "interchangeControlNumberLowerBound")] public int InterchangeControlNumberLowerBound { get; set; } /// <summary> /// Gets or sets the interchange control number upper bound. /// </summary> [JsonProperty(PropertyName = "interchangeControlNumberUpperBound")] public int InterchangeControlNumberUpperBound { get; set; } /// <summary> /// Gets or sets the value indicating whether to rollover interchange /// control number. /// </summary> [JsonProperty(PropertyName = "rolloverInterchangeControlNumber")] public bool RolloverInterchangeControlNumber { get; set; } /// <summary> /// Gets or sets the value indicating whether to enable default group /// headers. /// </summary> [JsonProperty(PropertyName = "enableDefaultGroupHeaders")] public bool EnableDefaultGroupHeaders { get; set; } /// <summary> /// Gets or sets the functional group id. /// </summary> [JsonProperty(PropertyName = "functionalGroupId")] public string FunctionalGroupId { get; set; } /// <summary> /// Gets or sets the group control number lower bound. /// </summary> [JsonProperty(PropertyName = "groupControlNumberLowerBound")] public int GroupControlNumberLowerBound { get; set; } /// <summary> /// Gets or sets the group control number upper bound. /// </summary> [JsonProperty(PropertyName = "groupControlNumberUpperBound")] public int GroupControlNumberUpperBound { get; set; } /// <summary> /// Gets or sets the value indicating whether to rollover group control /// number. /// </summary> [JsonProperty(PropertyName = "rolloverGroupControlNumber")] public bool RolloverGroupControlNumber { get; set; } /// <summary> /// Gets or sets the group header agency code. /// </summary> [JsonProperty(PropertyName = "groupHeaderAgencyCode")] public string GroupHeaderAgencyCode { get; set; } /// <summary> /// Gets or sets the group header version. /// </summary> [JsonProperty(PropertyName = "groupHeaderVersion")] public string GroupHeaderVersion { get; set; } /// <summary> /// Gets or sets the transaction set control number lower bound. /// </summary> [JsonProperty(PropertyName = "transactionSetControlNumberLowerBound")] public int TransactionSetControlNumberLowerBound { get; set; } /// <summary> /// Gets or sets the transaction set control number upper bound. /// </summary> [JsonProperty(PropertyName = "transactionSetControlNumberUpperBound")] public int TransactionSetControlNumberUpperBound { get; set; } /// <summary> /// Gets or sets the value indicating whether to rollover transaction /// set control number. /// </summary> [JsonProperty(PropertyName = "rolloverTransactionSetControlNumber")] public bool RolloverTransactionSetControlNumber { get; set; } /// <summary> /// Gets or sets the transaction set control number prefix. /// </summary> [JsonProperty(PropertyName = "transactionSetControlNumberPrefix")] public string TransactionSetControlNumberPrefix { get; set; } /// <summary> /// Gets or sets the transaction set control number suffix. /// </summary> [JsonProperty(PropertyName = "transactionSetControlNumberSuffix")] public string TransactionSetControlNumberSuffix { get; set; } /// <summary> /// Gets or sets the value indicating whether to overwrite existing /// transaction set control number. /// </summary> [JsonProperty(PropertyName = "overwriteExistingTransactionSetControlNumber")] public bool OverwriteExistingTransactionSetControlNumber { get; set; } /// <summary> /// Gets or sets the group header date format. Possible values include: /// 'NotSpecified', 'CCYYMMDD', 'YYMMDD' /// </summary> [JsonProperty(PropertyName = "groupHeaderDateFormat")] public X12DateFormat GroupHeaderDateFormat { get; set; } /// <summary> /// Gets or sets the group header time format. Possible values include: /// 'NotSpecified', 'HHMM', 'HHMMSS', 'HHMMSSdd', 'HHMMSSd' /// </summary> [JsonProperty(PropertyName = "groupHeaderTimeFormat")] public X12TimeFormat GroupHeaderTimeFormat { get; set; } /// <summary> /// Gets or sets the usage indicator. Possible values include: /// 'NotSpecified', 'Test', 'Information', 'Production' /// </summary> [JsonProperty(PropertyName = "usageIndicator")] public UsageIndicator UsageIndicator { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (SenderApplicationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "SenderApplicationId"); } if (ReceiverApplicationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ReceiverApplicationId"); } if (ControlVersionNumber == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ControlVersionNumber"); } if (GroupHeaderAgencyCode == null) { throw new ValidationException(ValidationRules.CannotBeNull, "GroupHeaderAgencyCode"); } if (GroupHeaderVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "GroupHeaderVersion"); } } } }
/**************************************************************************** Tilde Copyright (c) 2008 Tantalus Media Pty 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.Text; using System.IO; using Tilde.Framework.Model; using System.Threading; using Timer = System.Threading.Timer; namespace Tilde.Framework.Controller { /// <summary> /// Provides a service where nominated files are regularly polled to check if they have been /// externally modified. /// </summary> /// <remarks> /// Events are fired when a file's modified time or attributes have changed; however note that /// these will be running in a worker thread, not the main thread! The user can flag files to be /// temporarily ignored, such as when the main application is making changes. The service as a /// whole can also be paused and resumed, such as when the application loses focus. /// </remarks> public class FileWatcher { [Flags] public enum NotificationEvents { Modified = 1, Created = 2, Deleted = 4, Renamed = 8, AttributesChanged = 16 } class WatchedFile { public string FileName; public DateTime LastWriteTime; public FileAttributes Attributes; } private object mLock; private List<WatchedFile> mWatchedFiles; private List<WatchedFile> mIgnoredFiles; private Timer mUpdateTimer; private bool mPaused; private DateTime mPauseTime; private static int mUpdatePeriod = 2000; public FileWatcher() { mLock = new object(); mWatchedFiles = new List<WatchedFile>(); mIgnoredFiles = new List<WatchedFile>(); mUpdateTimer = new Timer(new TimerCallback(this.UpdateTimer_Callback)); mPaused = false; } public event FileModifiedEventHandler FileModified; public event FileDeletedEventHandler FileDeleted; public event FileAttributesChangedEventHandler FileAttributesChanged; public void AddFile(string fileName) { if (!File.Exists(fileName)) return; WatchedFile fileInfo = new WatchedFile(); try { fileInfo.FileName = fileName; fileInfo.LastWriteTime = File.GetLastWriteTime(fileName); fileInfo.Attributes = File.GetAttributes(fileName); } catch(Exception) { return; } lock (mLock) { mWatchedFiles.Add(fileInfo); UpdateTimer(); } } public void RemoveFile(string fileName) { lock (mLock) { mWatchedFiles.RemoveAll(delegate(WatchedFile file) { return PathUtils.Compare(file.FileName, fileName) == 0; }); mIgnoredFiles.RemoveAll(delegate(WatchedFile file) { return PathUtils.Compare(file.FileName, fileName) == 0; }); UpdateTimer(); } } /// <summary> /// Enables or disables a file from being watched (such as when the client code is about to save it). /// </summary> /// <param name="fileName">Files' absolute path name.</param> /// <param name="enabled">Whether to enable or disable watching.</param> /// <remarks>Enabling a file that is not monitored causes it to be added to the watch list.</remarks> public void EnableFile(string fileName, bool enabled) { lock (mLock) { if (!enabled) { WatchedFile fileInfo = mWatchedFiles.Find(delegate(WatchedFile file) { return PathUtils.Compare(file.FileName, fileName) == 0; }); if (fileInfo != null) { mWatchedFiles.Remove(fileInfo); mIgnoredFiles.Add(fileInfo); UpdateTimer(); } } else { WatchedFile fileInfo = mIgnoredFiles.Find(delegate(WatchedFile file) { return PathUtils.Compare(file.FileName, fileName) == 0; }); if (fileInfo == null) AddFile(fileName); else { mIgnoredFiles.Remove(fileInfo); mWatchedFiles.Add(fileInfo); fileInfo.Attributes = File.GetAttributes(fileInfo.FileName); fileInfo.LastWriteTime = File.GetLastWriteTime(fileInfo.FileName); UpdateTimer(); } } } } public bool Paused { get { lock(mLock) { return mPaused; } } } public void Pause() { lock (mLock) { if (!mPaused) { mPaused = true; mPauseTime = DateTime.Now; UpdateTimer(); } } } /// <summary> /// Resumes the polling of watched files. /// </summary> /// <remarks> /// If it has been longer than the polling interval since the FileWatcher was paused, /// all watched files are immediately polled for changes and the results dispatched immediately /// in the callers' thread (before the function returns). /// </remarks> public void Resume() { lock (mLock) { if (mPaused) { if (DateTime.Now.Subtract(mPauseTime).TotalMilliseconds > mUpdatePeriod) { // Go through all the watched files and check them for (int index = 0; index < mWatchedFiles.Count; ) { WatchedFile file = mWatchedFiles[index]; if (!CheckFile(file)) { // Remove from queue mWatchedFiles.RemoveAt(index); } else { // Leave on queue ++index; } } } mPaused = false; UpdateTimer(); } } } private void UpdateTimer() { lock (mLock) { if (mWatchedFiles.Count == 0 || mPaused) mUpdateTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); else mUpdateTimer.Change(0, mUpdatePeriod / mWatchedFiles.Count); } } void UpdateTimer_Callback(object state) { lock (mLock) { if (!mPaused && mWatchedFiles.Count > 0) { WatchedFile file = mWatchedFiles[0]; if (!CheckFile(file)) { // Remove from queue mWatchedFiles.RemoveAt(0); } else { // Put on back of queue mWatchedFiles.RemoveAt(0); mWatchedFiles.Add(file); } } } } bool CheckFile(WatchedFile file) { if (!File.Exists(file.FileName)) { OnFileDeleted(file.FileName); return false; } else { DateTime fileWriteTime = File.GetLastWriteTime(file.FileName); FileAttributes fileAttributes = File.GetAttributes(file.FileName); if (fileWriteTime.CompareTo(file.LastWriteTime) > 0) { OnFileModified(file.FileName); } if (fileAttributes != file.Attributes) { OnFileAttributesChanged(file.FileName, file.Attributes, fileAttributes); } file.Attributes = fileAttributes; file.LastWriteTime = fileWriteTime; return true; } } void OnFileModified(string filename) { if (FileModified != null) FileModified(this, filename); } void OnFileDeleted(string filename) { if (FileDeleted != null) FileDeleted(this, filename); } void OnFileAttributesChanged(string filename, FileAttributes oldAttr, FileAttributes newAttr) { if (FileAttributesChanged != null) FileAttributesChanged(this, filename, oldAttr, newAttr); } } }
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace ActiveWare.CSS { /// <summary></summary> public class Directive : IDeclarationContainer, IRuleSetContainer { private DirectiveType type; private string name; private Expression expression; private List<Medium> mediums = new List<Medium>(); private List<Directive> directives = new List<Directive>(); private List<RuleSet> rulesets = new List<RuleSet>(); private List<Declaration> declarations = new List<Declaration>(); /// <summary></summary> [XmlAttribute("type")] public DirectiveType Type { get { return this.type; } set { this.type = value; } } /// <summary></summary> [XmlAttribute("name")] public string Name { get { return this.name; } set { this.name = value; } } /// <summary></summary> [XmlElement("Expression")] public Expression Expression { get { return this.expression; } set { this.expression = value; } } /// <summary></summary> [XmlArrayItem("Medium", typeof(Medium))] [XmlArray("Mediums")] public List<Medium> Mediums { get { return this.mediums; } set { this.mediums = value; } } /// <summary></summary> [XmlArrayItem("Directive", typeof(Directive))] [XmlArray("Directives")] public List<Directive> Directives { get { return this.directives; } set { this.directives = value; } } /// <summary></summary> [XmlArrayItem("RuleSet", typeof(RuleSet))] [XmlArray("RuleSets")] public List<RuleSet> RuleSets { get { return this.rulesets; } set { this.rulesets = value; } } /// <summary></summary> [XmlArrayItem("Declaration", typeof(Declaration))] [XmlArray("Declarations")] public List<Declaration> Declarations { get { return this.declarations; } set { this.declarations = value; } } /// <summary></summary> /// <returns></returns> public override string ToString() { return ToString(0); } /// <summary></summary> /// <param name="nesting"></param> /// <returns></returns> public string ToString(int nesting) { string start = ""; for (int i = 0; i < nesting; i++) { start += "\t"; } switch (type) { case DirectiveType.Charset: return ToCharSetString(start); case DirectiveType.Page: return ToPageString(start); case DirectiveType.Media: return ToMediaString(nesting); case DirectiveType.Import: return ToImportString(); case DirectiveType.FontFace: return ToFontFaceString(start); } System.Text.StringBuilder txt = new System.Text.StringBuilder(); txt.AppendFormat("{0} ", name); if (expression != null) { txt.AppendFormat("{0} ", expression); } bool first = true; foreach (Medium m in mediums) { if (first) { first = false; txt.Append(" "); } else { txt.Append(", "); } txt.Append(m.ToString()); } bool HasBlock = (this.declarations.Count > 0 || this.directives.Count > 0 || this.rulesets.Count > 0); if (!HasBlock) { txt.Append(";"); return txt.ToString(); } txt.Append(" {\r\n" + start); foreach (Directive dir in directives) { txt.AppendFormat("{0}\r\n", dir.ToCharSetString(start + "\t")); } foreach (RuleSet rules in rulesets) { txt.AppendFormat("{0}\r\n", rules.ToString(nesting + 1)); } first = true; foreach (Declaration dec in declarations) { if (first) { first = false; } else { txt.Append(";"); } txt.Append("\r\n\t" + start); txt.Append(dec.ToString()); } txt.Append("\r\n}"); return txt.ToString(); } private string ToFontFaceString(string start) { System.Text.StringBuilder txt = new System.Text.StringBuilder(); txt.Append("@font-face {"); bool first = true; foreach (Declaration dec in declarations) { if (first) { first = false; } else { txt.Append(";"); } txt.Append("\r\n\t" + start); txt.Append(dec.ToString()); } txt.Append("\r\n}"); return txt.ToString(); } private string ToImportString() { System.Text.StringBuilder txt = new System.Text.StringBuilder(); txt.Append("@import "); if (expression != null) { txt.AppendFormat("{0} ", expression); } bool first = true; foreach (Medium m in mediums) { if (first) { first = false; txt.Append(" "); } else { txt.Append(", "); } txt.Append(m.ToString()); } txt.Append(";"); return txt.ToString(); } private string ToMediaString(int nesting) { System.Text.StringBuilder txt = new System.Text.StringBuilder(); txt.Append("@media"); bool first = true; foreach (Medium m in mediums) { if (first) { first = false; txt.Append(" "); } else { txt.Append(", "); } txt.Append(m.ToString()); } txt.Append(" {\r\n"); foreach (RuleSet rules in rulesets) { txt.AppendFormat("{0}\r\n", rules.ToString(nesting + 1)); } txt.Append("}"); return txt.ToString(); } private string ToPageString(string start) { System.Text.StringBuilder txt = new System.Text.StringBuilder(); txt.Append("@page "); if (expression != null) { txt.AppendFormat("{0} ", expression); } txt.Append("{\r\n"); bool first = true; foreach (Declaration dec in declarations) { //if (first) { first = false; } else { txt.Append("; "); } //txt.Append(dec.ToString()); if (first) { first = false; } else { txt.Append(";"); } txt.Append("\r\n\t" + start); txt.Append(dec.ToString()); } txt.Append("}"); return txt.ToString(); } private string ToCharSetString(string start) { return string.Format("{2}{0} {1}", name, expression.ToString(), start); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class GeneratedRegionNetworkEndpointGroupsClientSnippets { /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteRegionNetworkEndpointGroupRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) DeleteRegionNetworkEndpointGroupRequest request = new DeleteRegionNetworkEndpointGroupRequest { RequestId = "", Region = "", Project = "", NetworkEndpointGroup = "", }; // Make the request lro::Operation<Operation, Operation> response = regionNetworkEndpointGroupsClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNetworkEndpointGroupsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteRegionNetworkEndpointGroupRequest, CallSettings) // Additional: DeleteAsync(DeleteRegionNetworkEndpointGroupRequest, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) DeleteRegionNetworkEndpointGroupRequest request = new DeleteRegionNetworkEndpointGroupRequest { RequestId = "", Region = "", Project = "", NetworkEndpointGroup = "", }; // Make the request lro::Operation<Operation, Operation> response = await regionNetworkEndpointGroupsClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNetworkEndpointGroupsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, string, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string networkEndpointGroup = ""; // Make the request lro::Operation<Operation, Operation> response = regionNetworkEndpointGroupsClient.Delete(project, region, networkEndpointGroup); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNetworkEndpointGroupsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, string, CallSettings) // Additional: DeleteAsync(string, string, string, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string networkEndpointGroup = ""; // Make the request lro::Operation<Operation, Operation> response = await regionNetworkEndpointGroupsClient.DeleteAsync(project, region, networkEndpointGroup); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNetworkEndpointGroupsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetRegionNetworkEndpointGroupRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) GetRegionNetworkEndpointGroupRequest request = new GetRegionNetworkEndpointGroupRequest { Region = "", Project = "", NetworkEndpointGroup = "", }; // Make the request NetworkEndpointGroup response = regionNetworkEndpointGroupsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetRegionNetworkEndpointGroupRequest, CallSettings) // Additional: GetAsync(GetRegionNetworkEndpointGroupRequest, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) GetRegionNetworkEndpointGroupRequest request = new GetRegionNetworkEndpointGroupRequest { Region = "", Project = "", NetworkEndpointGroup = "", }; // Make the request NetworkEndpointGroup response = await regionNetworkEndpointGroupsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, string, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string networkEndpointGroup = ""; // Make the request NetworkEndpointGroup response = regionNetworkEndpointGroupsClient.Get(project, region, networkEndpointGroup); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, string, CallSettings) // Additional: GetAsync(string, string, string, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string networkEndpointGroup = ""; // Make the request NetworkEndpointGroup response = await regionNetworkEndpointGroupsClient.GetAsync(project, region, networkEndpointGroup); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertRegionNetworkEndpointGroupRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) InsertRegionNetworkEndpointGroupRequest request = new InsertRegionNetworkEndpointGroupRequest { RequestId = "", Region = "", Project = "", NetworkEndpointGroupResource = new NetworkEndpointGroup(), }; // Make the request lro::Operation<Operation, Operation> response = regionNetworkEndpointGroupsClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNetworkEndpointGroupsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertRegionNetworkEndpointGroupRequest, CallSettings) // Additional: InsertAsync(InsertRegionNetworkEndpointGroupRequest, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) InsertRegionNetworkEndpointGroupRequest request = new InsertRegionNetworkEndpointGroupRequest { RequestId = "", Region = "", Project = "", NetworkEndpointGroupResource = new NetworkEndpointGroup(), }; // Make the request lro::Operation<Operation, Operation> response = await regionNetworkEndpointGroupsClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNetworkEndpointGroupsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, string, NetworkEndpointGroup, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; NetworkEndpointGroup networkEndpointGroupResource = new NetworkEndpointGroup(); // Make the request lro::Operation<Operation, Operation> response = regionNetworkEndpointGroupsClient.Insert(project, region, networkEndpointGroupResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNetworkEndpointGroupsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, string, NetworkEndpointGroup, CallSettings) // Additional: InsertAsync(string, string, NetworkEndpointGroup, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; NetworkEndpointGroup networkEndpointGroupResource = new NetworkEndpointGroup(); // Make the request lro::Operation<Operation, Operation> response = await regionNetworkEndpointGroupsClient.InsertAsync(project, region, networkEndpointGroupResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNetworkEndpointGroupsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListRegionNetworkEndpointGroupsRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) ListRegionNetworkEndpointGroupsRequest request = new ListRegionNetworkEndpointGroupsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = regionNetworkEndpointGroupsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (NetworkEndpointGroup item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (NetworkEndpointGroupList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NetworkEndpointGroup item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NetworkEndpointGroup> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NetworkEndpointGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListRegionNetworkEndpointGroupsRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) ListRegionNetworkEndpointGroupsRequest request = new ListRegionNetworkEndpointGroupsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = regionNetworkEndpointGroupsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((NetworkEndpointGroup item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((NetworkEndpointGroupList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NetworkEndpointGroup item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NetworkEndpointGroup> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NetworkEndpointGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, string, int?, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = regionNetworkEndpointGroupsClient.List(project, region); // Iterate over all response items, lazily performing RPCs as required foreach (NetworkEndpointGroup item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (NetworkEndpointGroupList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NetworkEndpointGroup item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NetworkEndpointGroup> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NetworkEndpointGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, string, int?, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedAsyncEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = regionNetworkEndpointGroupsClient.ListAsync(project, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((NetworkEndpointGroup item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((NetworkEndpointGroupList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NetworkEndpointGroup item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NetworkEndpointGroup> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NetworkEndpointGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation.Language; using log4net; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Tagging; using Tasks = System.Threading.Tasks; namespace PowerShellTools.Classification { internal class PowerShellTokenizationService : IPowerShellTokenizationService { private static readonly ILog Log = LogManager.GetLogger(typeof(PowerShellTokenizationService)); private readonly object _tokenizationLock = new object(); public event EventHandler<Ast> TokenizationComplete; private readonly ClassifierService _classifierService; private readonly ErrorTagSpanService _errorTagService; private readonly RegionAndBraceMatchingService _regionAndBraceMatchingService; private ITextBuffer _textBuffer; private ITextSnapshot _lastSnapshot; private bool _isBufferTokenizing; public PowerShellTokenizationService(ITextBuffer textBuffer) { _textBuffer = textBuffer; _classifierService = new ClassifierService(); _errorTagService = new ErrorTagSpanService(); _regionAndBraceMatchingService = new RegionAndBraceMatchingService(); _isBufferTokenizing = true; _lastSnapshot = _textBuffer.CurrentSnapshot; UpdateTokenization(); } public void StartTokenization() { lock (_tokenizationLock) { if (_lastSnapshot == null || (_lastSnapshot.Version.VersionNumber != _textBuffer.CurrentSnapshot.Version.VersionNumber && _textBuffer.CurrentSnapshot.Length > 0)) { if (!_isBufferTokenizing) { _isBufferTokenizing = true; Tasks.Task.Factory.StartNew(() => { UpdateTokenization(); }); } } } } private void UpdateTokenization() { while (true) { var currentSnapshot = _textBuffer.CurrentSnapshot; try { string scriptToTokenize = currentSnapshot.GetText(); Ast genereatedAst; Token[] generatedTokens; List<ClassificationInfo> tokenSpans; List<TagInformation<ErrorTag>> errorTags; Dictionary<int, int> startBraces; Dictionary<int, int> endBraces; List<TagInformation<IOutliningRegionTag>> regions; Tokenize(currentSnapshot, scriptToTokenize, 0, out genereatedAst, out generatedTokens, out tokenSpans, out errorTags, out startBraces, out endBraces, out regions); lock (_tokenizationLock) { if (_textBuffer.CurrentSnapshot.Version.VersionNumber == currentSnapshot.Version.VersionNumber) { SetTokenizationProperties(genereatedAst, generatedTokens, tokenSpans, errorTags, startBraces, endBraces, regions); RemoveCachedTokenizationProperties(); _isBufferTokenizing = false; _lastSnapshot = currentSnapshot; OnTokenizationComplete(genereatedAst); NotifyOnTagsChanged(BufferProperties.Classifier, currentSnapshot); NotifyOnTagsChanged(BufferProperties.ErrorTagger, currentSnapshot); NotifyOnTagsChanged(typeof(PowerShellOutliningTagger).Name, currentSnapshot); NotifyBufferUpdated(); break; } } } catch (Exception ex) { Log.Debug("Failed to tokenize the new snapshot.", ex); } } } private void NotifyOnTagsChanged(string name, ITextSnapshot currentSnapshot) { INotifyTagsChanged classifier; if (_textBuffer.Properties.TryGetProperty<INotifyTagsChanged>(name, out classifier)) { classifier.OnTagsChanged(new SnapshotSpan(currentSnapshot, new Span(0, currentSnapshot.Length))); } } private void NotifyBufferUpdated() { INotifyBufferUpdated tagger; if (_textBuffer.Properties.TryGetProperty<INotifyBufferUpdated>(typeof(PowerShellBraceMatchingTagger).Name, out tagger) && tagger != null) { tagger.OnBufferUpdated(_textBuffer); } } private void SetBufferProperty(object key, object propertyValue) { if (_textBuffer.Properties.ContainsProperty(key)) { _textBuffer.Properties.RemoveProperty(key); } _textBuffer.Properties.AddProperty(key, propertyValue); } private void OnTokenizationComplete(Ast generatedAst) { if (TokenizationComplete != null) { TokenizationComplete(this, generatedAst); } } private void Tokenize(ITextSnapshot currentSnapshot, string spanText, int startPosition, out Ast generatedAst, out Token[] generatedTokens, out List<ClassificationInfo> tokenSpans, out List<TagInformation<ErrorTag>> errorTags, out Dictionary<int, int> startBraces, out Dictionary<int, int> endBraces, out List<TagInformation<IOutliningRegionTag>> regions) { Log.Debug("Parsing input."); ParseError[] errors; generatedAst = Parser.ParseInput(spanText, out generatedTokens, out errors); Log.Debug("Classifying tokens."); tokenSpans = _classifierService.ClassifyTokens(generatedTokens, startPosition).ToList(); Log.Debug("Tagging error spans."); // Trigger the out-proc error parsing only when there are errors from the in-proc parser if (errors.Length != 0) { var errorsParsedFromOutProc = PowerShellToolsPackage.IntelliSenseService.GetParseErrors(spanText); errorTags = _errorTagService.TagErrorSpans(currentSnapshot, startPosition, errorsParsedFromOutProc).ToList(); } else { errorTags = _errorTagService.TagErrorSpans(currentSnapshot, startPosition, errors).ToList(); } Log.Debug("Matching braces and regions."); _regionAndBraceMatchingService.GetRegionsAndBraceMatchingInformation(spanText, startPosition, generatedTokens, out startBraces, out endBraces, out regions); } private void SetTokenizationProperties(Ast generatedAst, Token[] generatedTokens, List<ClassificationInfo> tokenSpans, List<TagInformation<ErrorTag>> errorTags, Dictionary<int, int> startBraces, Dictionary<int, int> endBraces, List<TagInformation<IOutliningRegionTag>> regions) { SetBufferProperty(BufferProperties.Ast, generatedAst); SetBufferProperty(BufferProperties.Tokens, generatedTokens); SetBufferProperty(BufferProperties.TokenSpans, tokenSpans); SetBufferProperty(BufferProperties.TokenErrorTags, errorTags); SetBufferProperty(BufferProperties.StartBraces, startBraces); SetBufferProperty(BufferProperties.EndBraces, endBraces); SetBufferProperty(BufferProperties.Regions, regions); } private void RemoveCachedTokenizationProperties() { if (_textBuffer.Properties.ContainsProperty(BufferProperties.RegionTags)) { _textBuffer.Properties.RemoveProperty(BufferProperties.RegionTags); } } } internal struct BraceInformation { internal char Character; internal int Position; internal BraceInformation(char character, int position) { Character = character; Position = position; } } internal struct ClassificationInfo { private readonly IClassificationType _classificationType; private readonly int _length; private readonly int _start; internal ClassificationInfo(int start, int length, IClassificationType classificationType) { _classificationType = classificationType; _start = start; _length = length; } internal int Length { get { return _length; } } internal int Start { get { return _start; } } internal IClassificationType ClassificationType { get { return _classificationType; } } } internal struct TagInformation<T> where T : ITag { internal readonly int Length; internal readonly int Start; internal readonly T Tag; internal TagInformation(int start, int length, T tag) { Tag = tag; Start = start; Length = length; } internal TagSpan<T> GetTagSpan(ITextSnapshot snapshot) { return snapshot.Length >= Start + Length ? new TagSpan<T>(new SnapshotSpan(snapshot, Start, Length), Tag) : null; } } public static class BufferProperties { public const string Ast = "PSAst"; public const string Tokens = "PSTokens"; public const string TokenErrorTags = "PSTokenErrorTags"; public const string EndBraces = "PSEndBrace"; public const string StartBraces = "PSStartBrace"; public const string TokenSpans = "PSTokenSpans"; public const string Regions = "PSRegions"; public const string RegionTags = "PSRegionTags"; public const string Classifier = "Classifier"; public const string ErrorTagger = "PowerShellErrorTagger"; public const string FromRepl = "PowerShellREPL"; public const string LastWordReplacementSpan = "LastWordReplacementSpan"; public const string LineUpToReplacementSpan = "LineUpToReplacementSpan"; public const string SessionOriginIntellisense = "SessionOrigin_Intellisense"; public const string SessionCompletionFullyMatchedStatus = "SessionCompletionFullyMatchedStatus"; public const string PowerShellTokenizer = "PowerShellTokenizer"; } public interface INotifyTagsChanged { void OnTagsChanged(SnapshotSpan span); } public interface INotifyBufferUpdated { void OnBufferUpdated(ITextBuffer textBuffer); } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.Targets; /// <summary> /// Reflection helpers for accessing properties. /// </summary> internal static class PropertyHelper { private static Dictionary<Type, Dictionary<string, PropertyInfo>> parameterInfoCache = new Dictionary<Type, Dictionary<string, PropertyInfo>>(); /// <summary> /// Set value parsed from string. /// </summary> /// <param name="obj">object instance to set with property <paramref name="propertyName"/></param> /// <param name="propertyName">name of the property on <paramref name="obj"/></param> /// <param name="value">The value to be parsed.</param> /// <param name="configurationItemFactory"></param> internal static void SetPropertyFromString(object obj, string propertyName, string value, ConfigurationItemFactory configurationItemFactory) { InternalLogger.Debug("Setting '{0}.{1}' to '{2}'", obj.GetType().Name, propertyName, value); PropertyInfo propInfo; if (!TryGetPropertyInfo(obj, propertyName, out propInfo)) { throw new NotSupportedException($"Parameter {propertyName} not supported on {obj.GetType().Name}"); } try { if (propInfo.IsDefined(typeof(ArrayParameterAttribute), false)) { throw new NotSupportedException($"Parameter {propertyName} of {obj.GetType().Name} is an array and cannot be assigned a scalar value."); } object newValue; Type propertyType = propInfo.PropertyType; propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType; if (!(TryNLogSpecificConversion(propertyType, value, out newValue, configurationItemFactory) || TryGetEnumValue(propertyType, value, out newValue, true) || TryImplicitConversion(propertyType, value, out newValue) || TrySpecialConversion(propertyType, value, out newValue) || TryFlatListConversion(propertyType, value, out newValue) || TryTypeConverterConversion(propertyType, value, out newValue))) newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture); propInfo.SetValue(obj, newValue, null); } catch (TargetInvocationException ex) { throw new NLogConfigurationException($"Error when setting property '{propInfo.Name}' on {obj}", ex.InnerException); } catch (Exception exception) { InternalLogger.Warn(exception, "Error when setting property '{0}' on '{1}'", propInfo.Name, obj); if (exception.MustBeRethrownImmediately()) { throw; } throw new NLogConfigurationException($"Error when setting property '{propInfo.Name}' on {obj}", exception); } } /// <summary> /// Is the property of array-type? /// </summary> /// <param name="t">Type which has the property <paramref name="propertyName"/></param> /// <param name="propertyName">name of the property.</param> /// <returns></returns> internal static bool IsArrayProperty(Type t, string propertyName) { PropertyInfo propInfo; if (!TryGetPropertyInfo(t, propertyName, out propInfo)) { throw new NotSupportedException($"Parameter {propertyName} not supported on {t.Name}"); } return propInfo.IsDefined(typeof(ArrayParameterAttribute), false); } /// <summary> /// Get propertyinfo /// </summary> /// <param name="obj">object which could have property <paramref name="propertyName"/></param> /// <param name="propertyName">propertyname on <paramref name="obj"/></param> /// <param name="result">result when success.</param> /// <returns>success.</returns> internal static bool TryGetPropertyInfo(object obj, string propertyName, out PropertyInfo result) { PropertyInfo propInfo = obj.GetType().GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propInfo != null) { result = propInfo; return true; } lock (parameterInfoCache) { Type targetType = obj.GetType(); Dictionary<string, PropertyInfo> cache; if (!parameterInfoCache.TryGetValue(targetType, out cache)) { cache = BuildPropertyInfoDictionary(targetType); parameterInfoCache[targetType] = cache; } return cache.TryGetValue(propertyName, out result); } } internal static Type GetArrayItemType(PropertyInfo propInfo) { var arrayParameterAttribute = propInfo.GetCustomAttribute<ArrayParameterAttribute>(); return arrayParameterAttribute?.ItemType; } internal static IEnumerable<PropertyInfo> GetAllReadableProperties(Type type) { return type.GetProperties(BindingFlags.Public | BindingFlags.Instance); } internal static void CheckRequiredParameters(object o) { foreach (PropertyInfo propInfo in GetAllReadableProperties(o.GetType())) { if (propInfo.IsDefined(typeof(RequiredParameterAttribute), false)) { object value = propInfo.GetValue(o, null); if (value == null) { throw new NLogConfigurationException( $"Required parameter '{propInfo.Name}' on '{o}' was not specified."); } } } } private static bool TryImplicitConversion(Type resultType, string value, out object result) { try { if (string.Equals(resultType.Namespace, "System", StringComparison.Ordinal)) { result = null; return false; } MethodInfo operatorImplicitMethod = resultType.GetMethod("op_Implicit", BindingFlags.Public | BindingFlags.Static, null, new Type[] { value.GetType() }, null); if (operatorImplicitMethod == null || !resultType.IsAssignableFrom(operatorImplicitMethod.ReturnType)) { result = null; return false; } result = operatorImplicitMethod.Invoke(null, new object[] { value }); return true; } catch (Exception ex) { InternalLogger.Warn(ex, "Implicit Conversion Failed of {0} to {1}", value, resultType); } result = null; return false; } private static bool TryNLogSpecificConversion(Type propertyType, string value, out object newValue, ConfigurationItemFactory configurationItemFactory) { if (propertyType == typeof(Layout) || propertyType == typeof(SimpleLayout)) { newValue = new SimpleLayout(value, configurationItemFactory); return true; } if (propertyType == typeof(ConditionExpression)) { newValue = ConditionParser.ParseExpression(value, configurationItemFactory); return true; } newValue = null; return false; } private static bool TryGetEnumValue(Type resultType, string value, out object result, bool flagsEnumAllowed) { if (!resultType.IsEnum()) { result = null; return false; } if (flagsEnumAllowed && resultType.IsDefined(typeof(FlagsAttribute), false)) { ulong union = 0; foreach (string v in value.Split(',')) { FieldInfo enumField = resultType.GetField(v.Trim(), BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); if (enumField == null) { throw new NLogConfigurationException($"Invalid enumeration value '{value}'."); } union |= Convert.ToUInt64(enumField.GetValue(null), CultureInfo.InvariantCulture); } result = Convert.ChangeType(union, Enum.GetUnderlyingType(resultType), CultureInfo.InvariantCulture); result = Enum.ToObject(resultType, result); return true; } else { FieldInfo enumField = resultType.GetField(value, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); if (enumField == null) { throw new NLogConfigurationException($"Invalid enumeration value '{value}'."); } result = enumField.GetValue(null); return true; } } private static bool TrySpecialConversion(Type type, string value, out object newValue) { if (type == typeof(Encoding)) { value = value.Trim(); newValue = Encoding.GetEncoding(value); return true; } if (type == typeof(CultureInfo)) { value = value.Trim(); newValue = new CultureInfo(value); return true; } if (type == typeof(Type)) { value = value.Trim(); newValue = Type.GetType(value, true); return true; } newValue = null; return false; } /// <summary> /// Try parse of string to (Generic) list, comma separated. /// </summary> /// <remarks> /// If there is a comma in the value, then (single) quote the value. For single quotes, use the backslash as escape /// </remarks> /// <param name="type"></param> /// <param name="valueRaw"></param> /// <param name="newValue"></param> /// <returns></returns> private static bool TryFlatListConversion(Type type, string valueRaw, out object newValue) { if (type.IsGenericType()) { var typeDefinition = type.GetGenericTypeDefinition(); #if NET3_5 var isSet = typeDefinition == typeof(HashSet<>); #else var isSet = typeDefinition == typeof(ISet<>) || typeDefinition == typeof(HashSet<>); #endif //not checking "implements" interface as we are creating HashSet<T> or List<T> and also those checks are expensive if (isSet || typeDefinition == typeof(List<>) || typeDefinition == typeof(IList<>) || typeDefinition == typeof(IEnumerable<>)) //set or list/array etc { //note: type.GenericTypeArguments is .NET 4.5+ var propertyType = type.GetGenericArguments()[0]; var listType = isSet ? typeof(HashSet<>) : typeof(List<>); var genericArgs = propertyType; var concreteType = listType.MakeGenericType(genericArgs); var newList = Activator.CreateInstance(concreteType); //no support for array if (newList == null) { throw new NLogConfigurationException("Cannot create instance of {0} for value {1}", type.ToString(), valueRaw); } var values = valueRaw.SplitQuoted(',', '\'', '\\'); var collectionAddMethod = concreteType.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); if (collectionAddMethod == null) { throw new NLogConfigurationException("Add method on type {0} for value {1} not found", type.ToString(), valueRaw); } foreach (var value in values) { if (!(TryGetEnumValue(propertyType, value, out newValue, false) || TryImplicitConversion(propertyType, value, out newValue) || TrySpecialConversion(propertyType, value, out newValue) || TryTypeConverterConversion(propertyType, value, out newValue))) { newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture); } collectionAddMethod.Invoke(newList, new object[] { newValue }); } newValue = newList; return true; } } newValue = null; return false; } private static bool TryTypeConverterConversion(Type type, string value, out object newValue) { #if !SILVERLIGHT && !WINDOWS_UWP var converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(typeof(string))) { newValue = converter.ConvertFromInvariantString(value); return true; } #else if (type == typeof(LineEndingMode)) { newValue = LineEndingMode.FromString(value); return true; } else if (type == typeof(Uri)) { newValue = new Uri(value); return true; } #endif newValue = null; return false; } private static bool TryGetPropertyInfo(Type targetType, string propertyName, out PropertyInfo result) { if (!string.IsNullOrEmpty(propertyName)) { PropertyInfo propInfo = targetType.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propInfo != null) { result = propInfo; return true; } } lock (parameterInfoCache) { Dictionary<string, PropertyInfo> cache; if (!parameterInfoCache.TryGetValue(targetType, out cache)) { cache = BuildPropertyInfoDictionary(targetType); parameterInfoCache[targetType] = cache; } return cache.TryGetValue(propertyName, out result); } } private static Dictionary<string, PropertyInfo> BuildPropertyInfoDictionary(Type t) { var retVal = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase); foreach (PropertyInfo propInfo in GetAllReadableProperties(t)) { var arrayParameterAttribute = propInfo.GetCustomAttribute<ArrayParameterAttribute>(); if (arrayParameterAttribute != null) { retVal[arrayParameterAttribute.ElementName] = propInfo; } else { retVal[propInfo.Name] = propInfo; } if (propInfo.IsDefined(typeof(DefaultParameterAttribute), false)) { // define a property with empty name retVal[string.Empty] = propInfo; } } return retVal; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Configuration.Internal; using System.Threading; namespace System.Configuration { internal sealed class ClientConfigurationSystem : IInternalConfigSystem { private const string SystemDiagnosticsConfigKey = "system.diagnostics"; private const string SystemNetGroupKey = "system.net/"; private readonly IInternalConfigHost _configHost; private readonly IInternalConfigRoot _configRoot; private readonly bool _isAppConfigHttp; private IInternalConfigRecord _completeConfigRecord; private Exception _initError; private bool _isInitInProgress; private bool _isMachineConfigInited; private bool _isUserConfigInited; private IInternalConfigRecord _machineConfigRecord; internal ClientConfigurationSystem() { IConfigSystem configSystem = new ConfigSystem(); configSystem.Init(typeof(ClientConfigurationHost), null, null); _configHost = configSystem.Host; _configRoot = configSystem.Root; _configRoot.ConfigRemoved += OnConfigRemoved; _isAppConfigHttp = ((IInternalConfigHostPaths)_configHost).IsAppConfigHttp; } object IInternalConfigSystem.GetSection(string sectionName) { PrepareClientConfigSystem(sectionName); // Get the appropriate config record for the section. IInternalConfigRecord configRecord = null; if (DoesSectionOnlyUseMachineConfig(sectionName)) { if (_isMachineConfigInited) configRecord = _machineConfigRecord; } else { if (_isUserConfigInited) configRecord = _completeConfigRecord; } // Call GetSection(), or return null if no configuration is yet available. return configRecord?.GetSection(sectionName); } void IInternalConfigSystem.RefreshConfig(string sectionName) { PrepareClientConfigSystem(sectionName); if (_isMachineConfigInited) _machineConfigRecord.RefreshSection(sectionName); } // Supports user config bool IInternalConfigSystem.SupportsUserConfig => true; // Return true if the section might be used during initialization of the configuration system, // and thus lead to deadlock if appropriate measures are not taken. private bool IsSectionUsedInInit(string configKey) { return (configKey == SystemDiagnosticsConfigKey) || (_isAppConfigHttp && configKey.StartsWith(SystemNetGroupKey, StringComparison.Ordinal)); } // Return true if the section should only use the machine configuration and not use the // application configuration. This is only true for system.net sections when the configuration // file for the application is downloaded via http using System.Net.WebClient. private bool DoesSectionOnlyUseMachineConfig(string configKey) { return _isAppConfigHttp && configKey.StartsWith(SystemNetGroupKey, StringComparison.Ordinal); } // Ensure that initialization has completed, while handling re-entrancy issues // for certain sections that may be used during initialization itself. private void EnsureInit(string configKey) { bool doInit = false; lock (this) { // If the user config is not initialized, then we must either: // a. Perform the initialization ourselves if no other thread is doing it, or // b. Wait for the initialization to complete if we know the section is not used during initialization itself, or // c. Ignore initialization if the section can be used during initialization. Note that GetSection() // returns null is initialization has not completed. if (!_isUserConfigInited) { if (!_isInitInProgress) { _isInitInProgress = true; doInit = true; } else { if (!IsSectionUsedInInit(configKey)) { // Wait for initialization to complete. Monitor.Wait(this); } } } } if (!doInit) return; try { try { // Initialize machine configuration. _machineConfigRecord = _configRoot.GetConfigRecord( ClientConfigurationHost.MachineConfigPath); _machineConfigRecord.ThrowIfInitErrors(); // Make machine configuration available to system.net sections // when application configuration is downloaded via http. _isMachineConfigInited = true; // If we add System.Net.Configuration we'll need to kick the initialization here // to prevent deadlocks in the networking classes by loading networking config // before making any networking requests. // // Any requests for sections used in initialization during the call to // EnsureConfigLoaded() will be served by _machine.config or will return null. //if (_isAppConfigHttp) //{ //} // Now load the rest of configuration var configHostPaths = (IInternalConfigHostPaths)_configHost; configHostPaths.RefreshConfigPaths(); string configPath; if (configHostPaths.HasLocalConfig) { configPath = ClientConfigurationHost.LocalUserConfigPath; } else { configPath = configHostPaths.HasRoamingConfig ? ClientConfigurationHost.RoamingUserConfigPath : ClientConfigurationHost.ExeConfigPath; } _completeConfigRecord = _configRoot.GetConfigRecord(configPath); _completeConfigRecord.ThrowIfInitErrors(); _isUserConfigInited = true; } catch (Exception e) { _initError = new ConfigurationErrorsException(SR.Config_client_config_init_error, e); throw _initError; } } catch { ConfigurationManager.SetInitError(_initError); _isMachineConfigInited = true; _isUserConfigInited = true; throw; } finally { lock (this) { try { // Notify ConfigurationSettings that initialization has fully completed, // even if unsuccessful. ConfigurationManager.CompleteConfigInit(); _isInitInProgress = false; } finally { // Wake up all threads waiting for initialization to complete. Monitor.PulseAll(this); } } } } private void PrepareClientConfigSystem(string sectionName) { // Ensure the configuration system is inited for this section. if (!_isUserConfigInited) EnsureInit(sectionName); // If an error occurred during initialzation, throw it. if (_initError != null) throw _initError; } // If config has been removed because initialization was not complete, // fetch a new configuration record. The record will be created and // completely initialized as RequireCompleteInit() will have been called // on the ClientConfigurationHost before we receive this event. private void OnConfigRemoved(object sender, InternalConfigEventArgs e) { try { IInternalConfigRecord newConfigRecord = _configRoot.GetConfigRecord(_completeConfigRecord.ConfigPath); _completeConfigRecord = newConfigRecord; _completeConfigRecord.ThrowIfInitErrors(); } catch (Exception ex) { _initError = new ConfigurationErrorsException(SR.Config_client_config_init_error, ex); ConfigurationManager.SetInitError(_initError); throw _initError; } } } }
using System; using System.Buffers; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; using Orleans.Serialization.Buffers; using Orleans.Serialization.Codecs; using Orleans.Serialization.WireProtocol; namespace Orleans.Runtime { [RegisterSerializer] public sealed class IdSpanCodec : IFieldCodec<IdSpan> { private static readonly ConcurrentDictionary<int, IdSpan> _cache = new ConcurrentDictionary<int, IdSpan>(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteField<TBufferWriter>( ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, IdSpan value) where TBufferWriter : IBufferWriter<byte> { ReferenceCodec.MarkValueField(writer.Session); writer.WriteFieldHeaderExpected(fieldIdDelta, WireType.LengthPrefixed); var hashCode = value.GetHashCode(); var bytes = IdSpan.UnsafeGetArray(value); var bytesLength = value.IsDefault ? 0 : bytes.Length; writer.WriteVarUInt32((uint)(sizeof(int) + bytesLength)); writer.WriteInt32(hashCode); writer.Write(bytes); } public static void WriteRaw<TBufferWriter>( ref Writer<TBufferWriter> writer, IdSpan value) where TBufferWriter : IBufferWriter<byte> { var hashCode = value.GetHashCode(); var bytes = IdSpan.UnsafeGetArray(value); writer.WriteInt32(hashCode); var bytesLength = value.IsDefault ? 0 : bytes.Length; writer.WriteVarUInt32((uint)bytesLength); writer.Write(bytes); } public static unsafe IdSpan ReadRaw<TInput>(ref Reader<TInput> reader) { byte[] payloadArray = default; var hashCode = reader.ReadInt32(); var length = reader.ReadVarUInt32(); if (!reader.TryReadBytes((int)length, out var payloadSpan)) { payloadSpan = payloadArray = reader.ReadBytes(length); } // Search through var candidateHashCode = hashCode; while (_cache.TryGetValue(candidateHashCode, out var existing)) { if (existing.GetHashCode() != hashCode) { break; } var existingSpan = new ReadOnlySpan<byte>(IdSpan.UnsafeGetArray(existing)); if (existingSpan.SequenceEqual(payloadSpan)) { return existing; } // Try the next slot. ++candidateHashCode; } if (payloadArray is null) { payloadArray = new byte[length]; payloadSpan.CopyTo(payloadArray); } var value = IdSpan.UnsafeCreate(payloadArray, hashCode); while (!_cache.TryAdd(candidateHashCode++, value)) { // Insert the value at the first available position. } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe IdSpan ReadValue<TInput>(ref Reader<TInput> reader, Field field) { ReferenceCodec.MarkValueField(reader.Session); byte[] payloadArray = default; var length = reader.ReadVarUInt32() - sizeof(int); var hashCode = reader.ReadInt32(); if (!reader.TryReadBytes((int)length, out var payloadSpan)) { payloadSpan = payloadArray = reader.ReadBytes(length); } // Search through var candidateHashCode = hashCode; while (_cache.TryGetValue(candidateHashCode, out var existing)) { if (existing.GetHashCode() != hashCode) { break; } var existingSpan = new ReadOnlySpan<byte>(IdSpan.UnsafeGetArray(existing)); if (existingSpan.SequenceEqual(payloadSpan)) { return existing; } // Try the next slot. ++candidateHashCode; } if (payloadArray is null) { payloadArray = new byte[length]; payloadSpan.CopyTo(payloadArray); } var value = IdSpan.UnsafeCreate(payloadArray, hashCode); while (!_cache.TryAdd(candidateHashCode++, value)) { // Insert the value at the first available position. } return value; } } /// <summary> /// Primitive type for identities, representing a sequence of bytes. /// </summary> [Immutable] [Serializable] [StructLayout(LayoutKind.Auto)] [GenerateSerializer] public readonly struct IdSpan : IEquatable<IdSpan>, IComparable<IdSpan>, ISerializable { [Id(0)] private readonly int _hashCode; [Id(1)] private readonly byte[] _value; /// <summary> /// Creates a new <see cref="IdSpan"/> instance from the provided value. /// </summary> internal IdSpan(byte[] value) { _value = value; _hashCode = GetHashCode(value); } /// <summary> /// Creates a new <see cref="IdSpan"/> instance from the provided value. /// </summary> private IdSpan(byte[] value, int hashCode) { _value = value; _hashCode = hashCode; } /// <summary> /// Creates a new <see cref="IdSpan"/> instance from the provided value. /// </summary> private IdSpan(SerializationInfo info, StreamingContext context) { _value = (byte[])info.GetValue("v", typeof(byte[])); _hashCode = info.GetInt32("h"); } public ReadOnlyMemory<byte> Value => _value; /// <summary> /// <see langword="true"/> if this instance is the default value, <see langword="false"/> if it is not. /// </summary> public bool IsDefault => _value is null || _value.Length == 0; /// <summary> /// Creates a new <see cref="IdSpan"/> instance from the provided value. /// </summary> public static IdSpan Create(string id) => id is string idString ? new IdSpan(Encoding.UTF8.GetBytes(idString)) : default; /// <summary> /// Returns a span representation of this instance. /// </summary> public ReadOnlySpan<byte> AsSpan() => _value; /// <inheritdoc/> public override bool Equals(object obj) { return obj is IdSpan kind && this.Equals(kind); } /// <inheritdoc/> public bool Equals(IdSpan obj) { if (object.ReferenceEquals(_value, obj._value)) return true; if (_value is null || obj._value is null) return false; return _value.AsSpan().SequenceEqual(obj._value); } /// <inheritdoc/> public override int GetHashCode() => _hashCode; /// <summary> /// Return uniform, stable hash code for IdSpan /// </summary> public uint GetUniformHashCode() => unchecked((uint)_hashCode); /// <inheritdoc/> public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("v", _value); info.AddValue("h", _hashCode); } /// <summary> /// Creates an instance, specifying both the hash code and the value. /// </summary> /// <remarks> /// This method is intended for use by serializers and other low-level libraries. /// </remarks> public static IdSpan UnsafeCreate(byte[] value, int hashCode) => new IdSpan(value, hashCode); /// <inheritdoc/> public static byte[] UnsafeGetArray(IdSpan id) => id._value; /// <inheritdoc/> public int CompareTo(IdSpan other) => _value.AsSpan().SequenceCompareTo(other._value.AsSpan()); /// <inheritdoc/> public override string ToString() => this.ToStringUtf8(); /// <summary> /// Returns a string representation of this instance, decoding the value as UTF8. /// </summary> public string ToStringUtf8() { if (_value is object) return Encoding.UTF8.GetString(_value); return null; } /// <inheritdoc/> public static bool operator ==(IdSpan a, IdSpan b) => a.Equals(b); /// <inheritdoc/> public static bool operator !=(IdSpan a, IdSpan b) => !a.Equals(b); private static int GetHashCode(byte[] value) => (int)JenkinsHash.ComputeHash(value); /// <summary> /// An <see cref="IEqualityComparer{T}"/> and <see cref="IComparer{T}"/> implementation for <see cref="IdSpan"/>. /// </summary> public sealed class Comparer : IEqualityComparer<IdSpan>, IComparer<IdSpan> { /// <summary> /// A singleton <see cref="Comparer"/> instance. /// </summary> public static Comparer Instance { get; } = new Comparer(); /// <inheritdoc/> public int Compare(IdSpan x, IdSpan y) => x.CompareTo(y); /// <inheritdoc/> public bool Equals(IdSpan x, IdSpan y) => x.Equals(y); /// <inheritdoc/> public int GetHashCode(IdSpan obj) => obj.GetHashCode(); } } }
namespace Fixtures.SwaggerBatBodyComplex { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; internal partial class BasicOperations : IServiceOperations<AutoRestComplexTestService>, IBasicOperations { /// <summary> /// Initializes a new instance of the BasicOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal BasicOperations(AutoRestComplexTestService client) { this.Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex type {id: 2, name: 'abc', color: 'YELLOW'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetValid", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//complex/basic/valid"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Basic>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Basic>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </summary> /// <param name='complexBody'> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutValid", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//complex/basic/valid"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get a basic complex type that is invalid for the local strong type /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetInvalid", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//complex/basic/invalid"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Basic>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Basic>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get a basic complex type that is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetEmpty", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//complex/basic/empty"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Basic>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Basic>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get a basic complex type whose properties are null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetNull", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//complex/basic/null"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Basic>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Basic>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get a basic complex type while the server doesn't provide a response /// payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//complex/basic/notprovided"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Basic>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Basic>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/11/2009 1:08:21 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using DotSpatial.Data; using DotSpatial.NTSExtension; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// PointSymbolizer /// </summary> public class PointSymbolizer : FeatureSymbolizer, IPointSymbolizer { #region Private Variables private IList<ISymbol> _symbols; #endregion #region Constructors /// <summary> /// Creates a new instance of PointSymbolizer /// </summary> public PointSymbolizer() { Configure(); } /// <summary> /// Generates a new symbolizer with only one symbol. /// </summary> /// <param name="symbol">The symbol to use for creating this symbolizer</param> public PointSymbolizer(ISymbol symbol) { base.Smoothing = true; _symbols = new CopyList<ISymbol> { symbol }; } /// <summary> /// Builds the new list of symbols from the symbols in the preset list or array of symbols. /// </summary> /// <param name="presetSymbols"></param> public PointSymbolizer(IEnumerable<ISymbol> presetSymbols) { base.Smoothing = true; _symbols = new CopyList<ISymbol>(); foreach (ISymbol symbol in presetSymbols) { _symbols.Add(symbol); } } /// <summary> /// Creates a point symbolizer with one member, and that member is constructed /// based on the values specified. /// </summary> /// <param name="color"></param> /// <param name="shape"></param> /// <param name="size"></param> public PointSymbolizer(Color color, PointShape shape, double size) { base.Smoothing = true; _symbols = new CopyList<ISymbol>(); ISimpleSymbol ss = new SimpleSymbol(color, shape, size); _symbols.Add(ss); } /// <summary> /// Creates a point symbolizer with one memberw, and that member is constructed /// from the specified image. /// </summary> /// <param name="image">The image to use as a point symbol</param> /// <param name="size">The desired output size of the larger dimension of the image.</param> public PointSymbolizer(Image image, double size) { _symbols = new CopyList<ISymbol>(); IPictureSymbol ps = new PictureSymbol(image); ps.Size = new Size2D(size, size); _symbols.Add(ps); } /// <summary> /// Creates a new point symbolizer that has a character symbol based on the specified characteristics. /// </summary> /// <param name="character">The character to draw</param> /// <param name="fontFamily">The font family to use for rendering the font</param> /// <param name="color">The font color</param> /// <param name="size">The size of the symbol</param> public PointSymbolizer(char character, string fontFamily, Color color, double size) { _symbols = new CopyList<ISymbol>(); CharacterSymbol cs = new CharacterSymbol(character, fontFamily, color, size); _symbols.Add(cs); } /// <summary> /// Creates a new PointSymbolizer /// </summary> /// <param name="selected"></param> public PointSymbolizer(bool selected) { Configure(); if (!selected) return; ISimpleSymbol ss = _symbols[0] as ISimpleSymbol; if (ss != null) { ss.Color = Color.Cyan; } } /// <summary> /// Sets the symbol type to geographic and generates a size that is 1/100 the width of the specified extents. /// </summary> /// <param name="selected"></param> /// <param name="extents"></param> public PointSymbolizer(bool selected, IRectangle extents) { Configure(); base.ScaleMode = ScaleMode.Geographic; base.Smoothing = false; ISymbol s = _symbols[0]; if (s == null) return; s.Size.Width = extents.Width / 100; s.Size.Height = extents.Width / 100; ISimpleSymbol ss = _symbols[0] as ISimpleSymbol; if (ss != null && selected) ss.Color = Color.Cyan; } private void Configure() { _symbols = new CopyList<ISymbol>(); ISimpleSymbol ss = new SimpleSymbol(); ss.Color = SymbologyGlobal.RandomColor(); ss.Opacity = 1F; ss.PointShape = PointShape.Rectangle; Smoothing = true; ScaleMode = ScaleMode.Symbolic; _symbols.Add(ss); } #endregion #region Methods /// <summary> /// Sets the outline, assuming that the symbolizer either supports outlines, or /// else by using a second symbol layer. /// </summary> /// <param name="outlineColor">The color of the outline</param> /// <param name="width">The width of the outline in pixels</param> public override void SetOutline(Color outlineColor, double width) { if (_symbols == null) return; if (_symbols.Count == 0) return; foreach (ISymbol symbol in _symbols) { IOutlinedSymbol oSymbol = symbol as IOutlinedSymbol; if (oSymbol == null) continue; oSymbol.OutlineColor = outlineColor; oSymbol.OutlineWidth = width; oSymbol.UseOutline = true; } base.SetOutline(outlineColor, width); } /// <summary> /// Returns the encapsulating size when considering all of the symbol layers that make up this symbolizer. /// </summary> /// <returns>A Size2D</returns> public Size2D GetSize() { return _symbols.GetBoundingSize(); } /// <summary> /// This assumes that you wish to simply scale the various sizes. /// It will adjust all of the sizes so that the maximum size is /// the same as the specified size. /// </summary> /// <param name="value">The Size2D of the new maximum size</param> public void SetSize(Size2D value) { Size2D oldSize = _symbols.GetBoundingSize(); double dX = value.Width / oldSize.Width; double dY = value.Height / oldSize.Height; foreach (ISymbol symbol in _symbols) { Size2D os = symbol.Size; symbol.Size = new Size2D(os.Width * dX, os.Height * dY); } } /// <inheritdoc /> public override Size GetLegendSymbolSize() { Size2D sz = GetSize(); int w = (int)sz.Width; int h = (int)sz.Height; if (w < 1) w = 1; if (w > 128) w = 128; if (h < 1) h = 1; if (h > 128) h = 128; return new Size(w, h); } /// <summary> /// Returns the color of the top-most layer symbol /// </summary> /// <returns></returns> public Color GetFillColor() { if (_symbols == null) return Color.Empty; if (_symbols.Count == 0) return Color.Empty; IColorable c = _symbols[_symbols.Count - 1] as IColorable; return c == null ? Color.Empty : c.Color; } /// <summary> /// Sets the color of the top-most layer symbol /// </summary> /// <param name="color">The color to assign to the top-most layer.</param> public void SetFillColor(Color color) { if (_symbols == null) return; if (_symbols.Count == 0) return; _symbols[_symbols.Count - 1].SetColor(color); } /// <summary> /// Draws the specified value /// </summary> /// <param name="g">The Graphics object to draw to</param> /// <param name="target">The Rectangle defining the bounds to draw in</param> public override void Draw(Graphics g, Rectangle target) { Size2D size = GetSize(); double scaleH = target.Width / size.Width; double scaleV = target.Height / size.Height; double scale = Math.Min(scaleH, scaleV); Matrix old = g.Transform; Matrix shift = g.Transform; shift.Translate(target.X + target.Width / 2, target.Y + target.Height / 2); g.Transform = shift; Draw(g, scale); g.Transform = old; } /// <summary> /// Draws the point symbol to the specified graphics object by cycling through each of the layers and /// drawing the content. This assumes that the graphics object has been translated to the specified point. /// </summary> /// <param name="g">Graphics object that is used for drawing.</param> /// <param name="scaleSize">Scale size represents the constant to multiply to the geographic measures in order to turn them into pixel coordinates </param> public void Draw(Graphics g, double scaleSize) { GraphicsState s = g.Save(); if (Smoothing) { g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.AntiAlias; } else { g.SmoothingMode = SmoothingMode.None; g.TextRenderingHint = TextRenderingHint.SystemDefault; } foreach (ISymbol symbol in _symbols) { symbol.Draw(g, scaleSize); } g.Restore(s); //Changed by jany_ (2015-07-06) remove smoothing because we might not want to smooth whatever is drawn with g afterwards } /// <summary> /// Multiplies all the linear measurements, like width, height, and offset values by the specified value. /// </summary> /// <param name="value">The double precision value to multiply all of the values against.</param> public void Scale(double value) { foreach (ISymbol symbol in _symbols) { symbol.Scale(value); } } #endregion #region Properties /// <summary> /// Gets or sets the set of layered symbols. The symbol with the highest index is drawn on top. /// </summary> [Serialize("Symbols")] public IList<ISymbol> Symbols { get { return _symbols; } set { _symbols = value; } } #endregion #region Protected Methods /// <summary> /// This controls randomly creating a single random symbol from the symbol types, and randomizing it. /// </summary> /// <param name="generator"></param> protected override void OnRandomize(Random generator) { SymbolType type = generator.NextEnum<SymbolType>(); _symbols.Clear(); switch (type) { case SymbolType.Custom: _symbols.Add(new SimpleSymbol()); break; case SymbolType.Character: _symbols.Add(new CharacterSymbol()); break; case SymbolType.Picture: _symbols.Add(new CharacterSymbol()); break; case SymbolType.Simple: _symbols.Add(new SimpleSymbol()); break; } // This part will actually randomize the sub-member base.OnRandomize(generator); } #endregion } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes a VPN connection. /// </summary> public partial class VpnConnection { private string _customerGatewayConfiguration; private string _customerGatewayId; private VpnConnectionOptions _options; private List<VpnStaticRoute> _routes = new List<VpnStaticRoute>(); private VpnState _state; private List<Tag> _tags = new List<Tag>(); private GatewayType _type; private List<VgwTelemetry> _vgwTelemetry = new List<VgwTelemetry>(); private string _vpnConnectionId; private string _vpnGatewayId; /// <summary> /// Gets and sets the property CustomerGatewayConfiguration. /// <para> /// The configuration information for the VPN connection's customer gateway (in the native /// XML format). This element is always present in the <a>CreateVpnConnection</a> response; /// however, it's present in the <a>DescribeVpnConnections</a> response only if the VPN /// connection is in the <code>pending</code> or <code>available</code> state. /// </para> /// </summary> public string CustomerGatewayConfiguration { get { return this._customerGatewayConfiguration; } set { this._customerGatewayConfiguration = value; } } // Check to see if CustomerGatewayConfiguration property is set internal bool IsSetCustomerGatewayConfiguration() { return this._customerGatewayConfiguration != null; } /// <summary> /// Gets and sets the property CustomerGatewayId. /// <para> /// The ID of the customer gateway at your end of the VPN connection. /// </para> /// </summary> public string CustomerGatewayId { get { return this._customerGatewayId; } set { this._customerGatewayId = value; } } // Check to see if CustomerGatewayId property is set internal bool IsSetCustomerGatewayId() { return this._customerGatewayId != null; } /// <summary> /// Gets and sets the property Options. /// <para> /// The VPN connection options. /// </para> /// </summary> public VpnConnectionOptions Options { get { return this._options; } set { this._options = value; } } // Check to see if Options property is set internal bool IsSetOptions() { return this._options != null; } /// <summary> /// Gets and sets the property Routes. /// <para> /// The static routes associated with the VPN connection. /// </para> /// </summary> public List<VpnStaticRoute> Routes { get { return this._routes; } set { this._routes = value; } } // Check to see if Routes property is set internal bool IsSetRoutes() { return this._routes != null && this._routes.Count > 0; } /// <summary> /// Gets and sets the property State. /// <para> /// The current state of the VPN connection. /// </para> /// </summary> public VpnState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Any tags assigned to the VPN connection. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property Type. /// <para> /// The type of VPN connection. /// </para> /// </summary> public GatewayType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } /// <summary> /// Gets and sets the property VgwTelemetry. /// <para> /// Information about the VPN tunnel. /// </para> /// </summary> public List<VgwTelemetry> VgwTelemetry { get { return this._vgwTelemetry; } set { this._vgwTelemetry = value; } } // Check to see if VgwTelemetry property is set internal bool IsSetVgwTelemetry() { return this._vgwTelemetry != null && this._vgwTelemetry.Count > 0; } /// <summary> /// Gets and sets the property VpnConnectionId. /// <para> /// The ID of the VPN connection. /// </para> /// </summary> public string VpnConnectionId { get { return this._vpnConnectionId; } set { this._vpnConnectionId = value; } } // Check to see if VpnConnectionId property is set internal bool IsSetVpnConnectionId() { return this._vpnConnectionId != null; } /// <summary> /// Gets and sets the property VpnGatewayId. /// <para> /// The ID of the virtual private gateway at the AWS side of the VPN connection. /// </para> /// </summary> public string VpnGatewayId { get { return this._vpnGatewayId; } set { this._vpnGatewayId = value; } } // Check to see if VpnGatewayId property is set internal bool IsSetVpnGatewayId() { return this._vpnGatewayId != null; } } }
using UnityEngine; using System; using System.Runtime.InteropServices; using System.Collections.Generic; public class BluetoothLEHardwareInterface { public enum CBCharacteristicProperties { CBCharacteristicPropertyBroadcast = 0x01, CBCharacteristicPropertyRead = 0x02, CBCharacteristicPropertyWriteWithoutResponse = 0x04, CBCharacteristicPropertyWrite = 0x08, CBCharacteristicPropertyNotify = 0x10, CBCharacteristicPropertyIndicate = 0x20, CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40, CBCharacteristicPropertyExtendedProperties = 0x80, CBCharacteristicPropertyNotifyEncryptionRequired = 0x100, CBCharacteristicPropertyIndicateEncryptionRequired = 0x200, }; public enum CBAttributePermissions { CBAttributePermissionsReadable = 0x01, CBAttributePermissionsWriteable = 0x02, CBAttributePermissionsReadEncryptionRequired = 0x04, CBAttributePermissionsWriteEncryptionRequired = 0x08, }; #if UNITY_IPHONE || UNITY_TVOS [DllImport ("__Internal")] private static extern void _iOSBluetoothLELog (string message); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEInitialize (bool asCentral, bool asPeripheral); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEDeInitialize (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEPauseMessages (bool isPaused); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEScanForPeripheralsWithServices (string serviceUUIDsString, bool allowDuplicates, bool rssiOnly); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERetrieveListOfPeripheralsWithServices (string serviceUUIDsString); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEStopScan (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEConnectToPeripheral (string name); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEDisconnectPeripheral (string name); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEReadCharacteristic (string name, string service, string characteristic); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEWriteCharacteristic (string name, string service, string characteristic, byte[] data, int length, bool withResponse); [DllImport ("__Internal")] private static extern void _iOSBluetoothLESubscribeCharacteristic (string name, string service, string characteristic); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEUnSubscribeCharacteristic (string name, string service, string characteristic); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEDisconnectAll (); #if !UNITY_TVOS [DllImport ("__Internal")] private static extern void _iOSBluetoothLEPeripheralName (string newName); [DllImport ("__Internal")] private static extern void _iOSBluetoothLECreateService (string uuid, bool primary); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERemoveService (string uuid); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERemoveServices (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLECreateCharacteristic (string uuid, int properties, int permissions, byte[] data, int length); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERemoveCharacteristic (string uuid); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERemoveCharacteristics (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEStartAdvertising (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEStopAdvertising (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEUpdateCharacteristicValue (string uuid, byte[] data, int length); #endif #elif UNITY_ANDROID static AndroidJavaObject _android = null; #endif private static BluetoothDeviceScript bluetoothDeviceScript; public static void Log (string message) { if (!Application.isEditor) { #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLELog (message); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothLog", message); #endif } } public static BluetoothDeviceScript Initialize (bool asCentral, bool asPeripheral, Action action, Action<string> errorAction) { bluetoothDeviceScript = null; GameObject bluetoothLEReceiver = GameObject.Find("BluetoothLEReceiver"); if (bluetoothLEReceiver == null) { bluetoothLEReceiver = new GameObject("BluetoothLEReceiver"); bluetoothDeviceScript = bluetoothLEReceiver.AddComponent<BluetoothDeviceScript>(); if (bluetoothDeviceScript != null) { bluetoothDeviceScript.InitializedAction = action; bluetoothDeviceScript.ErrorAction = errorAction; } } GameObject.DontDestroyOnLoad (bluetoothLEReceiver); if (Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.SendMessage ("OnBluetoothMessage", "Initialized"); } else { #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEInitialize (asCentral, asPeripheral); #elif UNITY_ANDROID if (_android == null) { AndroidJavaClass javaClass = new AndroidJavaClass ("com.shatalmic.unityandroidbluetoothlelib.UnityBluetoothLE"); _android = javaClass.CallStatic<AndroidJavaObject> ("getInstance"); } if (_android != null) _android.Call ("androidBluetoothInitialize", asCentral, asPeripheral); #endif } return bluetoothDeviceScript; } public static void DeInitialize (Action action) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.DeinitializedAction = action; if (Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.SendMessage ("OnBluetoothMessage", "DeInitialized"); } else { #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEDeInitialize (); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothDeInitialize"); #endif } } public static void FinishDeInitialize () { GameObject bluetoothLEReceiver = GameObject.Find("BluetoothLEReceiver"); if (bluetoothLEReceiver != null) GameObject.Destroy(bluetoothLEReceiver); } public static void PauseMessages (bool isPaused) { if (!Application.isEditor) { #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEPauseMessages (isPaused); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothPause", isPaused); #endif } } public static void ScanForPeripheralsWithServices (string[] serviceUUIDs, Action<string, string> action, Action<string, string, int, byte[]> actionAdvertisingInfo = null, bool rssiOnly = false) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { bluetoothDeviceScript.DiscoveredPeripheralAction = action; bluetoothDeviceScript.DiscoveredPeripheralWithAdvertisingInfoAction = actionAdvertisingInfo; if (bluetoothDeviceScript.DiscoveredDeviceList != null) bluetoothDeviceScript.DiscoveredDeviceList.Clear (); } string serviceUUIDsString = null; if (serviceUUIDs != null && serviceUUIDs.Length > 0) { serviceUUIDsString = ""; foreach (string serviceUUID in serviceUUIDs) serviceUUIDsString += serviceUUID + "|"; serviceUUIDsString = serviceUUIDsString.Substring (0, serviceUUIDsString.Length - 1); } #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEScanForPeripheralsWithServices (serviceUUIDsString, (actionAdvertisingInfo != null), rssiOnly); #elif UNITY_ANDROID if (_android != null) { if (serviceUUIDsString == null) serviceUUIDsString = ""; _android.Call ("androidBluetoothScanForPeripheralsWithServices", serviceUUIDsString, rssiOnly); } #endif } } public static void RetrieveListOfPeripheralsWithServices (string[] serviceUUIDs, Action<string, string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { bluetoothDeviceScript.RetrievedConnectedPeripheralAction = action; if (bluetoothDeviceScript.DiscoveredDeviceList != null) bluetoothDeviceScript.DiscoveredDeviceList.Clear (); } string serviceUUIDsString = serviceUUIDs.Length > 0 ? "" : null; foreach (string serviceUUID in serviceUUIDs) serviceUUIDsString += serviceUUID + "|"; // strip the last delimeter serviceUUIDsString = serviceUUIDsString.Substring (0, serviceUUIDsString.Length - 1); #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLERetrieveListOfPeripheralsWithServices (serviceUUIDsString); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothRetrieveListOfPeripheralsWithServices", serviceUUIDsString); #endif } } public static void StopScan () { if (!Application.isEditor) { #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEStopScan (); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothStopScan"); #endif } } public static void DisconnectAll () { if (!Application.isEditor) { #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEDisconnectAll (); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothDisconnectAll"); #endif } } public static void ConnectToPeripheral (string name, Action<string> connectAction, Action<string, string> serviceAction, Action<string, string, string> characteristicAction, Action<string> disconnectAction = null) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { bluetoothDeviceScript.ConnectedPeripheralAction = connectAction; bluetoothDeviceScript.DiscoveredServiceAction = serviceAction; bluetoothDeviceScript.DiscoveredCharacteristicAction = characteristicAction; bluetoothDeviceScript.ConnectedDisconnectPeripheralAction = disconnectAction; } #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEConnectToPeripheral (name); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothConnectToPeripheral", name); #endif } } public static void DisconnectPeripheral (string name, Action<string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.DisconnectedPeripheralAction = action; #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEDisconnectPeripheral (name); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothDisconnectPeripheral", name); #endif } } public static void ReadCharacteristic (string name, string service, string characteristic, Action<string, byte[]> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { if (!bluetoothDeviceScript.DidUpdateCharacteristicValueAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateCharacteristicValueAction[name] = new Dictionary<string, Action<string, byte[]>>(); #if UNITY_IPHONE || UNITY_TVOS bluetoothDeviceScript.DidUpdateCharacteristicValueAction [name] [characteristic] = action; #elif UNITY_ANDROID bluetoothDeviceScript.DidUpdateCharacteristicValueAction [name] [FullUUID (characteristic).ToLower ()] = action; #endif } #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEReadCharacteristic (name, service, characteristic); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidReadCharacteristic", name, service, characteristic); #endif } } public static void WriteCharacteristic (string name, string service, string characteristic, byte[] data, int length, bool withResponse, Action<string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.DidWriteCharacteristicAction = action; #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEWriteCharacteristic (name, service, characteristic, data, length, withResponse); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidWriteCharacteristic", name, service, characteristic, data, length, withResponse); #endif } } public static void SubscribeCharacteristic (string name, string service, string characteristic, Action<string> notificationAction, Action<string, byte[]> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { name = name.ToUpper (); service = service.ToUpper (); characteristic = characteristic.ToUpper (); #if UNITY_IPHONE || UNITY_TVOS if (!bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction [name] = new Dictionary<string, Action<string>> (); bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction [name] [characteristic] = notificationAction; if (!bluetoothDeviceScript.DidUpdateCharacteristicValueAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateCharacteristicValueAction [name] = new Dictionary<string, Action<string, byte[]>> (); bluetoothDeviceScript.DidUpdateCharacteristicValueAction [name] [characteristic] = action; #elif UNITY_ANDROID if (!bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction [name] = new Dictionary<string, Action<string>> (); bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction [name] [FullUUID (characteristic).ToLower ()] = notificationAction; if (!bluetoothDeviceScript.DidUpdateCharacteristicValueAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateCharacteristicValueAction [name] = new Dictionary<string, Action<string, byte[]>> (); bluetoothDeviceScript.DidUpdateCharacteristicValueAction [name] [FullUUID (characteristic).ToLower ()] = action; #endif } #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLESubscribeCharacteristic (name, service, characteristic); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidSubscribeCharacteristic", name, service, characteristic); #endif } } public static void SubscribeCharacteristicWithDeviceAddress (string name, string service, string characteristic, Action<string, string> notificationAction, Action<string, string, byte[]> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { name = name.ToUpper (); service = service.ToUpper (); characteristic = characteristic.ToUpper (); #if UNITY_IPHONE || UNITY_TVOS if (!bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[name] = new Dictionary<string, Action<string, string>>(); bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[name][characteristic] = notificationAction; if (!bluetoothDeviceScript.DidUpdateCharacteristicValueWithDeviceAddressAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateCharacteristicValueWithDeviceAddressAction[name] = new Dictionary<string, Action<string, string, byte[]>>(); bluetoothDeviceScript.DidUpdateCharacteristicValueWithDeviceAddressAction[name][characteristic] = action; #elif UNITY_ANDROID if (!bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[name] = new Dictionary<string, Action<string, string>>(); bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[name][FullUUID (characteristic).ToLower ()] = notificationAction; if (!bluetoothDeviceScript.DidUpdateCharacteristicValueWithDeviceAddressAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateCharacteristicValueWithDeviceAddressAction[name] = new Dictionary<string, Action<string, string, byte[]>>(); bluetoothDeviceScript.DidUpdateCharacteristicValueWithDeviceAddressAction[name][FullUUID (characteristic).ToLower ()] = action; #endif } #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLESubscribeCharacteristic (name, service, characteristic); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidSubscribeCharacteristic", name, service, characteristic); #endif } } public static void UnSubscribeCharacteristic (string name, string service, string characteristic, Action<string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { name = name.ToUpper (); service = service.ToUpper (); characteristic = characteristic.ToUpper (); #if UNITY_IPHONE || UNITY_TVOS if (!bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[name] = new Dictionary<string, Action<string, string>>(); bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[name][characteristic] = null; if (!bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction[name] = new Dictionary<string, Action<string>> (); bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction[name][characteristic] = null; #elif UNITY_ANDROID if (!bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[name] = new Dictionary<string, Action<string, string>>(); bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[name][FullUUID (characteristic).ToLower ()] = null; if (!bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction.ContainsKey (name)) bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction[name] = new Dictionary<string, Action<string>> (); bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction[name][FullUUID (characteristic).ToLower ()] = null; #endif } #if UNITY_IPHONE || UNITY_TVOS _iOSBluetoothLEUnSubscribeCharacteristic (name, service, characteristic); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidUnsubscribeCharacteristic", name, service, characteristic); #endif } } public static void PeripheralName (string newName) { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLEPeripheralName (newName); #endif } } public static void CreateService (string uuid, bool primary, Action<string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.ServiceAddedAction = action; #if UNITY_IPHONE _iOSBluetoothLECreateService (uuid, primary); #endif } } public static void RemoveService (string uuid) { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLERemoveService (uuid); #endif } } public static void RemoveServices () { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLERemoveServices (); #endif } } public static void CreateCharacteristic (string uuid, CBCharacteristicProperties properties, CBAttributePermissions permissions, byte[] data, int length, Action<string, byte[]> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.PeripheralReceivedWriteDataAction = action; #if UNITY_IPHONE _iOSBluetoothLECreateCharacteristic (uuid, (int)properties, (int)permissions, data, length); #endif } } public static void RemoveCharacteristic (string uuid) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.PeripheralReceivedWriteDataAction = null; #if UNITY_IPHONE _iOSBluetoothLERemoveCharacteristic (uuid); #endif } } public static void RemoveCharacteristics () { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLERemoveCharacteristics (); #endif } } public static void StartAdvertising (Action action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.StartedAdvertisingAction = action; #if UNITY_IPHONE _iOSBluetoothLEStartAdvertising (); #endif } } public static void StopAdvertising (Action action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.StoppedAdvertisingAction = action; #if UNITY_IPHONE _iOSBluetoothLEStopAdvertising (); #endif } } public static void UpdateCharacteristicValue (string uuid, byte[] data, int length) { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLEUpdateCharacteristicValue (uuid, data, length); #endif } } public static string FullUUID (string uuid) { if (uuid.Length == 4) return "0000" + uuid + "-0000-1000-8000-00805f9b34fb"; return uuid; } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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.IO; using System.Text; using DiscUtils; using DiscUtils.Vfs; namespace ExternalFileSystem { class Program { static void Main(string[] args) { MemoryStream dummyFileSystemData = new MemoryStream(Encoding.ASCII.GetBytes("MYFS")); FileSystemManager fsmgr = new FileSystemManager(); fsmgr.RegisterFileSystems(typeof(Program).Assembly); VirtualDisk dummyDisk = new DiscUtils.Raw.Disk(dummyFileSystemData, Ownership.None); VolumeManager volMgr = new VolumeManager(dummyDisk); VolumeInfo volInfo = volMgr.GetLogicalVolumes()[0]; DiscUtils.FileSystemInfo fsInfo = fsmgr.DetectFileSystems(volInfo)[0]; DiscFileSystem fs = fsInfo.Open(volInfo); ShowDir(fs.Root, 4); } private static void ShowDir(DiscDirectoryInfo dirInfo, int indent) { Console.WriteLine("{0}{1,-50} [{2}]", new String(' ', indent), dirInfo.FullName, dirInfo.CreationTimeUtc); foreach (DiscDirectoryInfo subDir in dirInfo.GetDirectories()) { ShowDir(subDir, indent + 0); } foreach (DiscFileInfo file in dirInfo.GetFiles()) { Console.WriteLine("{0}{1,-50} [{2}]", new String(' ', indent), file.FullName, file.CreationTimeUtc); } } } class MyDirEntry : VfsDirEntry { private static long _nextId; private bool _isDir; private string _name; private long _id; public MyDirEntry(string name, bool isDir) { _name = name; _isDir = isDir; _id = _nextId++; } public override bool IsDirectory { get { return _isDir; } } public override bool IsSymlink { get { return false; } } public override string FileName { get { return _name; } } public override bool HasVfsTimeInfo { get { return true; } } public override DateTime LastAccessTimeUtc { get { return new DateTime(1980, 10, 21, 11, 04, 22); } } public override DateTime LastWriteTimeUtc { get { return new DateTime(1980, 10, 21, 11, 04, 22); } } public override DateTime CreationTimeUtc { get { return new DateTime(1980, 10, 21, 11, 04, 22); } } public override bool HasVfsFileAttributes { get { return true; } } public override FileAttributes FileAttributes { get { return IsDirectory ? FileAttributes.Directory : FileAttributes.Normal; } } public override long UniqueCacheId { get { return _id; } } } class MyFile : IVfsFile { private MyDirEntry _dirEntry; public MyFile(MyDirEntry dirEntry) { _dirEntry = dirEntry; } public DateTime LastAccessTimeUtc { get { return _dirEntry.LastAccessTimeUtc; } set { throw new NotSupportedException(); } } public DateTime LastWriteTimeUtc { get { return _dirEntry.LastWriteTimeUtc; } set { throw new NotImplementedException(); } } public DateTime CreationTimeUtc { get { return _dirEntry.CreationTimeUtc; } set { throw new NotImplementedException(); } } public FileAttributes FileAttributes { get { return _dirEntry.FileAttributes; } set { throw new NotImplementedException(); } } public long FileLength { get { return 10; } } public IBuffer FileContent { get { SparseMemoryBuffer result = new SparseMemoryBuffer(10); result.Write(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 0, 10); return result; } } } class MyDirectory : MyFile, IVfsDirectory<MyDirEntry, MyFile> { private List<MyDirEntry> _entries; public MyDirectory(MyDirEntry dirEntry, bool isRoot) : base(dirEntry) { _entries = new List<MyDirEntry>(); if (isRoot) { for (int i = 0; i < 4; ++i) { _entries.Add(new MyDirEntry("DIR" + i, true)); } } for (int i = 0; i < 6; ++i) { _entries.Add(new MyDirEntry("FILE" + i, false)); } } public ICollection<MyDirEntry> AllEntries { get { return _entries; } } public MyDirEntry Self { get { return null; } } public MyDirEntry GetEntryByName(string name) { foreach (var entry in _entries) { if (string.Compare(name, entry.FileName, StringComparison.OrdinalIgnoreCase) == 0) { return entry; } } return null; } public MyDirEntry CreateNewFile(string name) { throw new NotSupportedException(); } } class MyContext : VfsContext { } class MyFileSystem : VfsFileSystem<MyDirEntry, MyFile, MyDirectory, MyContext> { public MyFileSystem() : base(new DiscFileSystemOptions()) { this.Context = new MyContext(); this.RootDirectory = new MyDirectory(new MyDirEntry("", true), true); } public override string VolumeLabel { get { return "Volume Label"; } } protected override MyFile ConvertDirEntryToFile(MyDirEntry dirEntry) { if (dirEntry.IsDirectory) { return new MyDirectory(dirEntry, false); } else { return new MyFile(dirEntry); } } public override string FriendlyName { get { return "My File System"; } } public override bool CanWrite { get { return false; } } } [VfsFileSystemFactory] class MyFileSystemFactory : VfsFileSystemFactory { public override DiscUtils.FileSystemInfo[] Detect(Stream stream, VolumeInfo volumeInfo) { byte[] header = new byte[4]; stream.Read(header, 0, 4); if (Encoding.ASCII.GetString(header, 0, 4) == "MYFS") { return new DiscUtils.FileSystemInfo[] { new VfsFileSystemInfo("MyFs", "My File System", Open) }; } return new DiscUtils.FileSystemInfo[0]; } private DiscFileSystem Open(Stream stream, VolumeInfo volInfo, FileSystemParameters parameters) { return new MyFileSystem(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MLRecommendAPI.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// *********************************************************************** // Copyright (c) 2008 Charlie Poole, Rob Prouse // // 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.Threading; using System.Collections.Generic; namespace NUnit.Framework.Syntax { // NOTE: The tests in this file ensure that the various // syntactic elements work together to create a // DelayedConstraint object with the proper values. public class AfterTest_SimpleConstraint : SyntaxTest { [SetUp] public void SetUp() { parseTree = "<after 1000 <equal 10>>"; staticSyntax = Is.EqualTo(10).After(1000); builderSyntax = Builder().EqualTo(10).After(1000); } } public class AfterMinutesTest_SimpleConstraint : SyntaxTest { [SetUp] public void SetUp() { parseTree = "<after 60000 <equal 10>>"; staticSyntax = Is.EqualTo(10).After(1).Minutes; builderSyntax = Builder().EqualTo(10).After(1).Minutes; } } public class AfterSecondsTest_SimpleConstraint : SyntaxTest { [SetUp] public void SetUp() { parseTree = "<after 20000 <equal 10>>"; staticSyntax = Is.EqualTo(10).After(20).Seconds; builderSyntax = Builder().EqualTo(10).After(20).Seconds; } } public class AfterMillisecondsTest_SimpleConstraint : SyntaxTest { [SetUp] public void SetUp() { parseTree = "<after 500 <equal 10>>"; staticSyntax = Is.EqualTo(10).After(500).MilliSeconds; builderSyntax = Builder().EqualTo(10).After(500).MilliSeconds; } } public class AfterTest_PropertyTest : SyntaxTest { [SetUp] public void SetUp() { parseTree = "<after 1000 <property X <equal 10>>>"; staticSyntax = Has.Property("X").EqualTo(10).After(1000); builderSyntax = Builder().Property("X").EqualTo(10).After(1000); } } public class AfterTest_AndOperator : SyntaxTest { [SetUp] public void SetUp() { parseTree = "<after 1000 <and <greaterthan 0> <lessthan 10>>>"; staticSyntax = Is.GreaterThan(0).And.LessThan(10).After(1000); builderSyntax = Builder().GreaterThan(0).And.LessThan(10).After(1000); } } public abstract class AfterSyntaxTests { protected bool flag; protected int num; protected object ob1, ob2, ob3; protected List<object> list; protected string greeting; [SetUp] public void InitializeValues() { this.flag = false; this.num = 0; this.ob1 = new object(); this.ob2 = new object(); this.ob3 = new object(); this.list = new List<object>(); this.list.Add(1); this.list.Add(2); this.list.Add(3); this.greeting = "hello"; new Thread(ModifyValuesAfterDelay).Start(); } private void ModifyValuesAfterDelay() { Thread.Sleep(100); this.flag = true; this.num = 1; this.ob1 = ob2; this.ob3 = null; this.list.Add(4); this.greeting += "world"; } } public class AfterSyntaxUsingAnonymousDelegates : AfterSyntaxTests { [Test] public void TrueTest() { Assert.That(delegate { return flag; }, Is.True.After(5000, 200)); } [Test] public void EqualToTest() { Assert.That(delegate { return num; }, Is.EqualTo(1).After(5000, 200)); } [Test] public void SameAsTest() { Assert.That(delegate { return ob1; }, Is.SameAs(ob2).After(5000, 200)); } [Test] public void GreaterTest() { Assert.That(delegate { return num; }, Is.GreaterThan(0).After(5000,200)); } [Test] public void HasMemberTest() { Assert.That(delegate { return list; }, Has.Member(4).After(5000, 200)); } [Test] public void NullTest() { Assert.That(delegate { return ob3; }, Is.Null.After(5000, 200)); } [Test] public void TextTest() { Assert.That(delegate { return greeting; }, Does.EndWith("world").After(5000, 200)); } } public class AfterSyntaxUsingLambda : AfterSyntaxTests { [Test] public void TrueTest() { Assert.That(() => flag, Is.True.After(5000, 200)); } [Test] public void EqualToTest() { Assert.That(() => num, Is.EqualTo(1).After(5000, 200)); } [Test] public void SameAsTest() { Assert.That(() => ob1, Is.SameAs(ob2).After(5000, 200)); } [Test] public void GreaterTest() { Assert.That(() => num, Is.GreaterThan(0).After(5000, 200)); } [Test] public void HasMemberTest() { Assert.That(() => list, Has.Member(4).After(5000, 200)); } [Test] public void NullTest() { Assert.That(() => ob3, Is.Null.After(5000, 200)); } [Test] public void TextTest() { Assert.That(() => greeting, Does.EndWith("world").After(5000, 200)); } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Tests.Mvc4 { using System; using System.Collections; using System.Globalization; using System.Linq; using System.Threading; using System.Web; using System.Web.Mvc; using Attributes; using Internal; using Moq; using Mvc; using Results; using Xunit; public class ModelBinderTester : IDisposable { FluentValidationModelValidatorProvider provider; DefaultModelBinder binder; ControllerContext controllerContext; public ModelBinderTester() { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); provider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()); ModelValidatorProviders.Providers.Add(provider); DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; binder = new DefaultModelBinder(); controllerContext = new ControllerContext { HttpContext = MockHttpContext.Create() }; } public void Dispose() { //Cleanup ModelValidatorProviders.Providers.Remove(provider); } protected ModelMetadata CreateMetaData(Type type) { var meta = new DataAnnotationsModelMetadataProvider(); return meta.GetMetadataForType(null, type); //return new ModelMetadata(new EmptyModelMetadataProvider(), null, null, type, null); } public class TestModel2 { } [Validator(typeof(TestModelValidator))] public class TestModel { public string Name { get; set; } } public class TestModelValidator : AbstractValidator<TestModel> { public TestModelValidator() { RuleFor(x => x.Name).NotNull().WithMessage("Validation Failed"); } } [Validator(typeof(TestModelValidator3))] public class TestModel3 { public int Id { get; set; } } public class TestModelValidator3 : AbstractValidator<TestModel3> { public TestModelValidator3() { RuleFor(x => x.Id).NotNull().WithMessage("Validation failed"); } } public class TestModelWithoutValidator { public int Id { get; set; } } [Validator(typeof(TestModel4Validator))] public class TestModel4 { public string Surname { get; set; } public string Forename { get; set; } public string Email { get; set; } public DateTime DateOfBirth { get; set; } public string Address1 { get; set; } } public class TestModel4Validator : AbstractValidator<TestModel4> { public TestModel4Validator() { RuleFor(x => x.Surname).NotEqual(x => x.Forename); RuleFor(x => x.Email) .EmailAddress(); RuleFor(x => x.Address1).NotEmpty(); } } [Validator(typeof(TestModel6Validator))] public class TestModel6 { public int Id { get; set; } } public class TestModel6Validator : AbstractValidator<TestModel6> { public TestModel6Validator() { //This ctor is intentionally blank. } } [FactAttribute] public void Should_add_all_errors_in_one_go() { var form = new FormCollection { { "Email", "foo" }, { "Surname", "foo" }, { "Forename", "foo" }, { "DateOfBirth", null }, { "Address1", null } }; var context = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModel4)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider(), }; binder.BindModel(controllerContext, context); context.ModelState.IsValidField("Email").ShouldBeFalse(); //Email validation failed context.ModelState.IsValidField("DateOfBirth").ShouldBeFalse(); //Date of Birth not specified (implicit required error) context.ModelState.IsValidField("Surname").ShouldBeFalse(); //cross-property } [Validator(typeof(TestModel5Validator))] public class TestModel5 { public int Id { get; set; } public bool SomeBool { get; set; } } public class TestModel5Validator : AbstractValidator<TestModel5> { public TestModel5Validator() { //force a complex rule RuleFor(x => x.SomeBool).Must(x => x == true); RuleFor(x => x.Id).NotEmpty(); } } [FactAttribute] public void Should_add_all_erorrs_in_one_go_when_NotEmpty_rule_specified_for_non_nullable_value_type() { var form = new FormCollection { { "SomeBool", "False" }, { "Id", "0" } }; var context = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModel5)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider(), }; binder.BindModel(controllerContext, context); context.ModelState.IsValidField("SomeBool").ShouldBeFalse(); //Complex rule context.ModelState.IsValidField("Id").ShouldBeFalse(); //NotEmpty for non-nullable value type } [FactAttribute] public void When_a_validation_error_occurs_the_error_should_be_added_to_modelstate() { var form = new FormCollection { { "test.Name", null } }; var bindingContext = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModel)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider() }; binder.BindModel(controllerContext, bindingContext); bindingContext.ModelState["test.Name"].Errors.Single().ErrorMessage.ShouldEqual("Validation Failed"); } [FactAttribute] public void When_a_validation_error_occurs_the_error_should_be_added_to_Modelstate_without_prefix() { var form = new FormCollection { { "Name", null } }; var bindingContext = new ModelBindingContext { ModelName = "foo", ModelMetadata = CreateMetaData(typeof(TestModel)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider() }; binder.BindModel(controllerContext, bindingContext); bindingContext.ModelState["Name"].Errors.Count().ShouldEqual(1); } [FactAttribute] public void Should_not_fail_when_no_validator_can_be_found() { var bindingContext = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModel2)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = new FormCollection().ToValueProvider() }; binder.BindModel(controllerContext, bindingContext).ShouldNotBeNull(); } [FactAttribute] public void Should_not_add_default_message_to_modelstate() { var form = new FormCollection { { "Id", "" } }; var bindingContext = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModel3)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider() }; binder.BindModel(controllerContext, bindingContext); bindingContext.ModelState["Id"].Errors.Single().ErrorMessage.ShouldEqual("Validation failed"); } [FactAttribute] public void Should_not_add_default_message_to_modelstate_when_there_is_no_required_validator_explicitly_specified() { var form = new FormCollection { { "Id", "" } }; var bindingContext = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModel6)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider() }; binder.BindModel(controllerContext, bindingContext); bindingContext.ModelState["Id"].Errors.Single().ErrorMessage.ShouldEqual("'Id' must not be empty."); } [FactAttribute] public void Should_add_Default_message_to_modelstate_when_no_validator_specified() { var form = new FormCollection { { "Id", "" } }; var bindingContext = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModelWithoutValidator)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider() }; binder.BindModel(controllerContext, bindingContext); bindingContext.ModelState["Id"].Errors.Single().ErrorMessage.ShouldEqual("A value is required."); } [FactAttribute] public void Allows_override_of_required_message_for_non_nullable_value_types() { var form = new FormCollection { { "Id", "" } }; var bindingContext = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModelWithOverridenMessageValueType)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider() }; binder.BindModel(controllerContext, bindingContext); //TODO: Localise test. bindingContext.ModelState["Id"].Errors.Single().ErrorMessage.ShouldEqual("Foo"); } [FactAttribute] public void Allows_override_of_required_property_name_for_non_nullable_value_types() { var form = new FormCollection { { "Id", "" } }; var bindingContext = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModelWithOverridenPropertyNameValueType)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider() }; binder.BindModel(controllerContext, bindingContext); //TODO: Localise test. bindingContext.ModelState["Id"].Errors.Single().ErrorMessage.ShouldEqual("'Foo' must not be empty." ); } [FactAttribute] public void Should_add_default_message_to_modelstate_when_both_fv_and_DataAnnotations_have_implicit_required_validation_disabled() { DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; provider.AddImplicitRequiredValidator = false; var form = new FormCollection { { "Id", "" } }; var bindingContext = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(TestModelWithoutValidator)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider() }; binder.BindModel(controllerContext, bindingContext); bindingContext.ModelState["Id"].Errors.Single().ErrorMessage.ShouldEqual("A value is required."); provider.AddImplicitRequiredValidator = true; DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = true; } [FactAttribute] public void Should_only_validate_specified_ruleset() { var form = new FormCollection { { "Email", "foo" }, { "Surname", "foo" }, { "Forename", "foo" }, }; var context = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(RulesetTestModel)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider(), }; var binder = new CustomizeValidatorAttribute { RuleSet = "Names" }; binder.BindModel(controllerContext, context); context.ModelState.IsValidField("Forename").ShouldBeFalse(); context.ModelState.IsValidField("Surname").ShouldBeFalse(); context.ModelState.IsValidField("Email").ShouldBeTrue(); } [FactAttribute] public void Should_only_validate_specified_properties() { var form = new FormCollection { { "Email", "foo" }, { "Surname", "foo" }, { "Forename", "foo" }, }; var context = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(PropertiesTestModel)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider(), }; var binder = new CustomizeValidatorAttribute { Properties = "Surname,Forename" }; binder.BindModel(controllerContext, context); context.ModelState.IsValidField("Forename").ShouldBeFalse(); context.ModelState.IsValidField("Surname").ShouldBeFalse(); context.ModelState.IsValidField("Email").ShouldBeTrue(); } [FactAttribute] public void When_interceptor_specified_Intercepts_validation() { var form = new FormCollection { { "Email", "foo" }, { "Surname", "foo" }, { "Forename", "foo" }, }; var context = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(PropertiesTestModel)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider(), }; var binder = new CustomizeValidatorAttribute { Interceptor = typeof(SimplePropertyInterceptor) }; binder.BindModel(controllerContext, context); context.ModelState.IsValidField("Forename").ShouldBeFalse(); context.ModelState.IsValidField("Surname").ShouldBeFalse(); context.ModelState.IsValidField("Email").ShouldBeTrue(); } [FactAttribute] public void When_interceptor_specified_Intercepts_validation_provides_custom_errors() { var form = new FormCollection { { "Email", "foo" }, { "Surname", "foo" }, { "Forename", "foo" }, }; var context = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(PropertiesTestModel)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider(), }; var binder = new CustomizeValidatorAttribute { Interceptor = typeof(ClearErrorsInterceptor) }; binder.BindModel(controllerContext, context); context.ModelState.IsValid.ShouldBeTrue(); } [FactAttribute] public void When_validator_implements_IValidatorInterceptor_directly_interceptor_invoked() { var form = new FormCollection { { "Email", "foo" }, { "Surname", "foo" }, { "Forename", "foo" }, }; var context = new ModelBindingContext { ModelName = "test", ModelMetadata = CreateMetaData(typeof(PropertiesTestModel2)), ModelState = new ModelStateDictionary(), FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider(), }; binder.BindModel(controllerContext, context); context.ModelState.IsValid.ShouldBeTrue(); } [FactAttribute] public void Validator_customizations_should_only_apply_to_single_parameter() { var form = new FormCollection { { "first.Email", "foo" }, { "first.Surname", "foo" }, { "first.Forename", "foo" }, { "second.Email", "foo" }, { "second.Surname", "foo" }, { "second.Forename", "foo" } }; var modelstate = new ModelStateDictionary(); var firstContext = new ModelBindingContext { ModelName = "first", ModelMetadata = CreateMetaData(typeof(RulesetTestModel)), ModelState = modelstate, FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider(), }; var secondContext = new ModelBindingContext { ModelName = "second", ModelMetadata = CreateMetaData(typeof(RulesetTestModel)), ModelState = modelstate, FallbackToEmptyPrefix = true, ValueProvider = form.ToValueProvider() }; // Use the customizations for the first var binder = new CustomizeValidatorAttribute { RuleSet = "Names" }; binder.BindModel(controllerContext, firstContext); // ...but not for the second. this.binder.BindModel(controllerContext, secondContext); //customizations should only apply to the first validator modelstate.IsValidField("first.Forename").ShouldBeFalse(); modelstate.IsValidField("first.Surname").ShouldBeFalse(); modelstate.IsValidField("second.Forename").ShouldBeTrue(); modelstate.IsValidField("second.Surname").ShouldBeTrue(); } private class SimplePropertyInterceptor : IValidatorInterceptor { readonly string[] properties = new[] { "Surname", "Forename" }; public ValidationContext BeforeMvcValidation(ControllerContext cc, ValidationContext context) { var newContext = context.Clone(selector: new MemberNameValidatorSelector(properties)); return newContext; } public ValidationResult AfterMvcValidation(ControllerContext cc, ValidationContext context, ValidationResult result) { return result; } } private class ClearErrorsInterceptor : IValidatorInterceptor { public ValidationContext BeforeMvcValidation(ControllerContext cc, ValidationContext context) { return null; } public ValidationResult AfterMvcValidation(ControllerContext cc, ValidationContext context, ValidationResult result) { return new ValidationResult(); } } [Validator(typeof(PropertiesValidator2))] private class PropertiesTestModel2 { public string Email { get; set; } public string Surname { get; set; } public string Forename { get; set; } } private class PropertiesValidator2 : AbstractValidator<PropertiesTestModel2>, IValidatorInterceptor { public PropertiesValidator2() { RuleFor(x => x.Email).NotEqual("foo"); RuleFor(x => x.Surname).NotEqual("foo"); RuleFor(x => x.Forename).NotEqual("foo"); } public ValidationContext BeforeMvcValidation(ControllerContext controllerContext, ValidationContext validationContext) { return validationContext; } public ValidationResult AfterMvcValidation(ControllerContext controllerContext, ValidationContext validationContext, ValidationResult result) { return new ValidationResult(); //empty errors } } [Validator(typeof(PropertiesValidator))] private class PropertiesTestModel { public string Email { get; set; } public string Surname { get; set; } public string Forename { get; set; } } private class PropertiesValidator : AbstractValidator<PropertiesTestModel> { public PropertiesValidator() { RuleFor(x => x.Email).NotEqual("foo"); RuleFor(x => x.Surname).NotEqual("foo"); RuleFor(x => x.Forename).NotEqual("foo"); } } [Validator(typeof(RulesetTestValidator))] private class RulesetTestModel { public string Email { get; set; } public string Surname { get; set; } public string Forename { get; set; } } private class RulesetTestValidator : AbstractValidator<RulesetTestModel> { public RulesetTestValidator() { RuleFor(x => x.Email).NotEqual("foo"); RuleSet("Names", () => { RuleFor(x => x.Surname).NotEqual("foo"); RuleFor(x => x.Forename).NotEqual("foo"); }); } } [Validator(typeof(TestModelWithOverridenMessageValueTypeValidator))] private class TestModelWithOverridenMessageValueType { public int Id { get; set; } } [Validator(typeof(TestModelWithOverridenPropertyNameValidator))] private class TestModelWithOverridenPropertyNameValueType { public int Id { get; set; } } private class TestModelWithOverridenMessageValueTypeValidator : AbstractValidator<TestModelWithOverridenMessageValueType> { public TestModelWithOverridenMessageValueTypeValidator() { RuleFor(x => x.Id).NotNull().WithMessage("Foo"); } } private class TestModelWithOverridenPropertyNameValidator : AbstractValidator<TestModelWithOverridenPropertyNameValueType> { public TestModelWithOverridenPropertyNameValidator() { RuleFor(x => x.Id).NotNull().WithName("Foo"); } } public class MockHttpContext : Mock<HttpContextBase> { public MockHttpContext() { Setup(x => x.Items).Returns(new Hashtable()); } public static HttpContextBase Create() { return new MockHttpContext().Object; } } } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using System.Collections.Specialized; using System.Linq.Expressions; using System.Web.UI; using Glass.Mapper.Sc.Fields; using Glass.Mapper.Sc.Razor.RenderingTypes; using Glass.Mapper.Sc.Razor.Web.Ui; using Glass.Mapper.Sc.RenderField; using Glass.Mapper.Sc.Web.Ui; using Sitecore.Data.Fields; using Sitecore.Diagnostics; using Sitecore.Web.UI; namespace Glass.Mapper.Sc.Razor { /// <summary> /// Class GlassHtmlFacade /// </summary> public class GlassHtmlFacade { private readonly HtmlTextWriter _writer; private IGlassHtml _glassHtml; /// <summary> /// Gets the sitecore context. /// </summary> /// <value> /// The sitecore context. /// </value> public ISitecoreContext SitecoreContext { get { return _glassHtml.SitecoreContext; } } /// <summary> /// Gets or sets the glass HTML. /// </summary> /// <value> /// The glass HTML. /// </value> public IGlassHtml GlassHtml { get { return _glassHtml; } set { _glassHtml = value; } } public ITemplateBase TemplateBase { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="GlassHtmlFacade" /> class. /// </summary> /// <param name="context">The context.</param> /// <param name="writer">The writer.</param> public GlassHtmlFacade(ISitecoreContext context, HtmlTextWriter writer, ITemplateBase templateBase) { _writer = writer; _glassHtml = new GlassHtml(context); TemplateBase = templateBase; } /// <summary> /// Editables the specified target. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target">The target.</param> /// <param name="field">The field.</param> /// <param name="parameters">The parameters.</param> /// <returns>RawString.</returns> public RawString Editable<T>(T target, Expression<Func<T, object>> field, object parameters = null) { return _glassHtml.Editable(target, field, parameters).RawString(); } /// <summary> /// Editables the specified target. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target">The target.</param> /// <param name="field">The field.</param> /// <param name="standardOutput">The standard output.</param> /// <param name="parameters">The parameters.</param> /// <returns>RawString.</returns> public RawString Editable<T>(T target, Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, object parameters = null) { return _glassHtml.Editable(target, field, standardOutput, parameters).RawString(); } /// <summary> /// Renders an image allowing simple page editor support /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model that contains the image field</param> /// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param> /// <param name="parameters">Image parameters, e.g. width, height</param> /// <param name="isEditable">Indicates if the field should be editable</param> /// <param name="outputHeightWidth">Indicates if the height and width attributes should be outputted when rendering the image</param> /// <returns></returns> public virtual RawString RenderImage<T>(T model, Expression<Func<T, object>> field, object parameters = null, bool isEditable = false, bool outputHeightWidth = true) { return _glassHtml.RenderImage(model, field, parameters, isEditable, outputHeightWidth).RawString(); } /// <summary> /// Indicates if the current page is in Page Editing mode /// </summary> public bool IsInEditingMode { get { return Sc.GlassHtml.IsInEditingMode; } } /// <summary> /// Render HTML for a link with contents /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model</param> /// <param name="field">The link field to user</param> /// <param name="attributes">Any additional link attributes</param> /// <param name="isEditable">Make the link editable</param> /// <returns></returns> public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false) { return GlassHtml.BeginRenderLink(model, field, _writer, attributes, isEditable); } /// <summary> /// Render HTML for a link /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model</param> /// <param name="field">The link field to user</param> /// <param name="attributes">Any additional link attributes</param> /// <param name="isEditable">Make the link editable</param> /// <param name="contents">Content to override the default decription or item name</param> /// <returns></returns> public virtual string RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents = null) { return GlassHtml.RenderLink(model, field, attributes, isEditable, contents); } /// <summary> /// Edits the frame. /// </summary> /// <param name="buttons">The buttons.</param> /// <param name="dataSource">The data source.</param> /// <returns></returns> public GlassEditFrame EditFrame(string buttons, string dataSource = null) { var frame = new GlassEditFrame(buttons, _writer, dataSource); frame.RenderFirstPart(); return frame; } /// <summary> /// Renders the partial. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="path">The path.</param> /// <param name="model">The model.</param> public void RenderPartial<T>(string path, T model) { var item = Sitecore.Context.Database.GetItem(path); Assert.IsNotNull(item, "Could not find rendering item {0}".Formatted(path)); var parameters = new NameValueCollection(); foreach (Field field in item.Fields) { parameters.Add(field.Name, field.Value); } Control control; if (item.TemplateID == SitecoreIds.GlassBehindRazorId) { var renderType = new BehindRazorRenderingType(); control = renderType.GetControl(parameters, false); } else { var renderType = new PartialRazorRenderingType(); control = renderType.GetControl(parameters, false); if (control is PartialControl) control.CastTo<PartialControl>().SetModel(model); } var webControl = control as WebControl; webControl.RenderControl(_writer); } /// <summary> /// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the /// model configuration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> public virtual T RenderingParameters<T>(string parameters) where T : class { return GlassHtml.GetRenderingParameters<T>(parameters); } /// <summary> /// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the /// model configuration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> public virtual T RenderingParameters<T>(NameValueCollection parameters) where T : class { return GlassHtml.GetRenderingParameters<T>(parameters); } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using log4net; using NetGore.Collections; using NetGore.Db.QueryBuilder; namespace NetGore.Db { /// <summary> /// Provides an interface between all objects and all the database handling methods. /// </summary> public abstract class DbControllerBase : IDbController { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static readonly List<DbControllerBase> _instances = new List<DbControllerBase>(); readonly DbConnectionPool _connectionPool; readonly string _database; readonly Dictionary<Type, object> _queryObjects = new Dictionary<Type, object>(); bool _disposed; /// <summary> /// Initializes a new instance of the <see cref="DbControllerBase"/> class. /// </summary> /// <param name="connectionString">The connection string.</param> /// <exception cref="ArgumentNullException"><paramref name="connectionString"/> is null or empty.</exception> /// <exception cref="DatabaseConnectionException">The connection failed to be created.</exception> protected DbControllerBase(string connectionString) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException("connectionString"); // Create the connection pool try { _connectionPool = CreateConnectionPool(connectionString); } catch (DbException ex) { throw CreateConnectionException(connectionString, ex); } if (log.IsInfoEnabled) log.InfoFormat("Database connection pool created."); // Test the connection _database = TestConnectionPoolAndGetDatabase(connectionString, _connectionPool); // Create the query objects PopulateQueryObjects(); // Add this connection to the list of instances lock (_instances) _instances.Add(this); } /// <summary> /// Creates the <see cref="DatabaseConnectionException"/> for when the connection fails. /// </summary> /// <param name="connectionString">The connection string.</param> /// <param name="innerException">The inner exception.</param> /// <returns>The <see cref="DatabaseConnectionException"/> for when the connection fails.</returns> /// <exception cref="DatabaseConnectionException">The database connection failed to be created.</exception> static DatabaseConnectionException CreateConnectionException(string connectionString, Exception innerException) { const string errmsg = "Failed to create connection to database: {0}{1}{0}{0}Connection string:{0}{2}"; var msg = string.Format(errmsg, Environment.NewLine, innerException.Message, connectionString); if (log.IsFatalEnabled) log.Fatal(msg, innerException); throw new DatabaseConnectionException(msg, innerException); } /// <summary> /// When overridden in the derived class, creates a <see cref="DbConnectionPool"/> for this /// <see cref="DbControllerBase"/>. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns>A DbConnectionPool for this <see cref="DbControllerBase"/>.</returns> protected abstract DbConnectionPool CreateConnectionPool(string connectionString); /// <summary> /// Gets an implementation of the <see cref="FindForeignKeysQuery"/> that works for this /// <see cref="DbControllerBase"/>. /// </summary> /// <param name="dbConnectionPool">The <see cref="DbConnectionPool"/> to use when creating the query.</param> /// <returns>The <see cref="FindForeignKeysQuery"/> to execute the query.</returns> protected abstract FindForeignKeysQuery GetFindForeignKeysQuery(DbConnectionPool dbConnectionPool); /// <summary> /// Gets an instance of the <see cref="DbControllerBase"/>. A <see cref="DbControllerBase"/> must have already /// been constructed for this to work. /// </summary> /// <returns>An available instance of the <see cref="DbControllerBase"/>.</returns> /// <exception cref="MemberAccessException">No <see cref="DbControllerBase"/>s have been created yet, or /// all created <see cref="DbControllerBase"/>s have already been disposed.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "DbController")] public static DbControllerBase GetInstance() { lock (_instances) { if (_instances.Count == 0) throw new MemberAccessException("Constructor on the DbController has not yet been called!"); return _instances[_instances.Count - 1]; } } /// <summary> /// Gets the SQL query string used for when testing if the database connection is valid. This string should /// be very simple and fool-proof, and work no matter what contents are in the database since this is just /// to test if the connection is working. /// </summary> /// <returns>The SQL query string used for when testing if the database connection is valid.</returns> protected abstract string GetTestQueryCommand(); /// <summary> /// Populates the <see cref="_queryObjects"/> with the query objects. /// </summary> /// <exception cref="InstantiateTypeException">A type failed to be instantiated.</exception> void PopulateQueryObjects() { if (log.IsInfoEnabled) log.InfoFormat("Creating query objects for database connection."); // Find the classes marked with our attribute var requiredConstructorParams = new Type[] { typeof(DbConnectionPool) }; var types = TypeHelper.FindTypesWithAttribute(typeof(DbControllerQueryAttribute), requiredConstructorParams); // Create an instance of each of the types foreach (var type in types) { var instance = Activator.CreateInstance(type, _connectionPool); if (instance == null) { const string errmsg = "Failed to create instance of Type `{0}`."; if (log.IsFatalEnabled) log.Fatal(string.Format(errmsg, type)); Debug.Fail(string.Format(errmsg, type)); throw new InstantiateTypeException(type); } // Add the instance to the collection _queryObjects.Add(type, instance); if (log.IsDebugEnabled) log.DebugFormat("Created instance of query class Type `{0}`.", type.Name); } if (log.IsInfoEnabled) log.Info("DbController successfully initialized all queries."); } /// <summary> /// Tests the database connection to make sure it works. /// </summary> /// <param name="connectionString">The connection string used.</param> /// <param name="pool">The pool of connections.</param> /// <returns>The name of the database.</returns> /// <exception cref="DatabaseConnectionException">The database connection failed to be created.</exception> string TestConnectionPoolAndGetDatabase(string connectionString, IObjectPool<PooledDbConnection> pool) { string database; try { using (var poolableConn = pool.Acquire()) { database = poolableConn.Connection.Database; using (var cmd = poolableConn.Connection.CreateCommand()) { cmd.CommandText = GetTestQueryCommand(); cmd.ExecuteNonQuery(); } } } catch (DbException ex) { throw CreateConnectionException(connectionString, ex); } return database; } #region IDbController Members /// <summary> /// Gets the <see cref="DbConnectionPool"/> used by this <see cref="IDbController"/>. /// </summary> public DbConnectionPool ConnectionPool { get { return _connectionPool; } } /// <summary> /// Gets the name of the database that this <see cref="IDbController"/> instance is connected to. /// </summary> public string Database { get { return _database; } } /// <summary> /// Gets the <see cref="IQueryBuilder"/> to build queries for this connection. /// </summary> public abstract IQueryBuilder QueryBuilder { get; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public virtual void Dispose() { if (_disposed) return; _disposed = true; lock (_instances) _instances.Remove(this); // Dispose of all the queries, where possible foreach (var disposableQuery in _queryObjects.OfType<IDisposable>()) { disposableQuery.Dispose(); } // Dispose of the DbConnectionPool _connectionPool.Dispose(); } /// <summary> /// Gets the schema, table, and column tuples for columns containing a reference to the specified primary key. /// </summary> /// <param name="database">Database or schema object that the <paramref name="table"/> belongs to.</param> /// <param name="table">The table of the primary key.</param> /// <param name="column">The column of the primary key.</param> /// <returns>An IEnumerable of the name of the tables and columns that reference a the given primary key.</returns> public IEnumerable<SchemaTableColumn> GetPrimaryKeyReferences(string database, string table, string column) { var query = GetFindForeignKeysQuery(_connectionPool); var results = query.Execute(database, table, column); return results; } /// <summary> /// Gets a query that was marked with the attribute DbControllerQueryAttribute. /// </summary> /// <typeparam name="T">The Type of query.</typeparam> /// <returns>The query instance of type <typeparamref name="T"/>.</returns> /// <exception cref="ArgumentException">Type <typeparamref name="T"/> was not found in the query cache.</exception> public T GetQuery<T>() { object value; if (!_queryObjects.TryGetValue(typeof(T), out value)) { const string errmsg = "Failed to find a query of Type `{0}`. Make sure the attribute `{1}`" + " is attached to the specified class."; var err = string.Format(errmsg, typeof(T), typeof(DbControllerQueryAttribute)); log.Fatal(err); Debug.Fail(err); throw new ArgumentException(err); } return (T)value; } /// <summary> /// Finds all of the column names in the given <paramref name="table"/>. /// </summary> /// <param name="table">The table.</param> /// <returns>All of the column names in the given <paramref name="table"/>.</returns> public IEnumerable<string> GetTableColumns(string table) { var ret = new List<string>(); using (var conn = _connectionPool.Acquire()) { using (var cmd = conn.Connection.CreateCommand()) { cmd.CommandText = string.Format("SELECT * FROM `{0}` WHERE 0=1", table); using (var r = cmd.ExecuteReader()) { var fields = r.FieldCount; for (var i = 0; i < fields; i++) { var fieldName = r.GetName(i); ret.Add(fieldName); } } } } return ret; } /// <summary> /// When overridden in the derived class, removes all of the primary keys from a table where there is no foreign keys for the /// respective primary key. /// For safety reasons, if a column has no foreign keys, the query will be aborted. /// </summary> /// <param name="schema">The schema or database name of the table.</param> /// <param name="table">The table to check.</param> /// <param name="column">The primary key column.</param> /// <returns>The number of rows removed, or -1 if there were no foreign keys for the given column in the first place.</returns> public abstract int RemoveUnreferencedPrimaryKeys(string schema, string table, string column); /// <summary> /// Executes raw sql directly against the database with no parameterization or pooling. /// Only use this for quick one-off queries, such as queries to run during load/unload of the server or editor-specific tasks. /// </summary> /// <param name="sql">The sql to execute.</param> public abstract void ExecuteNonQuery(string sql); /// <summary> /// Executes raw sql directly against the database with no parameterization or pooling. /// Only use this for quick one-off queries, such as queries to run during load/unload of the server or editor-specific tasks. /// </summary> /// <param name="sqls">The sql queries to execute. Gets wrapped up in a transaction.</param> public abstract void ExecuteNonQueries(params string[] sqls); /// <summary> /// Executes raw sql directly against the database with no parameterization or pooling. /// Only use this for quick one-off queries, such as queries to run during load/unload of the server or editor-specific tasks. /// </summary> /// <param name="sql">The sql to execute.</param> /// <param name="readFunc">The function used to describe how to the results of each row.</param> /// <typeparam name="T">The return type for read rows.</typeparam> public abstract List<T> ExecuteQuery<T>(string sql, Func<DbDataReader, T> readFunc); #endregion } }
using System; using System.Drawing; using NUnit.Framework; namespace OpenQA.Selenium { [TestFixture] public class WindowTest : DriverTestFixture { private Size originalWindowSize; [SetUp] public void GetBrowserWindowSize() { this.originalWindowSize = driver.Manage().Window.Size; } [TearDown] public void RestoreBrowserWindow() { driver.Manage().Window.Size = originalWindowSize; } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToGetTheSizeOfTheCurrentWindow() { Size size = driver.Manage().Window.Size; Assert.That(size.Width, Is.GreaterThan(0)); Assert.That(size.Height, Is.GreaterThan(0)); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToSetTheSizeOfTheCurrentWindow() { IWindow window = driver.Manage().Window; Size size = window.Size; // resize relative to the initial size, since we don't know what it is Size targetSize = new Size(size.Width - 20, size.Height - 20); window.Size = targetSize; Size newSize = window.Size; Assert.AreEqual(targetSize.Width, newSize.Width); Assert.AreEqual(targetSize.Height, newSize.Height); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToSetTheSizeOfTheCurrentWindowFromFrame() { IWindow window = driver.Manage().Window; Size size = window.Size; driver.Url = framesetPage; driver.SwitchTo().Frame("fourth"); try { // resize relative to the initial size, since we don't know what it is Size targetSize = new Size(size.Width - 20, size.Height - 20); window.Size = targetSize; Size newSize = window.Size; Assert.AreEqual(targetSize.Width, newSize.Width); Assert.AreEqual(targetSize.Height, newSize.Height); } finally { driver.SwitchTo().DefaultContent(); } } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToSetTheSizeOfTheCurrentWindowFromIFrame() { IWindow window = driver.Manage().Window; Size size = window.Size; driver.Url = iframePage; driver.SwitchTo().Frame("iframe1-name"); try { // resize relative to the initial size, since we don't know what it is Size targetSize = new Size(size.Width - 20, size.Height - 20); window.Size = targetSize; Size newSize = window.Size; Assert.AreEqual(targetSize.Width, newSize.Width); Assert.AreEqual(targetSize.Height, newSize.Height); } finally { driver.SwitchTo().DefaultContent(); } } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToGetThePositionOfTheCurrentWindow() { Point position = driver.Manage().Window.Position; Assert.That(position.X, Is.GreaterThan(0)); Assert.That(position.Y, Is.GreaterThan(0)); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToMaximizeTheCurrentWindow() { Size targetSize = new Size(450, 275); ChangeSizeTo(targetSize); Maximize(); IWindow window = driver.Manage().Window; Assert.That(window.Size.Height, Is.GreaterThan(targetSize.Height)); Assert.That(window.Size.Width, Is.GreaterThan(targetSize.Width)); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToMaximizeTheWindowFromFrame() { driver.Url = framesetPage; ChangeSizeTo(new Size(450, 275)); driver.SwitchTo().Frame("fourth"); try { Maximize(); } finally { driver.SwitchTo().DefaultContent(); } } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToMaximizeTheWindowFromIframe() { driver.Url = iframePage; ChangeSizeTo(new Size(450, 275)); driver.SwitchTo().Frame("iframe1-name"); try { Maximize(); } finally { driver.SwitchTo().DefaultContent(); } } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToSetThePositionOfTheCurrentWindow() { IWindow window = driver.Manage().Window; Point position = window.Position; Point targetPosition = new Point(position.X + 10, position.Y + 10); window.Position = targetPosition; Point newLocation = window.Position; Assert.AreEqual(targetPosition.X, newLocation.X); Assert.AreEqual(targetPosition.Y, newLocation.Y); } [Test] [IgnoreBrowser(Browser.Edge, "Not implemented in driver")] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToFullScreenTheCurrentWindow() { Size targetSize = new Size(450, 275); ChangeSizeTo(targetSize); FullScreen(); IWindow window = driver.Manage().Window; Size windowSize = window.Size; Point windowPosition = window.Position; Assert.That(windowSize.Height, Is.GreaterThan(targetSize.Height)); Assert.That(windowSize.Width, Is.GreaterThan(targetSize.Width)); } [Test] [IgnoreBrowser(Browser.Edge, "Not implemented in driver")] [IgnoreBrowser(Browser.Chrome, "Chrome window size does not report zero when minimized.")] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToMinimizeTheCurrentWindow() { Size targetSize = new Size(450, 275); ChangeSizeTo(targetSize); Minimize(); IWindow window = driver.Manage().Window; Size windowSize = window.Size; Point windowPosition = window.Position; Assert.That(windowSize.Height, Is.LessThan(targetSize.Height)); Assert.That(windowSize.Width, Is.LessThan(targetSize.Width)); Assert.That(windowPosition.X, Is.LessThan(0)); Assert.That(windowPosition.Y, Is.LessThan(0)); } private void FullScreen() { IWindow window = driver.Manage().Window; Size currentSize = window.Size; window.FullScreen(); } private void Maximize() { IWindow window = driver.Manage().Window; Size currentSize = window.Size; window.Maximize(); WaitFor(WindowHeightToBeGreaterThan(currentSize.Height), "Window height was not greater than " + currentSize.Height.ToString()); WaitFor(WindowWidthToBeGreaterThan(currentSize.Width), "Window width was not greater than " + currentSize.Width.ToString()); } private void Minimize() { IWindow window = driver.Manage().Window; Size currentSize = window.Size; window.Minimize(); WaitFor(WindowHeightToBeLessThan(currentSize.Height), "Window height was not less than " + currentSize.Height.ToString()); WaitFor(WindowWidthToBeLessThan(currentSize.Width), "Window width was not less than " + currentSize.Width.ToString()); } private void ChangeSizeTo(Size targetSize) { IWindow window = driver.Manage().Window; window.Size = targetSize; WaitFor(WindowHeightToBeEqualTo(targetSize.Height), "Window height was not " + targetSize.Height.ToString()); WaitFor(WindowWidthToBeEqualTo(targetSize.Width), "Window width was not " + targetSize.Width.ToString()); } private void ChangeSizeBy(int deltaX, int deltaY) { IWindow window = driver.Manage().Window; Size size = window.Size; ChangeSizeTo(new Size(size.Width + deltaX, size.Height + deltaY)); } private Func<bool> WindowHeightToBeEqualTo(int height) { return () => { return driver.Manage().Window.Size.Height == height; }; } private Func<bool> WindowWidthToBeEqualTo(int width) { return () => { return driver.Manage().Window.Size.Width == width; }; } private Func<bool> WindowHeightToBeGreaterThan(int height) { return () => { return driver.Manage().Window.Size.Height > height; }; } private Func<bool> WindowWidthToBeGreaterThan(int width) { return () => { return driver.Manage().Window.Size.Width > width; }; } private Func<bool> WindowHeightToBeLessThan(int height) { return () => { return driver.Manage().Window.Size.Height < height; }; } private Func<bool> WindowWidthToBeLessThan(int width) { return () => { return driver.Manage().Window.Size.Width < width; }; } } }
using System; using System.IO; using NUnit.Framework; using TheFactory.Datastore; using System.Collections.Generic; namespace TheFactory.DatastoreTests { [TestFixture] public class TransactionLogReaderTests { [Test] public void TestTransactionLogReaderSingle() { var bytes = new byte[] { 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x01, // type (Full). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1 }; var stream = new MemoryStream(bytes); var reader = new TransactionLogReader(stream); Slice data = null; foreach (var t in reader.Transactions()) { data = t; break; } Assert.True(data.Equals(new Slice(bytes, TransactionLog.HeaderSize, 10))); } [Test] public void TestTransactionLogReaderSingleFirstLast() { var bytes = new byte[] { 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x02, // type (First). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1, 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x04, // type (Last). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1 }; var stream = new MemoryStream(bytes); var reader = new TransactionLogReader(stream); Slice data = null; foreach (var t in reader.Transactions()) { data = t; break; } Slice orig = (Slice)bytes; Assert.True(data.Subslice(0, 10).Equals(orig.Subslice(TransactionLog.HeaderSize, 10))); Assert.True(data.Subslice(10, 10).Equals(orig.Subslice(2*TransactionLog.HeaderSize+10, 10))); } [Test] public void TestTransactionLogReaderSingleFirstMiddleLast() { var bytes = new byte[] { 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x02, // type (First). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1, 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x03, // type (Middle). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1, 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x04, // type (Last). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1 }; var stream = new MemoryStream(bytes); var reader = new TransactionLogReader(stream); Slice data = null; foreach (var t in reader.Transactions()) { data = t; break; } Slice orig = (Slice)bytes; Assert.True(data.Subslice(0, 10).Equals(orig.Subslice(TransactionLog.HeaderSize, 10))); Assert.True(data.Subslice(10, 10).Equals(orig.Subslice(2*TransactionLog.HeaderSize+10, 10))); Assert.True(data.Subslice(20, 10).Equals(orig.Subslice(3*TransactionLog.HeaderSize+20, 10))); } [Test] [ExpectedException(typeof(FormatException))] public void TestTransactionLogReaderSingleBadRecordType() { var bytes = new byte[] { 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x03, // type (Middle). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1 }; var stream = new MemoryStream(bytes); var reader = new TransactionLogReader(stream); reader.ReadTransaction(new MemoryStream()); } [Test] [ExpectedException(typeof(FormatException))] public void TestTransactionLogReaderSingleBadSecondRecordType() { var bytes = new byte[] { 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x02, // type (First). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1, 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x01, // type (Full). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1 }; var stream = new MemoryStream(bytes); var reader = new TransactionLogReader(stream); reader.ReadTransaction(new MemoryStream()); } [Test] [ExpectedException(typeof(FormatException))] public void TestTransactionLogReaderSingleBadChecksum() { var bytes = new byte[] { 0xB2, 0x16, 0x3A, 0x00, // checksum (bad). 0x01, // type (Full). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1 }; var stream = new MemoryStream(bytes); var reader = new TransactionLogReader(stream); reader.ReadTransaction(new MemoryStream()); } [Test] public void TestTransactionLogReaderReplaySingle() { var bytes = new byte[] { 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x01, // type (Full). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1 }; var stream = new MemoryStream(bytes); var reader = new TransactionLogReader(stream); var count = 0; foreach (var t in reader.Transactions()) { count++; } Assert.True(count == 1); } [Test] public void TestTransactionLogReaderReplayFirstBad() { var bytes = new byte[] { 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x04, // type (Last). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1, 0xB2, 0x16, 0x3A, 0xFF, // checksum. 0x01, // type (Full). 0x00, 0x0A, // length. 0x82, 0xD1, 0xAF, 0x84, 0x29, 0xD1, 0x04, 0x58, 0x67, 0xC1 }; var stream = new MemoryStream(bytes); var reader = new TransactionLogReader(stream); var count = 0; Assert.Throws(typeof(FormatException), delegate { foreach (var t in reader.Transactions()) { count++; } }); } } [TestFixture] public class TransactionLogWriterTests { private Random random; [SetUp] public void SetUp() { random = new Random(); } [Test] public void TestTransactionLogWriterEmitTransactionFull() { var data = new byte[10]; random.NextBytes(data); var stream = new MemoryStream(); var log = new TransactionLogWriter(stream); log.EmitTransaction((Slice)data); Assert.True(stream.Length == data.Length + TransactionLog.HeaderSize); var buf = stream.GetBuffer(); Assert.True(buf[4] == (byte)TransactionLog.RecordType.Full); Assert.True(buf[5] == (byte)0); Assert.True(buf[6] == (byte)data.Length); Assert.True(buf.CompareBytes(TransactionLog.HeaderSize, data, 0, data.Length)); } [Test] public void TestTransactionLogWriterEmitTransactionBoundaryFirst() { var data = new byte[100]; random.NextBytes(data); var first = data.Length / 2; var lastOffset = TransactionLog.MaxBlockSize; var stream = new MemoryStream(); // Pretend we're near the end of the block by moving the underlying stream position. var skip = TransactionLog.MaxBlockSize - TransactionLog.HeaderSize - first; stream.Position = skip; var log = new TransactionLogWriter(stream); log.EmitTransaction((Slice)data); var buf = stream.GetBuffer(); // skip checksum: 4 bytes Assert.True(buf[skip + 4] == (byte)TransactionLog.RecordType.First); Assert.True(buf[skip + 5] == (byte)0); Assert.True(buf[skip + 6] == (byte)first); Assert.True(buf.CompareBytes(skip + TransactionLog.HeaderSize, data, 0, first)); Assert.True(buf[lastOffset + 4] == (byte)TransactionLog.RecordType.Last); Assert.True(buf[lastOffset + 5] == (byte)0); Assert.True(buf[lastOffset + 6] == (byte)(data.Length - first)); Assert.True(buf.CompareBytes(lastOffset + TransactionLog.HeaderSize, data, first, data.Length - first)); } [Test] public void TestTransactionLogWriterEmitTransactionBoundaryFirstNoData() { var data = new byte[10]; random.NextBytes(data); var first = 0; var lastOffset = TransactionLog.MaxBlockSize; var stream = new MemoryStream(); var log = new TransactionLogWriter(stream); // Pretend we're near the end of the block by moving the underlying stream position. var skip = TransactionLog.MaxBlockSize - TransactionLog.HeaderSize; stream.Position = skip; log.EmitTransaction((Slice)data); var buf = stream.GetBuffer(); Assert.True(buf[skip + 4] == (byte)TransactionLog.RecordType.First); Assert.True(buf[skip + 5] == (byte)0); Assert.True(buf[skip + 6] == (byte)first); Assert.True(buf.CompareBytes(skip + TransactionLog.HeaderSize, data, 0, first)); Assert.True(buf[lastOffset + 4] == (byte)TransactionLog.RecordType.Last); Assert.True(buf[lastOffset + 5] == (byte)0); Assert.True(buf[lastOffset + 6] == (byte)(data.Length - first)); Assert.True(buf.CompareBytes(lastOffset + TransactionLog.HeaderSize, data, first, data.Length - first)); } [Test] public void TestTransactionLogWriterEmitTransactionBoundaryPadZeroes() { var data = new byte[10]; random.NextBytes(data); // starting here leaves (HeaderSize-1) bytes available to write, requiring padding var start = TransactionLog.MaxBlockSize - TransactionLog.HeaderSize + 1; var recordOffset = TransactionLog.MaxBlockSize; var stream = new MemoryStream(); var log = new TransactionLogWriter(stream); // Pretend we're near the end of the block by moving the underlying stream position. stream.Position = start; log.EmitTransaction((Slice)data); var buf = stream.GetBuffer(); for (var i = start; i < recordOffset; i++) { Assert.True(buf[i] == 0); } Assert.True(buf[recordOffset + 4] == (byte)TransactionLog.RecordType.Full); Assert.True(buf[recordOffset + 5] == (byte)0); Assert.True(buf[recordOffset + 6] == (byte)data.Length); Assert.True(buf.CompareBytes(recordOffset + TransactionLog.HeaderSize, data, 0, data.Length)); } [Test] public void TestTransactionLogWriterEmitTransactionBoundaryMany() { var len = TransactionLog.MaxBlockSize * 3; var data = new byte[len]; random.NextBytes(data); var stream = new MemoryStream(); var log = new TransactionLogWriter(stream); log.EmitTransaction((Slice)data); var buf = stream.GetBuffer(); Assert.True(buf[4] == (byte)TransactionLog.RecordType.First); Assert.True(buf.CompareBytes(TransactionLog.HeaderSize, data, 0, TransactionLog.MaxBlockSize-TransactionLog.HeaderSize)); var offset = TransactionLog.MaxBlockSize; Assert.True(buf[offset + 4] == (byte)TransactionLog.RecordType.Middle); offset += TransactionLog.MaxBlockSize; Assert.True(buf[offset + 4] == (byte)TransactionLog.RecordType.Middle); offset += TransactionLog.MaxBlockSize; Assert.True(buf[offset + 4] == (byte)TransactionLog.RecordType.Last); } } [TestFixture] public class TransactionLogIntegrationTests { private Random random; [SetUp] public void SetUp() { random = new Random(); } private long TransactionLogIntegration(int size, int count) { var bytes = new byte[size * count]; random.NextBytes(bytes); var stream = new MemoryStream(); var writer = new TransactionLogWriter(stream); // Write random log. var buf = new byte[size]; for (var i = 0; i < count; i++) { Buffer.BlockCopy(bytes, i * size, buf, 0, size); writer.EmitTransaction((Slice)buf); } // Seek to the start. stream.Seek(0, SeekOrigin.Begin); var reader = new TransactionLogReader(stream); int n = 0; foreach (var t in reader.Transactions()) { n++; } return n; } [Test] public void TestTransactionLogIntegration0x4700() { // (0 + 7) * 4700 = 32900 (will have > 1 block). // 32768 / 7.0 = 4681.14 (a transaction will cross block). // 32768 - 7 * 4681 = 32767 (will cause zero padding). var size = 0; var count = 4700; var result = TransactionLogIntegration(size, count); Assert.True(result == count); } [Test] public void TestTransactionLogIntegration100x310() { // (100 + 7) * 310 = 33170 (will have > 1 block). // 32768 / 107.0 = 306.24 (a transaction will cross a block). // 32768 - 7 * 310 = 30598 (no zero padding). var size = 100; var count = 310; var result = TransactionLogIntegration(size, count); Assert.True(result == count); } } }
using Loon.Core.Graphics.Opengl; using Loon.Core.Geom; using Loon.Action.Sprite; using System.Runtime.CompilerServices; using Loon.Utils; namespace Loon.Core { public class EmulatorButtons : LRelease { class up_monitor : EmulatorButton.Monitor { private EmulatorListener _l; public up_monitor(EmulatorListener l) { this._l = l; } public void Free() { if (_l != null) { _l.UnUpClick(); } } public void Call() { if (_l != null) { _l.OnUpClick(); } } }; class down_monitor : EmulatorButton.Monitor { private EmulatorListener _l; public down_monitor(EmulatorListener l) { this._l = l; } public void Free() { if (_l != null) { _l.UnDownClick(); } } public void Call() { if (_l != null) { _l.OnDownClick(); } } }; class left_monitor : EmulatorButton.Monitor { private EmulatorListener _l; public left_monitor(EmulatorListener l) { this._l = l; } public void Free() { if (_l != null) { _l.UnLeftClick(); } } public void Call() { if (_l != null) { _l.OnLeftClick(); } } }; class right_monitor : EmulatorButton.Monitor { private EmulatorListener _l; public right_monitor(EmulatorListener l) { this._l = l; } public void Free() { if (_l != null) { _l.UnRightClick(); } } public void Call() { if (_l != null) { _l.OnRightClick(); } } }; class triangle_monitor : EmulatorButton.Monitor { private EmulatorListener _l; public triangle_monitor(EmulatorListener l) { this._l = l; } public void Free() { if (_l != null) { _l.UnTriangleClick(); } } public void Call() { if (_l != null) { _l.OnTriangleClick(); } } }; class square_monitor : EmulatorButton.Monitor { private EmulatorListener _l; public square_monitor(EmulatorListener l) { this._l = l; } public void Free() { if (_l != null) { _l.UnSquareClick(); } } public void Call() { if (_l != null) { _l.OnSquareClick(); } } }; class circle_monitor : EmulatorButton.Monitor { private EmulatorListener _l; public circle_monitor(EmulatorListener l) { this._l = l; } public void Free() { if (_l != null) { _l.UnCircleClick(); } } public void Call() { if (_l != null) { _l.OnCircleClick(); } } }; class cancel_monitor : EmulatorButton.Monitor { private EmulatorListener _l; public cancel_monitor(EmulatorListener l) { this._l = l; } public void Free() { if (_l != null) { _l.UnCancelClick(); } } public void Call() { if (_l != null) { _l.OnCancelClick(); } } }; private LTextureRegion dpad, buttons; private EmulatorButton up, left, right, down; private EmulatorButton triangle, square, circle, cancel; private EmulatorListener emulatorListener; private int offsetX, offsetY, width, height; private const int offset = 10; private bool visible; private LTexturePack pack; public EmulatorButtons(EmulatorListener el):this(el, LSystem.screenRect.width, LSystem.screenRect.height) { } public EmulatorButtons(EmulatorListener el, int w, int h):this(el, w, h, LSystem.EMULATOR_BUTTIN_SCALE) { } public EmulatorButtons(EmulatorListener el, int w, int h, float scale) { this.emulatorListener = el; if (pack == null) { pack = new LTexturePack(); pack.PutImage(XNAConfig.LoadTex(LSystem.FRAMEWORK_IMG_NAME + "e1.png")); pack.PutImage(XNAConfig.LoadTex(LSystem.FRAMEWORK_IMG_NAME + "e2.png")); pack.Pack(Loon.Core.Graphics.Opengl.LTexture.Format.LINEAR); } RectBox.Rect2i bounds = pack.GetEntry(0).getBounds(); this.dpad = new LTextureRegion(pack.GetTexture(), bounds.left, bounds.top, bounds.right, bounds.bottom); bounds = pack.GetEntry(1).getBounds(); this.buttons = new LTextureRegion(pack.GetTexture(), bounds.left, bounds.top, bounds.right, bounds.bottom); this.width = w; this.height = h; if (scale <= 0f) { this.up = new EmulatorButton(dpad, 40, 40, 40, 0, true, 60, 60); this.left = new EmulatorButton(dpad, 40, 40, 0, 40, true, 60, 60); this.right = new EmulatorButton(dpad, 40, 40, 80, 40, true, 60, 60); this.down = new EmulatorButton(dpad, 40, 40, 40, 80, true, 60, 60); this.triangle = new EmulatorButton(buttons, 48, 48, 48, 0, true, 68, 68); this.square = new EmulatorButton(buttons, 48, 48, 0, 48, true, 68, 68); this.circle = new EmulatorButton(buttons, 48, 48, 96, 48, true, 68, 68); this.cancel = new EmulatorButton(buttons, 48, 48, 48, 96, true, 68, 68); } else { this.up = new EmulatorButton(dpad, 40, 40, 40, 0, true, (int)(60 * scale), (int)(60 * scale)); this.left = new EmulatorButton(dpad, 40, 40, 0, 40, true, (int)(60 * scale), (int)(60 * scale)); this.right = new EmulatorButton(dpad, 40, 40, 80, 40, true, (int)(60 * scale), (int)(60 * scale)); this.down = new EmulatorButton(dpad, 40, 40, 40, 80, true, (int)(60 * scale), (int)(60 * scale)); this.triangle = new EmulatorButton(buttons, 48, 48, 48, 0, true, (int)(68 * scale), (int)(68 * scale)); this.square = new EmulatorButton(buttons, 48, 48, 0, 48, true, (int)(68 * scale), (int)(68 * scale)); this.circle = new EmulatorButton(buttons, 48, 48, 96, 48, true, (int)(68 * scale), (int)(68 * scale)); this.cancel = new EmulatorButton(buttons, 48, 48, 48, 96, true, (int)(68 * scale), (int)(68 * scale)); } this.up._monitor = new up_monitor(el); this.left._monitor = new left_monitor(el); this.right._monitor = new right_monitor(el); this.down._monitor = new down_monitor(el); this.triangle._monitor = new triangle_monitor(el); this.square._monitor = new square_monitor(el); this.circle._monitor = new circle_monitor(el); this.cancel._monitor = new cancel_monitor(el); if (dpad != null) { dpad.Dispose(); dpad = null; } if (buttons != null) { buttons.Dispose(); buttons = null; } this.visible = true; this.SetLocation(0, 0); } public void SetLocation(int x, int y) { if (!visible) { return; } this.offsetX = x; this.offsetY = y; up.SetLocation((offsetX + up.GetWidth()) + offset, offsetY + (height - up.GetHeight() * 3) - offset); left.SetLocation((offsetX + 0) + offset, offsetY + (height - left.GetHeight() * 2) - offset); right.SetLocation((offsetX + right.GetWidth() * 2) + offset, offsetY + (height - right.GetHeight() * 2) - offset); down.SetLocation((offsetX + down.GetWidth()) + offset, offsetY + (height - down.GetHeight()) - offset); if (LSystem.screenRect.height >= LSystem.screenRect.width) { triangle.SetLocation(offsetX + (width - triangle.GetWidth() * 2) - offset, height - (triangle.GetHeight() * 4) - (offset * 2)); square.SetLocation(offsetX + (width - square.GetWidth()) - offset, height - (square.GetHeight() * 3) - (offset * 2)); circle.SetLocation(offsetX + (width - circle.GetWidth() * 3) - offset, height - (circle.GetHeight() * 3) - (offset * 2)); cancel.SetLocation(offsetX + (width - cancel.GetWidth() * 2) - offset, offsetY + height - (circle.GetHeight() * 2) - (offset * 2)); } else { triangle.SetLocation(offsetX + (width - triangle.GetWidth() * 2) - offset, height - (triangle.GetHeight() * 3) - offset); square.SetLocation(offsetX + (width - square.GetWidth()) - offset, height - (square.GetHeight() * 2) - offset); circle.SetLocation(offsetX + (width - circle.GetWidth() * 3) - offset, height - (circle.GetHeight() * 2) - offset); cancel.SetLocation(offsetX + (width - cancel.GetWidth() * 2) - offset, offsetY + height - (circle.GetHeight()) - offset); } } public bool IsClick() { if (up.IsClick()) { return true; } if (left.IsClick()) { return true; } if (down.IsClick()) { return true; } if (right.IsClick()) { return true; } if (triangle.IsClick()) { return true; } if (square.IsClick()) { return true; } if (circle.IsClick()) { return true; } if (cancel.IsClick()) { return true; } return false; } public void Hide() { HideLeft(); HideRight(); } public void Show() { ShowLeft(); ShowRight(); } public void HideLeft() { up.Disable(true); left.Disable(true); right.Disable(true); down.Disable(true); } public void ShowLeft() { up.Disable(false); left.Disable(false); right.Disable(false); down.Disable(false); } public void HideRight() { triangle.Disable(true); square.Disable(true); circle.Disable(true); cancel.Disable(true); } public void ShowRight() { triangle.Disable(false); square.Disable(false); circle.Disable(false); cancel.Disable(false); } public int GetX() { return offsetX; } public int GetY() { return offsetY; } public EmulatorButton[] GetEmulatorButtons() { return new EmulatorButton[] { up, left, right, down, triangle, square, circle, cancel }; } private float offsetTouchX,offsetTouchY,offsetMoveX,offsetMoveY; public void OnEmulatorButtonEvent(Microsoft.Xna.Framework.Input.Touch.TouchLocation touch, float touchX, float touchY) { if (!visible) { return; } switch (touch.State) { case Microsoft.Xna.Framework.Input.Touch.TouchLocationState.Pressed: offsetTouchX = touchX; offsetTouchY = touchY; Hit(touch.Id, touchX, touchY, false); break; case Microsoft.Xna.Framework.Input.Touch.TouchLocationState.Released: Unhit(touch.Id, touchX, touchY); break; case Microsoft.Xna.Framework.Input.Touch.TouchLocationState.Moved: offsetMoveX = touchX; offsetMoveY = touchY; if (MathUtils.Abs(offsetTouchX - offsetMoveX) > 5 || MathUtils.Abs(offsetTouchY - offsetMoveY) > 5) { Hit(touch.Id, touchX, touchY, true); } break; case Microsoft.Xna.Framework.Input.Touch.TouchLocationState.Invalid: Unhit(touch.Id, touchX, touchY); break; } } private SpriteBatch batch = new SpriteBatch(128); public void Draw(GLEx g) { if (!visible) { return; } batch.Begin(); batch.HalfAlpha(); up.Draw(batch); left.Draw(batch); right.Draw(batch); down.Draw(batch); triangle.Draw(batch); square.Draw(batch); circle.Draw(batch); cancel.Draw(batch); batch.ResetColor(); batch.End(); } public void Hit(int id, float x, float y, bool flag) { if (!visible) { return; } up.Hit(id, x, y, flag); left.Hit(id, x, y, flag); right.Hit(id, x, y, flag); down.Hit(id, x, y, flag); triangle.Hit(id, x, y, flag); square.Hit(id, x, y, flag); circle.Hit(id, x, y, flag); cancel.Hit(id, x, y, flag); } public void Unhit(int id, float x, float y) { if (!visible) { return; } up.Unhit(id, x, y); left.Unhit(id, x, y); right.Unhit(id, x, y); down.Unhit(id, x, y); triangle.Unhit(id, x, y); square.Unhit(id, x, y); circle.Unhit(id, x, y); cancel.Unhit(id, x, y); } public bool IsVisible() { return visible; } public void SetVisible(bool visible_0) { if (!visible_0) { Release(); } this.visible = visible_0; } public EmulatorListener GetEmulatorListener() { return emulatorListener; } public void SetEmulatorListener(EmulatorListener emulator) { this.emulatorListener = emulator; } public EmulatorButton GetUp() { return up; } public EmulatorButton GetLeft() { return left; } public EmulatorButton GetRight() { return right; } public EmulatorButton GetDown() { return down; } public EmulatorButton GetTriangle() { return triangle; } public EmulatorButton GetSquare() { return square; } public EmulatorButton GetCircle() { return circle; } public EmulatorButton GetCancel() { return cancel; } public void Release() { up.Unhit(); left.Unhit(); right.Unhit(); down.Unhit(); triangle.Unhit(); square.Unhit(); circle.Unhit(); cancel.Unhit(); if (emulatorListener != null) { emulatorListener.UnUpClick(); emulatorListener.UnLeftClick(); emulatorListener.UnRightClick(); emulatorListener.UnDownClick(); emulatorListener.UnTriangleClick(); emulatorListener.UnSquareClick(); emulatorListener.UnCircleClick(); emulatorListener.UnCancelClick(); } } public void Dispose() { if (pack != null) { pack.Dispose(); pack = null; } if (batch != null) { batch.Dispose(); batch = null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Localization; using OrchardCore.Data; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Environment.Shell; using OrchardCore.Environment.Shell.Models; using OrchardCore.Modules; using OrchardCore.Navigation; using OrchardCore.Recipes.Services; using OrchardCore.Routing; using OrchardCore.Settings; using OrchardCore.Tenants.ViewModels; namespace OrchardCore.Tenants.Controllers { public class AdminController : Controller { private readonly IShellHost _shellHost; private readonly IShellSettingsManager _shellSettingsManager; private readonly IEnumerable<DatabaseProvider> _databaseProviders; private readonly IAuthorizationService _authorizationService; private readonly ShellSettings _currentShellSettings; private readonly IEnumerable<IRecipeHarvester> _recipeHarvesters; private readonly IDataProtectionProvider _dataProtectorProvider; private readonly IClock _clock; private readonly INotifier _notifier; private readonly ISiteService _siteService; private readonly dynamic New; private readonly IStringLocalizer S; private readonly IHtmlLocalizer H; public AdminController( IShellHost shellHost, IShellSettingsManager shellSettingsManager, IEnumerable<DatabaseProvider> databaseProviders, IAuthorizationService authorizationService, ShellSettings currentShellSettings, IEnumerable<IRecipeHarvester> recipeHarvesters, IDataProtectionProvider dataProtectorProvider, IClock clock, INotifier notifier, ISiteService siteService, IShapeFactory shapeFactory, IStringLocalizer<AdminController> stringLocalizer, IHtmlLocalizer<AdminController> htmlLocalizer) { _shellHost = shellHost; _authorizationService = authorizationService; _shellSettingsManager = shellSettingsManager; _databaseProviders = databaseProviders; _currentShellSettings = currentShellSettings; _dataProtectorProvider = dataProtectorProvider; _recipeHarvesters = recipeHarvesters; _clock = clock; _notifier = notifier; _siteService = siteService; New = shapeFactory; S = stringLocalizer; H = htmlLocalizer; } public async Task<IActionResult> Index(TenantIndexOptions options, PagerParameters pagerParameters) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var allSettings = _shellHost.GetAllSettings().OrderBy(s => s.Name); var dataProtector = _dataProtectorProvider.CreateProtector("Tokens").ToTimeLimitedDataProtector(); var siteSettings = await _siteService.GetSiteSettingsAsync(); var pager = new Pager(pagerParameters, siteSettings.PageSize); // default options if (options == null) { options = new TenantIndexOptions(); } var entries = allSettings.Select(x => { var entry = new ShellSettingsEntry { Description = x["Description"], Name = x.Name, ShellSettings = x, IsDefaultTenant = string.Equals(x.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase) }; if (x.State == TenantState.Uninitialized && !string.IsNullOrEmpty(x["Secret"])) { entry.Token = dataProtector.Protect(x["Secret"], _clock.UtcNow.Add(new TimeSpan(24, 0, 0))); } return entry; }).ToList(); if (!string.IsNullOrWhiteSpace(options.Search)) { entries = entries.Where(t => t.Name.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1 || (t.ShellSettings != null && ((t.ShellSettings.RequestUrlHost != null && t.ShellSettings.RequestUrlHost.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1) || (t.ShellSettings.RequestUrlPrefix != null && t.ShellSettings.RequestUrlPrefix.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1)))).ToList(); } switch (options.Filter) { case TenantsFilter.Disabled: entries = entries.Where(t => t.ShellSettings.State == TenantState.Disabled).ToList(); break; case TenantsFilter.Running: entries = entries.Where(t => t.ShellSettings.State == TenantState.Running).ToList(); break; case TenantsFilter.Uninitialized: entries = entries.Where(t => t.ShellSettings.State == TenantState.Uninitialized).ToList(); break; } switch (options.OrderBy) { case TenantsOrder.Name: entries = entries.OrderBy(t => t.Name).ToList(); break; case TenantsOrder.State: entries = entries.OrderBy(t => t.ShellSettings?.State).ToList(); break; default: entries = entries.OrderByDescending(t => t.Name).ToList(); break; } var count = entries.Count(); var results = entries .Skip(pager.GetStartIndex()) .Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links var routeData = new RouteData(); routeData.Values.Add("Options.Filter", options.Filter); routeData.Values.Add("Options.Search", options.Search); routeData.Values.Add("Options.OrderBy", options.OrderBy); var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData); var model = new AdminIndexViewModel { ShellSettingsEntries = results, Options = options, Pager = pagerShape }; // We populate the SelectLists model.Options.TenantsStates = new List<SelectListItem>() { new SelectListItem() { Text = S["All states"], Value = nameof(TenantsFilter.All) }, new SelectListItem() { Text = S["Running"], Value = nameof(TenantsFilter.Running) }, new SelectListItem() { Text = S["Disabled"], Value = nameof(TenantsFilter.Disabled) }, new SelectListItem() { Text = S["Uninitialized"], Value = nameof(TenantsFilter.Uninitialized) } }; model.Options.TenantsSorts = new List<SelectListItem>() { new SelectListItem() { Text = S["Name"], Value = nameof(TenantsOrder.Name) }, new SelectListItem() { Text = S["State"], Value = nameof(TenantsOrder.State) } }; model.Options.TenantsBulkAction = new List<SelectListItem>() { new SelectListItem() { Text = S["Disable"], Value = nameof(TenantsBulkAction.Disable) }, new SelectListItem() { Text = S["Enable"], Value = nameof(TenantsBulkAction.Enable) } }; return View(model); } [HttpPost, ActionName("Index")] [FormValueRequired("submit.Filter")] public ActionResult IndexFilterPOST(AdminIndexViewModel model) { return RedirectToAction("Index", new RouteValueDictionary { { "Options.Filter", model.Options.Filter }, { "Options.OrderBy", model.Options.OrderBy }, { "Options.Search", model.Options.Search }, { "Options.TenantsStates", model.Options.TenantsStates } }); } [HttpPost] [FormValueRequired("submit.BulkAction")] public async Task<IActionResult> Index(BulkActionViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var allSettings = _shellHost.GetAllSettings(); foreach (var tenantName in model.TenantNames ?? Enumerable.Empty<string>()) { var shellSettings = allSettings .Where(x => string.Equals(x.Name, tenantName, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { break; } switch (model.BulkAction.ToString()) { case "Disable": if (string.Equals(shellSettings.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase)) { _notifier.Warning(H["You cannot disable the default tenant."]); } else if (shellSettings.State != TenantState.Running) { _notifier.Warning(H["The tenant '{0}' is already disabled.", shellSettings.Name]); } else { shellSettings.State = TenantState.Disabled; await _shellHost.UpdateShellSettingsAsync(shellSettings); } break; case "Enable": if (shellSettings.State != TenantState.Disabled) { _notifier.Warning(H["The tenant '{0}' is already enabled.", shellSettings.Name]); } else { shellSettings.State = TenantState.Running; await _shellHost.UpdateShellSettingsAsync(shellSettings); } break; default: break; } } return RedirectToAction(nameof(Index)); } public async Task<IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); // Creates a default shell settings based on the configuration. var shellSettings = _shellSettingsManager.CreateDefaultSettings(); var model = new EditTenantViewModel { Recipes = recipes, RequestUrlHost = shellSettings.RequestUrlHost, RequestUrlPrefix = shellSettings.RequestUrlPrefix, DatabaseProvider = shellSettings["DatabaseProvider"], TablePrefix = shellSettings["TablePrefix"], ConnectionString = shellSettings["ConnectionString"], RecipeName = shellSettings["RecipeName"] }; model.Recipes = recipes; return View(model); } [HttpPost] public async Task<IActionResult> Create(EditTenantViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } if (ModelState.IsValid) { ValidateViewModel(model, true); } if (ModelState.IsValid) { // Creates a default shell settings based on the configuration. var shellSettings = _shellSettingsManager.CreateDefaultSettings(); shellSettings.Name = model.Name; shellSettings.RequestUrlHost = model.RequestUrlHost; shellSettings.RequestUrlPrefix = model.RequestUrlPrefix; shellSettings.State = TenantState.Uninitialized; shellSettings["Description"] = model.Description; shellSettings["ConnectionString"] = model.ConnectionString; shellSettings["TablePrefix"] = model.TablePrefix; shellSettings["DatabaseProvider"] = model.DatabaseProvider; shellSettings["Secret"] = Guid.NewGuid().ToString(); shellSettings["RecipeName"] = model.RecipeName; await _shellHost.UpdateShellSettingsAsync(shellSettings); return RedirectToAction(nameof(Index)); } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); model.Recipes = recipes; // If we got this far, something failed, redisplay form return View(model); } public async Task<IActionResult> Edit(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var shellSettings = _shellHost.GetAllSettings() .Where(x => string.Equals(x.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } var model = new EditTenantViewModel { Description = shellSettings["Description"], Name = shellSettings.Name, RequestUrlHost = shellSettings.RequestUrlHost, RequestUrlPrefix = shellSettings.RequestUrlPrefix, }; // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); model.Recipes = recipes; model.DatabaseProvider = shellSettings["DatabaseProvider"]; model.TablePrefix = shellSettings["TablePrefix"]; model.ConnectionString = shellSettings["ConnectionString"]; model.RecipeName = shellSettings["RecipeName"]; model.CanSetDatabasePresets = true; } return View(model); } [HttpPost] public async Task<IActionResult> Edit(EditTenantViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } if (ModelState.IsValid) { ValidateViewModel(model, false); } var shellSettings = _shellHost.GetAllSettings() .Where(x => string.Equals(x.Name, model.Name, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } if (ModelState.IsValid) { shellSettings["Description"] = model.Description; shellSettings.RequestUrlPrefix = model.RequestUrlPrefix; shellSettings.RequestUrlHost = model.RequestUrlHost; // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { shellSettings["DatabaseProvider"] = model.DatabaseProvider; shellSettings["TablePrefix"] = model.TablePrefix; shellSettings["ConnectionString"] = model.ConnectionString; shellSettings["RecipeName"] = model.RecipeName; shellSettings["Secret"] = Guid.NewGuid().ToString(); } await _shellHost.UpdateShellSettingsAsync(shellSettings); return RedirectToAction(nameof(Index)); } // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { model.DatabaseProvider = shellSettings["DatabaseProvider"]; model.TablePrefix = shellSettings["TablePrefix"]; model.ConnectionString = shellSettings["ConnectionString"]; model.RecipeName = shellSettings["RecipeName"]; model.CanSetDatabasePresets = true; } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); model.Recipes = recipes; // If we got this far, something failed, redisplay form return View(model); } [HttpPost] public async Task<IActionResult> Disable(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var shellSettings = _shellHost.GetAllSettings() .Where(s => string.Equals(s.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } if (string.Equals(shellSettings.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase)) { _notifier.Error(H["You cannot disable the default tenant."]); return RedirectToAction(nameof(Index)); } if (shellSettings.State != TenantState.Running) { _notifier.Error(H["You can only disable an Enabled tenant."]); return RedirectToAction(nameof(Index)); } shellSettings.State = TenantState.Disabled; await _shellHost.UpdateShellSettingsAsync(shellSettings); return RedirectToAction(nameof(Index)); } [HttpPost] public async Task<IActionResult> Enable(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var shellSettings = _shellHost.GetAllSettings() .Where(x => string.Equals(x.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } if (shellSettings.State != TenantState.Disabled) { _notifier.Error(H["You can only enable a Disabled tenant."]); } shellSettings.State = TenantState.Running; await _shellHost.UpdateShellSettingsAsync(shellSettings); return RedirectToAction(nameof(Index)); } [HttpPost] public async Task<IActionResult> Reload(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var shellSettings = _shellHost.GetAllSettings() .OrderBy(x => x.Name) .Where(x => string.Equals(x.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } // Generating routes can fail while the tenant is recycled as routes can use services. // It could be fixed by waiting for the next request or the end of the current one // to actually release the tenant. Right now we render the url before recycling the tenant. var redirectUrl = Url.Action(nameof(Index)); await _shellHost.ReloadShellContextAsync(shellSettings); return Redirect(redirectUrl); } private void ValidateViewModel(EditTenantViewModel model, bool newTenant) { var selectedProvider = _databaseProviders.FirstOrDefault(x => x.Value == model.DatabaseProvider); if (selectedProvider != null && selectedProvider.HasConnectionString && String.IsNullOrWhiteSpace(model.ConnectionString)) { ModelState.AddModelError(nameof(EditTenantViewModel.ConnectionString), S["The connection string is mandatory for this provider."]); } if (string.IsNullOrWhiteSpace(model.Name)) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["The tenant name is mandatory."]); } var allSettings = _shellHost.GetAllSettings(); if (newTenant && allSettings.Any(tenant => string.Equals(tenant.Name, model.Name, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["A tenant with the same name already exists.", model.Name]); } if (!string.IsNullOrEmpty(model.Name) && !Regex.IsMatch(model.Name, @"^\w+$")) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["Invalid tenant name. Must contain characters only and no spaces."]); } if (!IsDefaultShell() && string.IsNullOrWhiteSpace(model.RequestUrlHost) && string.IsNullOrWhiteSpace(model.RequestUrlPrefix)) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["Host and url prefix can not be empty at the same time."]); } var allOtherShells = allSettings.Where(tenant => !string.Equals(tenant.Name, model.Name, StringComparison.OrdinalIgnoreCase)); if (allOtherShells.Any(tenant => string.Equals(tenant.RequestUrlPrefix, model.RequestUrlPrefix?.Trim(), StringComparison.OrdinalIgnoreCase) && string.Equals(tenant.RequestUrlHost, model.RequestUrlHost, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["A tenant with the same host and prefix already exists.", model.Name]); } if (!string.IsNullOrWhiteSpace(model.RequestUrlPrefix)) { if (model.RequestUrlPrefix.Contains('/')) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["The url prefix can not contain more than one segment."]); } } } private bool IsDefaultShell() { return string.Equals(_currentShellSettings.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase); } } }
//---------------------------------------------------------------- // <copyright company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //---------------------------------------------------------------- namespace System.Activities.Presentation.View { using System.Runtime; using System.Windows; using System.Windows.Controls; using System.Windows.Input; internal class ScrollViewerPanner { private ScrollViewer scrollViewer; private Point panningStartPosition; private PanState currentPanState; private bool inPanMode; private MouseButton draggingMouseButton; public ScrollViewerPanner(ScrollViewer scrollViewer) { Fx.Assert(scrollViewer != null, "ScrollViewer should never be null"); this.ScrollViewer = scrollViewer; } internal enum PanState { Normal, // Normal editing mode ReadyToPan, Panning, } public ScrollViewer ScrollViewer { get { return this.scrollViewer; } set { if (value != this.scrollViewer) { if (this.scrollViewer != null) { this.UnregisterEvents(); } this.scrollViewer = value; if (this.scrollViewer != null) { this.RegisterEvents(); } } } } public bool InPanMode { get { return this.inPanMode; } set { if (this.inPanMode != value) { this.inPanMode = value; if (this.inPanMode) { this.CurrentPanState = PanState.ReadyToPan; } else { this.CurrentPanState = PanState.Normal; } } } } public Cursor Hand { get; set; } public Cursor DraggingHand { get; set; } internal PanState CurrentPanState { get { return this.currentPanState; } set { if (this.currentPanState != value) { this.currentPanState = value; switch (this.currentPanState) { case PanState.ReadyToPan: this.scrollViewer.Cursor = this.Hand; break; case PanState.Panning: this.scrollViewer.Cursor = this.DraggingHand; break; default: this.scrollViewer.Cursor = null; break; } this.UpdateForceCursorProperty(); } } } internal bool IsInScrollableArea(Point mousePosition) { return mousePosition.X < this.scrollViewer.ViewportWidth && mousePosition.Y < this.scrollViewer.ViewportHeight; } internal void OnScrollViewerMouseDown(object sender, MouseButtonEventArgs e) { switch (this.CurrentPanState) { case PanState.Normal: if (e.ChangedButton == MouseButton.Middle) { this.StartPanningIfNecessary(e); } break; case PanState.ReadyToPan: switch (e.ChangedButton) { case MouseButton.Left: this.StartPanningIfNecessary(e); break; case MouseButton.Middle: this.StartPanningIfNecessary(e); break; case MouseButton.Right: e.Handled = true; break; } break; case PanState.Panning: e.Handled = true; break; default: break; } } internal void OnLostMouseCapture(object sender, MouseEventArgs e) { this.StopPanning(); } internal void OnScrollViewerMouseMove(object sender, MouseEventArgs e) { switch (this.CurrentPanState) { case PanState.Panning: Point currentPosition = Mouse.GetPosition(this.scrollViewer); Vector offset = Point.Subtract(currentPosition, this.panningStartPosition); this.panningStartPosition = currentPosition; this.scrollViewer.ScrollToHorizontalOffset(this.scrollViewer.HorizontalOffset - offset.X); this.scrollViewer.ScrollToVerticalOffset(this.scrollViewer.VerticalOffset - offset.Y); e.Handled = true; break; case PanState.ReadyToPan: this.UpdateForceCursorProperty(); break; default: break; } } internal void OnScrollViewerMouseUp(object sender, MouseButtonEventArgs e) { switch (this.CurrentPanState) { case PanState.ReadyToPan: this.StopPanningIfNecessary(e); // When the mouse is captured by other windows/views, that // window/view needs this mouse-up message to release // the capture. if (!this.IsMouseCapturedByOthers()) { e.Handled = true; } break; case PanState.Panning: this.StopPanningIfNecessary(e); e.Handled = true; break; default: break; } } internal void OnScrollViewerKeyDown(object sender, KeyEventArgs e) { switch (this.CurrentPanState) { // Don't change to ReadyToPan mode if the space is a // repeated input, because repeated-key input may come // from activity element on the scroll view. case PanState.Normal: if (e.Key == Key.Space && !e.IsRepeat && this.AllowSwitchToPanning()) { this.CurrentPanState = PanState.ReadyToPan; } break; default: break; } } internal void OnScrollViewerKeyUp(object sender, KeyEventArgs e) { switch (this.CurrentPanState) { case PanState.ReadyToPan: if (e.Key == Key.Space && !this.InPanMode) { this.CurrentPanState = PanState.Normal; } break; default: break; } } private void StartPanningIfNecessary(MouseButtonEventArgs e) { if (DesignerView.IsMouseInViewport(e, this.scrollViewer)) { this.draggingMouseButton = e.ChangedButton; this.CurrentPanState = PanState.Panning; this.scrollViewer.Focus(); this.panningStartPosition = Mouse.GetPosition(this.scrollViewer); Mouse.Capture(this.scrollViewer); e.Handled = true; } } private void StopPanningIfNecessary(MouseButtonEventArgs e) { if (e.ChangedButton == this.draggingMouseButton && object.Equals(this.scrollViewer, Mouse.Captured)) { // Trigers OnLostMouseCapture this.scrollViewer.ReleaseMouseCapture(); } } private void StopPanning() { // stop panning if (this.InPanMode || (Keyboard.IsKeyDown(Key.Space) && this.CurrentPanState == PanState.Panning)) { this.CurrentPanState = PanState.ReadyToPan; } else { this.CurrentPanState = PanState.Normal; } } private void UpdateForceCursorProperty() { Point pt = Mouse.GetPosition(this.ScrollViewer); if (this.IsInScrollableArea(pt)) { this.scrollViewer.ForceCursor = true; } else { this.scrollViewer.ForceCursor = false; } } // Mouse is sometimes captured by ScrollViewer's children, like // RepeatButton in Scroll Bar. private bool IsMouseCapturedByOthers() { return (Mouse.Captured != null) && !object.Equals(Mouse.Captured, this.ScrollViewer); } private bool AllowSwitchToPanning() { return Mouse.LeftButton == MouseButtonState.Released && Mouse.RightButton == MouseButtonState.Released; } private void RegisterEvents() { this.scrollViewer.PreviewMouseDown += new MouseButtonEventHandler(this.OnScrollViewerMouseDown); this.scrollViewer.PreviewMouseMove += new MouseEventHandler(this.OnScrollViewerMouseMove); this.scrollViewer.PreviewMouseUp += new MouseButtonEventHandler(this.OnScrollViewerMouseUp); this.scrollViewer.LostMouseCapture += new MouseEventHandler(this.OnLostMouseCapture); this.scrollViewer.KeyDown += new KeyEventHandler(this.OnScrollViewerKeyDown); this.scrollViewer.KeyUp += new KeyEventHandler(this.OnScrollViewerKeyUp); } private void UnregisterEvents() { this.scrollViewer.PreviewMouseDown -= new MouseButtonEventHandler(this.OnScrollViewerMouseDown); this.scrollViewer.PreviewMouseMove -= new MouseEventHandler(this.OnScrollViewerMouseMove); this.scrollViewer.PreviewMouseUp -= new MouseButtonEventHandler(this.OnScrollViewerMouseUp); this.scrollViewer.LostMouseCapture -= new MouseEventHandler(this.OnLostMouseCapture); this.scrollViewer.KeyDown -= new KeyEventHandler(this.OnScrollViewerKeyDown); this.scrollViewer.KeyUp -= new KeyEventHandler(this.OnScrollViewerKeyUp); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace System.IO.Tests { public partial class TextReaderTests { protected (char[] chArr, CharArrayTextReader textReader) GetCharArray() { CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.CharData); return (TestDataProvider.CharData, tr); } [Fact] public void EndOfStream() { using (CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.SmallData)) { var result = tr.ReadToEnd(); Assert.Equal("HELLO", result); Assert.True(tr.EndOfStream, "End of TextReader was not true after ReadToEnd"); } } [Fact] public void NotEndOfStream() { using (CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.SmallData)) { char[] charBuff = new char[3]; var result = tr.Read(charBuff, 0, 3); Assert.Equal(3, result); Assert.Equal("HEL", new string(charBuff)); Assert.False(tr.EndOfStream, "End of TextReader was true after ReadToEnd"); } } [Fact] public async Task ReadToEndAsync() { using (CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.LargeData)) { var result = await tr.ReadToEndAsync(); Assert.Equal(5000, result.Length); } } [Fact] public void TestRead() { (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray(); using (CharArrayTextReader tr = baseInfo.textReader) { for (int count = 0; count < baseInfo.chArr.Length; ++count) { int tmp = tr.Read(); Assert.Equal((int)baseInfo.chArr[count], tmp); } } } [Fact] public void ArgumentNullOnNullArray() { (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray(); using (CharArrayTextReader tr = baseInfo.textReader) { Assert.Throws<ArgumentNullException>(() => tr.Read(null, 0, 0)); } } [Fact] public void ArgumentOutOfRangeOnInvalidOffset() { using (CharArrayTextReader tr = GetCharArray().textReader) { Assert.Throws<ArgumentOutOfRangeException>(() => tr.Read(new char[0], -1, 0)); } } [Fact] public void ArgumentOutOfRangeOnNegativCount() { using (CharArrayTextReader tr = GetCharArray().textReader) { AssertExtensions.Throws<ArgumentException>(null, () => tr.Read(new char[0], 0, 1)); } } [Fact] public void ArgumentExceptionOffsetAndCount() { using (CharArrayTextReader tr = GetCharArray().textReader) { AssertExtensions.Throws<ArgumentException>(null, () => tr.Read(new char[0], 2, 0)); } } [Fact] public void EmptyInput() { using (CharArrayTextReader tr = new CharArrayTextReader(new char[] { })) { char[] buffer = new char[10]; int read = tr.Read(buffer, 0, 1); Assert.Equal(0, read); } } [Fact] public void ReadCharArr() { (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray(); using (CharArrayTextReader tr = baseInfo.textReader) { char[] chArr = new char[baseInfo.chArr.Length]; var read = tr.Read(chArr, 0, chArr.Length); Assert.Equal(chArr.Length, read); for (int count = 0; count < baseInfo.chArr.Length; ++count) { Assert.Equal(baseInfo.chArr[count], chArr[count]); } } } [Fact] public void ReadBlockCharArr() { (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray(); using (CharArrayTextReader tr = baseInfo.textReader) { char[] chArr = new char[baseInfo.chArr.Length]; var read = tr.ReadBlock(chArr, 0, chArr.Length); Assert.Equal(chArr.Length, read); for (int count = 0; count < baseInfo.chArr.Length; ++count) { Assert.Equal(baseInfo.chArr[count], chArr[count]); } } } [Fact] public async void ReadBlockAsyncCharArr() { (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray(); using (CharArrayTextReader tr = baseInfo.textReader) { char[] chArr = new char[baseInfo.chArr.Length]; var read = await tr.ReadBlockAsync(chArr, 0, chArr.Length); Assert.Equal(chArr.Length, read); for (int count = 0; count < baseInfo.chArr.Length; ++count) { Assert.Equal(baseInfo.chArr[count], chArr[count]); } } } [Fact] public async Task ReadAsync() { (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray(); using (CharArrayTextReader tr = baseInfo.textReader) { char[] chArr = new char[baseInfo.chArr.Length]; var read = await tr.ReadAsync(chArr, 4, 3); Assert.Equal(read, 3); for (int count = 0; count < 3; ++count) { Assert.Equal(baseInfo.chArr[count], chArr[count + 4]); } } } [Fact] public void ReadLines() { (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray(); using (CharArrayTextReader tr = baseInfo.textReader) { string valueString = new string(baseInfo.chArr); var data = tr.ReadLine(); Assert.Equal(valueString.Substring(0, valueString.IndexOf('\r')), data); data = tr.ReadLine(); Assert.Equal(valueString.Substring(valueString.IndexOf('\r') + 1, 3), data); data = tr.ReadLine(); Assert.Equal(valueString.Substring(valueString.IndexOf('\n') + 1, 2), data); data = tr.ReadLine(); Assert.Equal((valueString.Substring(valueString.LastIndexOf('\n') + 1)), data); } } [Fact] public void ReadLines2() { (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray(); using (CharArrayTextReader tr = baseInfo.textReader) { string valueString = new string(baseInfo.chArr); char[] temp = new char[10]; tr.Read(temp, 0, 1); var data = tr.ReadLine(); Assert.Equal(valueString.Substring(1, valueString.IndexOf('\r') - 1), data); } } [Fact] public async Task ReadLineAsyncContinuousNewLinesAndTabs() { char[] newLineTabData = new char[] { '\n', '\n', '\r', '\r', '\n' }; using (CharArrayTextReader tr = new CharArrayTextReader(newLineTabData)) { for (int count = 0; count < 4; ++count) { var data = await tr.ReadLineAsync(); Assert.Equal(string.Empty, data); } var eol = await tr.ReadLineAsync(); Assert.Null(eol); } } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using IdentityServerWithEfCoreDemo.EntityFrameworkCore; namespace IdentityServerWithEfCoreDemo.Migrations { [DbContext(typeof(IdentityServerWithEfCoreDemoDbContext))] [Migration("20170621153937_Added_Description_And_IsActive_To_Role")] partial class Added_Description_And_IsActive_To_Role { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.2") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("CustomData") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("Exception") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("MethodName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Parameters") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("IsGranted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .HasColumnType("nvarchar(450)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<long?>("UserLinkId") .HasColumnType("bigint"); b.Property<string>("UserName") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<byte>("Result") .HasColumnType("tinyint"); b.Property<string>("TenancyName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("UserNameOrEmailAddress") .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsAbandoned") .HasColumnType("bit"); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .HasColumnType("tinyint"); b.Property<short>("TryCount") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Icon") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsDisabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Key") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Source") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<string>("TenantIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("UserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<int>("State") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("TenantNotificationId") .HasColumnType("uniqueidentifier"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("Code") .IsRequired() .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<long?>("ParentId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("IdentityServerWithEfCoreDemo.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("IdentityServerWithEfCoreDemo.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("AuthenticationSource") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<bool>("IsLockoutEnabled") .HasColumnType("bit"); b.Property<bool>("IsPhoneNumberConfirmed") .HasColumnType("bit"); b.Property<bool>("IsTwoFactorEnabled") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LockoutEndDateUtc") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<string>("Surname") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("IdentityServerWithEfCoreDemo.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConnectionString") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<int?>("EditionId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId") .HasColumnType("int"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("TenantId") .HasColumnType("int"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId") .HasColumnType("int"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("IdentityServerWithEfCoreDemo.Authorization.Roles.Role", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("IdentityServerWithEfCoreDemo.Authorization.Users.User", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("IdentityServerWithEfCoreDemo.MultiTenancy.Tenant", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Data.Entity.ModelConfiguration.Conventions; using Abp.Application.Editions; using Abp.Application.Features; using Abp.Auditing; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.BackgroundJobs; using Abp.Domain.Entities; using Abp.EntityFramework.Extensions; using Abp.MultiTenancy; using Abp.Notifications; namespace Abp.Zero.EntityFramework { /// <summary> /// Base DbContext for ABP zero. /// Derive your DbContext from this class to have base entities. /// </summary> public abstract class AbpZeroDbContext<TTenant, TRole, TUser> : AbpZeroCommonDbContext<TRole, TUser> where TTenant : AbpTenant<TUser> where TRole : AbpRole<TUser> where TUser : AbpUser<TUser> { /// <summary> /// Tenants /// </summary> public virtual IDbSet<TTenant> Tenants { get; set; } /// <summary> /// Editions. /// </summary> public virtual IDbSet<Edition> Editions { get; set; } /// <summary> /// FeatureSettings. /// </summary> public virtual IDbSet<FeatureSetting> FeatureSettings { get; set; } /// <summary> /// TenantFeatureSetting. /// </summary> public virtual IDbSet<TenantFeatureSetting> TenantFeatureSettings { get; set; } /// <summary> /// EditionFeatureSettings. /// </summary> public virtual IDbSet<EditionFeatureSetting> EditionFeatureSettings { get; set; } /// <summary> /// Background jobs. /// </summary> public virtual IDbSet<BackgroundJobInfo> BackgroundJobs { get; set; } /// <summary> /// User accounts /// </summary> public virtual IDbSet<UserAccount> UserAccounts { get; set; } protected AbpZeroDbContext() { } protected AbpZeroDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } protected AbpZeroDbContext(DbCompiledModel model) : base(model) { } protected AbpZeroDbContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } protected AbpZeroDbContext(string nameOrConnectionString, DbCompiledModel model) : base(nameOrConnectionString, model) { } protected AbpZeroDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { } protected AbpZeroDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); #region BackgroundJobInfo.IX_IsAbandoned_NextTryTime modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.IsAbandoned) .CreateIndex("IX_IsAbandoned_NextTryTime", 1); modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.NextTryTime) .CreateIndex("IX_IsAbandoned_NextTryTime", 2); modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.Priority) .CreateIndex("IX_Priority_TryCount_NextTryTime", 1); modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.TryCount) .CreateIndex("IX_Priority_TryCount_NextTryTime", 2); modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.NextTryTime) .CreateIndex("IX_Priority_TryCount_NextTryTime", 3); #endregion #region NotificationSubscriptionInfo.IX_NotificationName_EntityTypeName_EntityId_UserId modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.NotificationName) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 1); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.EntityTypeName) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 2); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.EntityId) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 3); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.UserId) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 4); #endregion #region UserNotificationInfo.IX_UserId_State_CreationTime modelBuilder.Entity<UserNotificationInfo>() .Property(un => un.UserId) .CreateIndex("IX_UserId_State_CreationTime", 1); modelBuilder.Entity<UserNotificationInfo>() .Property(un => un.State) .CreateIndex("IX_UserId_State_CreationTime", 2); modelBuilder.Entity<UserNotificationInfo>() .Property(un => un.CreationTime) .CreateIndex("IX_UserId_State_CreationTime", 3); #endregion #region UserLoginAttempt.IX_TenancyName_UserNameOrEmailAddress_Result modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.TenancyName) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 1); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.UserNameOrEmailAddress) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 2); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.Result) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 3); #endregion #region UserLoginAttempt.IX_UserId_TenantId modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.UserId) .CreateIndex("IX_UserId_TenantId", 1); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.TenantId) .CreateIndex("IX_UserId_TenantId", 2); #endregion #region AuditLog.Set_MaxLengths modelBuilder.Entity<AuditLog>() .Property(e => e.ServiceName) .HasMaxLength(AuditLog.MaxServiceNameLength); modelBuilder.Entity<AuditLog>() .Property(e => e.MethodName) .HasMaxLength(AuditLog.MaxMethodNameLength); modelBuilder.Entity<AuditLog>() .Property(e => e.Parameters) .HasMaxLength(AuditLog.MaxParametersLength); modelBuilder.Entity<AuditLog>() .Property(e => e.ClientIpAddress) .HasMaxLength(AuditLog.MaxClientIpAddressLength); modelBuilder.Entity<AuditLog>() .Property(e => e.ClientName) .HasMaxLength(AuditLog.MaxClientNameLength); modelBuilder.Entity<AuditLog>() .Property(e => e.BrowserInfo) .HasMaxLength(AuditLog.MaxBrowserInfoLength); modelBuilder.Entity<AuditLog>() .Property(e => e.Exception) .HasMaxLength(AuditLog.MaxExceptionLength); modelBuilder.Entity<AuditLog>() .Property(e => e.CustomData) .HasMaxLength(AuditLog.MaxCustomDataLength); #endregion #region Common Indexes modelBuilder.Conventions.AddAfter<IndexAttributeConvention>(new IndexingPropertyConvention<ISoftDelete, bool>(m => m.IsDeleted)); modelBuilder.Conventions.AddAfter<IndexAttributeConvention>(new IndexingPropertyConvention<IMayHaveTenant, int?>(m => m.TenantId)); modelBuilder.Conventions.AddAfter<IndexAttributeConvention>(new IndexingPropertyConvention<IMustHaveTenant, int>(m => m.TenantId)); #endregion } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private SyntaxToken _methodName; public static async Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult); return await codeGenerator.GenerateAsync(cancellationToken).ConfigureAwait(false); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult); } return Contract.FailWithReturn<CSharpCodeGenerator>("Unknown selection"); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) : base(insertionPoint, selectionResult, analyzerResult) { Contract.ThrowIfFalse(this.SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(this.MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)this.SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = this.InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: SpecializedCollections.EmptyList<AttributeData>(), accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: this.AnalyzerResult.ReturnType, explicitInterfaceSymbol: null, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(cancellationToken), parameters: CreateMethodParameters(), statements: result.Data); return result.With( this.MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = this.GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( this.AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<IEnumerable<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = this.GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(this.CallSiteAnnotation, cancellationToken).ConfigureAwait(false); return SpecializedCollections.SingletonEnumerable(statement); } // regular case var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = SpecializedCollections.EmptyEnumerable<StatementSyntax>(); statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(statements, cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements, cancellationToken); return statements; } private bool IsExpressionBodiedMember(SyntaxNode node) { return node is MemberDeclarationSyntax && ((MemberDeclarationSyntax)node).GetExpressionBody() != null; } private SimpleNameSyntax CreateMethodNameForInvocation() { return this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in this.AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(this.SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = this.CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = this.CSharpSelectionResult.ShouldPutAsyncModifier(); return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: !this.AnalyzerResult.UseInstanceMember); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<List<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToList<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = this.CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } var block = statements.Single() as BlockSyntax; if (block != null) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private IEnumerable<StatementSyntax> CleanupCode(IEnumerable<StatementSyntax> statements) { var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); statements = postProcessor.RemoveRedundantBlock(statements); statements = postProcessor.RemoveDeclarationAssignmentPattern(statements); statements = postProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { var returnStatement = statements.Single() as ReturnStatementSyntax; if (returnStatement != null && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { var declStatement = statement as LocalDeclarationStatementSyntax; if (declStatement == null) { // found one return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private IEnumerable<StatementSyntax> MoveDeclarationOutFromMethodDefinition( IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken) { var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( this.AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); foreach (var statement in statements) { var declarationStatement = statement as LocalDeclarationStatementSyntax; if (declarationStatement == null) { // if given statement is not decl statement, do nothing. yield return statement; continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { SyntaxToken identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token yield return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { yield return SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, declarationStatement.RefKeyword, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); } // return any expression statement if there was any foreach (var expressionStatement in expressionStatements) { yield return expressionStatement; } } } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private static SyntaxToken GetIdentifierTokenAndTrivia(SyntaxToken identifier, TypeSyntax typeSyntax) { if (typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); var identifierTrailingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } if (typeSyntax.HasTrailingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetTrailingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifierTrailingTrivia = identifierTrailingTrivia.AddRange(identifier.TrailingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia) .WithTrailingTrivia(identifierTrailingTrivia); } return identifier; } private IEnumerable<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = this.GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) { return SyntaxFactory.Identifier(name); } protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); foreach (var argument in this.AnalyzerResult.MethodParameters) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default(SyntaxToken) : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = this.CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); } protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, CancellationToken cancellationToken, ExpressionSyntax initialValue = null) { var type = variable.GetVariableType(this.SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<MethodDeclarationSyntax>(this.MethodDefinitionAnnotation).First(); var newMethodDefinition = methodDefinition.ReplaceToken( methodDefinition.Body.OpenBraceToken, methodDefinition.Body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed))); newDocument = await newDocument.WithSyntaxRootAsync(root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (this.AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(this.AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Pk2 = PICkit2V2.PICkitFunctions; namespace PICkit2V2 { public partial class DialogPK2Go : Form { public float VDDVolts = 0; public string dataSource = "--"; public bool codeProtect = false; public bool dataProtect = false; public bool verifyDevice = false; public bool vppFirst = false; public bool writeProgMem = true; public bool writeEEPROM = true; public bool fastProgramming = true; public bool holdMCLR = false; public byte icspSpeedSlow = 4; private byte ptgMemory = 0; // 128K default private int blinkCount = 0; public DialogPK2Go() { InitializeComponent(); } public void SetPTGMemory(byte value) { ptgMemory = value; if ((ptgMemory > 0) && (ptgMemory <= 5)) label256K.Visible = true; //===== Display what will be used for PTG ===== if (ptgMemory == 1) label256K.Text = "256K PICkit 2 upgrade support enabled.\r\n"; else if (ptgMemory == 2) label256K.Text = "512K SPI memory support enabled.\r\n"; else if (ptgMemory == 3) label256K.Text = "1M SPI memory support enabled.\r\n"; else if (ptgMemory == 4) label256K.Text = "2M SPI memory support enabled.\r\n"; else if (ptgMemory == 5) label256K.Text = "4M SPI memory support enabled.\r\n"; } private void buttonCancel_Click(object sender, EventArgs e) { this.Close(); } private void buttonNext_Click(object sender, EventArgs e) { if (panelIntro.Visible) { panelIntro.Visible = false; buttonBack.Enabled = true; fillSettings(true); } else if (panelSettings.Visible) { if (checkEraseVoltage()) { panelSettings.Visible = false; buttonNext.Text = "Download"; fillDownload(); } } else if (panelDownload.Visible) { downloadGO(); } else if (panelDownloadDone.Visible) { buttonNext.Enabled = false; panelDownloadDone.Visible = false; panelErrors.Visible = true; timerBlink.Interval = 84; } } private void buttonBack_Click(object sender, EventArgs e) { if (panelSettings.Visible) { panelSettings.Visible = false; panelIntro.Visible = true; buttonBack.Enabled = false; } else if (panelDownload.Visible) { panelDownload.Visible = false; buttonNext.Text = "Next >"; fillSettings(false); } } private bool checkEraseVoltage() { if (radioButtonSelfPower.Checked) return true; if (VDDVolts < Pk2.DevFile.PartsList[Pk2.ActivePart].VddErase) { if (Pk2.DevFile.PartsList[Pk2.ActivePart].DebugRowEraseScript == 0) { DialogResult goAhead = MessageBox.Show( "The selected PICkit 2 VDD voltage is below\nthe minimum required to Bulk Erase this part.\n\nContinue anyway?", labelPartNumber.Text + " VDD Error", MessageBoxButtons.OKCancel); if (goAhead == DialogResult.OK) return true; else return false; } } return true; } private void fillSettings(bool changePower) { // Buffer settings // Device labelPartNumber.Text = Pk2.DevFile.PartsList[Pk2.ActivePart].PartName; if (Pk2.DevFile.PartsList[Pk2.ActivePart].OSSCALSave) { labelOSCCAL_BandGap.Visible = true; if (Pk2.DevFile.PartsList[Pk2.ActivePart].BandGapMask > 0) { labelOSCCAL_BandGap.Text = "OSCCAL && BandGap will be preserved."; } } // source if (dataSource == "Edited.") labelDataSource.Text = "Edited Buffer."; else labelDataSource.Text = dataSource; // code protects if (!writeProgMem) { // write EE only labelCodeProtect.Text = "N/A"; labelDataProtect.Text = "N/A"; } else { if (codeProtect) labelCodeProtect.Text = "ON"; else labelCodeProtect.Text = "OFF"; if (dataProtect) labelDataProtect.Text = "ON"; else { if (Pk2.DevFile.PartsList[Pk2.ActivePart].EEMem > 0) labelDataProtect.Text = "OFF"; else labelDataProtect.Text = "N/A"; } } // mem regions if (!writeProgMem) { labelMemRegions.Text = "Write EEPROM data only."; } else if (!writeEEPROM && (Pk2.DevFile.PartsList[Pk2.ActivePart].EEMem > 0)) { labelMemRegions.Text = "Preserve EEPROM on write."; } else { labelMemRegions.Text = "Write entire device."; } if (verifyDevice) labelVerify.Text = "Yes"; else labelVerify.Text = "No - device will NOT be verified"; // Power Settings if (changePower) { radioButtonPK2Power.Text = string.Format("Power target from PICkit 2 at {0:0.0} Volts.", VDDVolts); if (vppFirst) { radioButtonSelfPower.Enabled = false; radioButtonSelfPower.Text = "Use VPP First - must power from PICkit 2"; checkBoxRowErase.Enabled = false; radioButtonPK2Power.Checked = true; pickit2PowerRowErase(); } else { radioButtonSelfPower.Checked = true; if (Pk2.DevFile.PartsList[Pk2.ActivePart].DebugRowEraseScript > 0) { checkBoxRowErase.Text = string.Format("VDD < {0:0.0}V: Use low voltage row erase", Pk2.DevFile.PartsList[Pk2.ActivePart].VddErase); checkBoxRowErase.Enabled = true; } else { checkBoxRowErase.Visible = false; checkBoxRowErase.Enabled = false; labelVDDMin.Text = string.Format("VDD must be >= {0:0.0} Volts.", Pk2.DevFile.PartsList[Pk2.ActivePart].VddErase); labelVDDMin.Visible = true; } } } panelSettings.Visible = true; } private bool pickit2PowerRowErase() { if (VDDVolts < Pk2.DevFile.PartsList[Pk2.ActivePart].VddErase) { if (Pk2.DevFile.PartsList[Pk2.ActivePart].DebugRowEraseScript > 0) { labelRowErase.Text = "Row Erase used: Will NOT program Code Protected parts!"; labelRowErase.Visible = true; } else { MessageBox.Show(string.Format("PICkit 2 cannot program this device\nat the selected VDD voltage.\n\n{0:0.0}V is below the minimum for erase, {0:0.0}V", VDDVolts, Pk2.DevFile.PartsList[Pk2.ActivePart].VddErase), "Programmer-To-Go"); return false; } } else { labelRowErase.Visible = false; } return true; } private void fillDownload() { labelPNsmmry.Text = labelPartNumber.Text; labelSourceSmmry.Text = labelDataSource.Text; if (radioButtonSelfPower.Checked) { if (checkBoxRowErase.Enabled && checkBoxRowErase.Checked) { labelTargetPowerSmmry.Text = "Target is Powered (Use Low Voltage Row Erase)"; } else { labelTargetPowerSmmry.Text = string.Format("Target is Powered (Min VDD = {0:0.0} Volts)", Pk2.DevFile.PartsList[Pk2.ActivePart].VddErase); } } else { labelTargetPowerSmmry.Text = string.Format("Power target from PICkit 2 at {0:0.0} Volts", VDDVolts); } labelMemRegionsSmmry.Text = labelMemRegions.Text; if (writeProgMem) { if (codeProtect) labelMemRegionsSmmry.Text += " -CP"; if (dataProtect) labelMemRegionsSmmry.Text += " -DP"; } if (vppFirst) labelVPP1stSmmry.Text = "Use VPP 1st Program Entry"; else labelVPP1stSmmry.Text = ""; if (verifyDevice) labelVerifySmmry.Text = "Device will be verified"; else labelVerifySmmry.Text = "Device will NOT be verified"; if (fastProgramming) labelFastProgSmmry.Text = "Fast Programming is ON"; else labelFastProgSmmry.Text = "Fast Programming is OFF"; if (holdMCLR) labelMCLRHoldSmmry.Text = "MCLR kept asserted during && after programming"; else labelMCLRHoldSmmry.Text = "MCLR released after programming"; panelDownload.Visible = true; } public DelegateWrite PICkit2WriteGo; private void downloadGO() { panelDownload.Visible = false; panelDownloading.Visible = true; buttonHelp.Enabled = false; buttonBack.Enabled = false; buttonNext.Enabled = false; buttonCancel.Enabled = false; buttonCancel.Text = "Exit"; this.Update(); if (radioButtonSelfPower.Checked) { Pk2.ForceTargetPowered(); } else { Pk2.ForcePICkitPowered(); } if (ptgMemory <= 5) Pk2.EnterLearnMode(ptgMemory); // set memory size to use else Pk2.EnterLearnMode(0); // default to 128K on illegal value if (fastProgramming) Pk2.SetProgrammingSpeed(0); else Pk2.SetProgrammingSpeed(icspSpeedSlow); PICkit2WriteGo(true); Pk2.ExitLearnMode(); if (ptgMemory <= 5) Pk2.EnablePK2GoMode(ptgMemory); // set memory size to use else Pk2.EnablePK2GoMode(0); // default to 128K on illegal value. Pk2.DisconnectPICkit2Unit(); panelDownloading.Visible = false; panelDownloadDone.Visible = true; buttonHelp.Enabled = true; buttonNext.Enabled = true; buttonNext.Text = "Next >"; buttonCancel.Enabled = true; timerBlink.Enabled = true; } private void radioButtonPK2Power_Click(object sender, EventArgs e) { radiobuttonPower(); } private void radioButtonSelfPower_Click(object sender, EventArgs e) { radiobuttonPower(); } private void radiobuttonPower() { if (radioButtonPK2Power.Checked) { checkBoxRowErase.Enabled = false; if (!pickit2PowerRowErase()) { radioButtonPK2Power.Checked = false; radioButtonSelfPower.Checked = true; } } else { if (Pk2.DevFile.PartsList[Pk2.ActivePart].DebugRowEraseScript > 0) { checkBoxRowErase.Enabled = true; } else { checkBoxRowErase.Enabled = false; } if (checkBoxRowErase.Enabled && checkBoxRowErase.Checked) { labelRowErase.Text = "Row Erase used: Will NOT program Code Protected parts!"; labelRowErase.Visible = true; } else { labelRowErase.Visible = false; } } } private void checkBoxRowErase_CheckedChanged(object sender, EventArgs e) { if (checkBoxRowErase.Enabled && checkBoxRowErase.Checked) { labelRowErase.Text = "Row Erase used: Will NOT program Code Protected parts!"; labelRowErase.Visible = true; } else { labelRowErase.Visible = false; } } private void timerBlink_Tick(object sender, EventArgs e) { if (panelDownloadDone.Visible) { blinkCount++; if (blinkCount > 5) blinkCount = 0; if (blinkCount < 4) { if ((blinkCount & 0x1) == 0) pictureBoxTarget.BackColor = Color.Yellow; else pictureBoxTarget.BackColor = System.Drawing.SystemColors.ControlText; } } else { // error panel if (radioButtonVErr.Checked) { blinkCount++; if ((blinkCount & 0x1) == 0) pictureBoxBusy.BackColor = Color.Red; else pictureBoxBusy.BackColor = System.Drawing.SystemColors.ControlText; } else { int blink = 4; if (radioButton3Blinks.Checked) blink = 6; else if (radioButton4Blinks.Checked) blink = 8; if (blinkCount++ <= blink) { if ((blinkCount & 0x1) == 0) pictureBoxBusy.BackColor = Color.Red; else pictureBoxBusy.BackColor = System.Drawing.SystemColors.ControlText; } else blinkCount = 0; } } } private void DialogPK2Go_FormClosing(object sender, FormClosingEventArgs e) { Pk2.ExitLearnMode(); // just in case. } private void radioButtonVErr_Click(object sender, EventArgs e) { if (radioButtonVErr.Checked) timerBlink.Interval = 84; else timerBlink.Interval = 200; } public DelegateOpenProgToGoGuide OpenProgToGoGuide; private void buttonHelp_Click(object sender, EventArgs e) { OpenProgToGoGuide(); } } }
using System; using System.Collections; using System.Configuration; using System.Configuration.Install; using System.Reflection; using System.Threading; using System.Management; using System.Management.Instrumentation; // // Define unique namespace. // [assembly:Instrumented("root/WiresssDrivers")] namespace Hydra.Framework.ManagedInformationBase { // //********************************************************************** /// <summary> /// define the ManagedInformationBase provider class. /// </summary> //********************************************************************** // [InstrumentationClass(InstrumentationType.Instance)] public class MIBObject { #region Private Constants private static readonly bool MIB_INITIALISE_PROCESS_COUNTERS = bool.Parse(ConfigurationSettings.AppSettings["MIB.Initialise.ProcessCounters"]); private static readonly int MIB_CONCURRENCY_LIMIT = int.Parse(ConfigurationSettings.AppSettings["MIB.Thread.ConcurrencyLimit"]); private static readonly int MIB_TASK_QUEUE_LENGTH = int.Parse(ConfigurationSettings.AppSettings["TaskQueueLength"]); private static readonly int MIB_TASK_PREPROCESSOR_THREADS = int.Parse(ConfigurationSettings.AppSettings["TaskPreProcessorThreadCount"]); private static readonly int MIB_SCRIPT_PREPROCESSOR_THREADS = int.Parse(ConfigurationSettings.AppSettings["ScriptPreProcessorThreadCount"]); private static readonly int MIB_VOC_THREADS = int.Parse(ConfigurationSettings.AppSettings["VOCThreadCount"]); private static readonly int MIB_INFERENCE_ENGINE_THREADS = int.Parse(ConfigurationSettings.AppSettings["InferenceEngineThreadCount"]); private static readonly int MIB_GENERIC_MACHINE_SIMULATOR_THREADS = int.Parse(ConfigurationSettings.AppSettings["GenericMachineSimulatorThreadCount"]); private static readonly int MIB_GENERIC_MACHINE_SIMULATORS = int.Parse(ConfigurationSettings.AppSettings["GenericMachineSimulators"]); private static readonly int MIB_TASK_WAIT_INTERVAL = int.Parse(ConfigurationSettings.AppSettings["TaskPreProcessor.WaitInterval"]); private static readonly int MIB_VOC_WAIT_INTERVAL = int.Parse(ConfigurationSettings.AppSettings["VirtualOutputVesselConstructor.WaitInterval"]); private static readonly int MIB_CAP_THREADS = int.Parse(ConfigurationSettings.AppSettings["CapabilityPreProcessorThreadCount"]); private static readonly int MIB_CAP_WAIT_INTERVAL = int.Parse(ConfigurationSettings.AppSettings["CapabilityPreProcessor.WaitInterval"]); private static readonly int MIB_FSE_WAIT_INTERVAL = int.Parse(ConfigurationSettings.AppSettings["FiniteStateEngine.WaitInterval"]); private static readonly int MIB_SPP_WAIT_INTERVAL = int.Parse(ConfigurationSettings.AppSettings["ScriptPreProcessor.WaitInterval"]); private static readonly string MIB_SPP_POOL = ConfigurationSettings.AppSettings["ScriptPreProcessor.Pool"]; private static readonly int MIB_SPP_NUM_THREADS = int.Parse(ConfigurationSettings.AppSettings["ScriptPreProcessor.NumThreads"]); private static readonly int MIB_SPP_NUM_CONCURRENT_THREADS = int.Parse(ConfigurationSettings.AppSettings["ScriptPreProcessor.NumConcurrentThreads"]); private static readonly int MIB_SPP_ACTION_EVENT_TIMEOUT = int.Parse(ConfigurationSettings.AppSettings["ScriptPreProcessor.ActionEventTimeout"]); private static readonly int MIB_IE_WAIT_INTERVAL = int.Parse(ConfigurationSettings.AppSettings["InferenceEngine.WaitInterval"]); private static readonly string MIB_IE_POOL = ConfigurationSettings.AppSettings["InferenceEngine.Pool"]; private static readonly int MIB_IE_NUM_THREADS = int.Parse(ConfigurationSettings.AppSettings["InferenceEngine.NumThreads"]); private static readonly string MIB_LOGGER_NAME = ConfigurationSettings.AppSettings["LoggerName"]; private static readonly string MIB_LOGGER_SINGLE_INSTANCE = ConfigurationSettings.AppSettings["SingleInstance"]; private static readonly bool MIB_INFERENCE_ENGINE_SINGLE_SOLUTION = bool.Parse(ConfigurationSettings.AppSettings["InferenceEngine.SingleSolution"]); private static readonly bool MIB_TASK_OPTIMISE_FOR_CAPABILITIES = bool.Parse(ConfigurationSettings.AppSettings["TaskPreProcessor.OptimiseCapabilities"]); private static readonly int MIB_TPP_STEP_DOWN_WAIT_INTERVAL = int.Parse(ConfigurationSettings.AppSettings["TaskPreProcessor.StepDownWaitInterval"]); private static readonly bool MIB_TPP_USE_STEP_DOWN = bool.Parse(ConfigurationSettings.AppSettings["TaskPreProcessor.UseStepDown"]); private static readonly bool MIB_TPP_USE_CONCURRENT_TASKS = bool.Parse(ConfigurationSettings.AppSettings["TaskPreProcessor.UseConcurrentTasks"]); private static readonly bool MIB_TPP_ABORT_TASK = bool.Parse(ConfigurationSettings.AppSettings["TaskPreProcessor.AbortTask"]); private static readonly bool MIB_TPP_SIMPLE_FORMAT= bool.Parse(ConfigurationSettings.AppSettings["TaskPreProcessor.UseSimpleFormat"]); #endregion #region Private Attributes // //********************************************************************** /// <summary> /// The maximum number of task queue items /// </summary> //********************************************************************** // private int m_iTaskQueue; // //********************************************************************** /// <summary> /// Number of Threads required to support Task PreProcessing /// </summary> //********************************************************************** // private int m_iTaskPreProcessorThreads; // //********************************************************************** /// <summary> /// Number of Threads required to support Script PreProcessing /// </summary> //********************************************************************** // private int m_iScriptPreProcessorThreads; // //********************************************************************** /// <summary> /// Number of Threads required to support VOC /// </summary> //********************************************************************** // private int m_iVOCThreads; // //********************************************************************** /// <summary> /// Number of Threads required to support the Inference Engine /// </summary> //********************************************************************** // private int m_iInferenceThreads; // //********************************************************************** /// <summary> /// Number of Threads required to support the Generic Machine Simulator /// </summary> //********************************************************************** // private int m_iMachineSimilatorThreads; // //********************************************************************** /// <summary> /// Wait Interval for the Task PreProcessor /// </summary> //********************************************************************** // private int m_iTaskPreProcessorWaitInterval; // //********************************************************************** /// <summary> /// Wait Interval for the Virtual Output Vessel Constructor /// </summary> //********************************************************************** // private int m_iVOCWaitInterval; // //********************************************************************** /// <summary> /// Number of Threads required by the Capability Pre Processor /// </summary> //********************************************************************** // private int m_iCapabilityPreProcessorThreads; // //********************************************************************** /// <summary> /// Wait Interval for the Capability PreProcessor /// </summary> //********************************************************************** // private int m_iCapabilityPreProcessorWaitInterval; // //********************************************************************** /// <summary> /// Wait Interval for the Finite State Engine /// </summary> //********************************************************************** // private int m_iFiniteStateEngineWaitInterval; // //********************************************************************** /// <summary> /// Wait Interval for the Script PreProcessor /// </summary> //********************************************************************** // private int m_iScriptPreProcessorWaitInterval; // //********************************************************************** /// <summary> /// Thread Pool for the Script PreProcessor /// </summary> //********************************************************************** // private string m_sScriptPreProcessorPool; // //********************************************************************** /// <summary> /// Number of Internal Threads for the Script PreProcessor /// </summary> //********************************************************************** // private int m_iScriptPreProcessorNumThreads; // //********************************************************************** /// <summary> /// Number of Concurrent Threads what can be run to perform script engine work for a task /// </summary> //********************************************************************** // private int m_iScriptPreProcessorNumConcurrentThreads; // //********************************************************************** /// <summary> /// Number of Miliseconds in which the timer event needs to wakeup for action events /// within the Script PreProcessor /// </summary> //********************************************************************** // private int m_iScriptPreProcessorActionEventTimeout; // //********************************************************************** /// <summary> /// Wait Interval for the Inference Engine /// </summary> //********************************************************************** // private int m_iInferenceEngineWaitInterval; // //********************************************************************** /// <summary> /// Thread Pool for the Inference Engine /// </summary> //********************************************************************** // private string m_sInferenceEnginePool; // //********************************************************************** /// <summary> /// Number of Internal Threads for the Inference Engine /// </summary> //********************************************************************** // private int m_iInferenceEngineNumThreads; // //********************************************************************** /// <summary> /// Logging (log4net) Appender StateName /// </summary> //********************************************************************** // private string m_LoggingName; // //********************************************************************** /// <summary> /// Logging Single Instance (Single Thread supporting all logging /// </summary> //********************************************************************** // private string m_LoggingSingleInstance; // //********************************************************************** /// <summary> /// Inference Engine - Find the First Solution and stop /// </summary> //********************************************************************** // private bool m_bFindFirstSolution; // //********************************************************************** /// <summary> /// Task Pre Processor - Optimise task against all capabilities /// </summary> //********************************************************************** // private bool m_bOptimiseForCapabilities; // //********************************************************************** /// <summary> /// Concurrency Limits on the number of active threads which can perform work /// </summary> //********************************************************************** // private int m_iConcurrencyLimit; // //********************************************************************** /// <summary> /// This is the interval when the task preprocessor has no tasks to perform and increases the CPU requirements of the task preprocessor so that /// the queue can be populated quickly, then reverts to the normal wait interval while the queue contains tasks so that there is little or no bottlenecks /// </summary> //********************************************************************** // private int m_iStepDownWaitInterval; // //********************************************************************** /// <summary> /// set this when the task preprocessor has no tasks to perform and increases the CPU requirements of the task preprocessor so that /// the queue can be populated quickly, then reverts to the normal wait interval while the queue contains tasks so that there is little or no bottlenecks /// </summary> //********************************************************************** // private bool m_bUseStepDown; // //********************************************************************** /// <summary> /// Set this when you want the task preprocessor to instigate concurrent task loading. This will start a number of concurrent jobs to load up a number of /// tasks which is no more than the task queue length limit. /// </summary> //********************************************************************** // private bool m_bUseConcurrentTasks; // //********************************************************************** /// <summary> /// When the task preprocessor fails to find a suitable capability should it abort the task - this notifies core that the task has been aborted /// </summary> //********************************************************************** // private bool m_bAbortTask; // //********************************************************************** /// <summary> /// When use simple format is specified the inference engine task pre-processor uses a single op1 / rep1 format as well as the spec-hole format /// </summary> //********************************************************************** // private bool m_bUseSimpleFormat; // //********************************************************************** /// <summary> /// Number of Script Engines being executed /// </summary> //********************************************************************** // private int m_iScriptEngineCount; // //********************************************************************** /// <summary> /// A lock when accessing our properties. /// </summary> //********************************************************************** // private readonly object mibLock = new object(); // //********************************************************************** /// <summary> /// Record current Instance of TaskService /// </summary> //********************************************************************** // private static readonly MIBObject INSTANCE = new MIBObject(); // //********************************************************************** /// <summary> /// Instance of the WMI Object /// </summary> //********************************************************************** // [IgnoreMember] private readonly WMI WMIObject = new WMI(); // //********************************************************************** /// <summary> /// Performance Counters /// </summary> //********************************************************************** // [IgnoreMember] private PerformanceCounters Counters = null; #endregion #region Public Attributes #endregion #region Constructor // //********************************************************************** /// <summary> /// Constructor for initialising MIB attributes /// </summary> //********************************************************************** // public MIBObject() { // // Inference Engine Defaults // m_iTaskQueue = MIB_TASK_QUEUE_LENGTH; m_iTaskPreProcessorThreads = MIB_TASK_PREPROCESSOR_THREADS; m_iScriptPreProcessorThreads = MIB_SCRIPT_PREPROCESSOR_THREADS; m_iVOCThreads = MIB_VOC_THREADS; m_iInferenceThreads = MIB_INFERENCE_ENGINE_THREADS; m_iMachineSimilatorThreads = MIB_GENERIC_MACHINE_SIMULATOR_THREADS * MIB_GENERIC_MACHINE_SIMULATORS; m_iTaskPreProcessorWaitInterval = MIB_TASK_WAIT_INTERVAL; m_iVOCWaitInterval = MIB_VOC_WAIT_INTERVAL; m_iCapabilityPreProcessorThreads = MIB_CAP_THREADS; m_iCapabilityPreProcessorWaitInterval = MIB_CAP_WAIT_INTERVAL; m_iFiniteStateEngineWaitInterval = MIB_FSE_WAIT_INTERVAL; m_iScriptPreProcessorNumThreads = MIB_SPP_NUM_THREADS; m_iScriptPreProcessorNumConcurrentThreads = MIB_SPP_NUM_CONCURRENT_THREADS; m_sScriptPreProcessorPool = MIB_SPP_POOL; m_iScriptPreProcessorWaitInterval = MIB_SPP_WAIT_INTERVAL; m_iScriptPreProcessorActionEventTimeout = MIB_SPP_ACTION_EVENT_TIMEOUT; m_iInferenceEngineNumThreads = MIB_IE_NUM_THREADS; m_sInferenceEnginePool = MIB_IE_POOL; m_iInferenceEngineWaitInterval = MIB_IE_WAIT_INTERVAL; m_LoggingName = MIB_LOGGER_NAME; m_LoggingSingleInstance = MIB_LOGGER_SINGLE_INSTANCE; m_bFindFirstSolution = MIB_INFERENCE_ENGINE_SINGLE_SOLUTION; m_bOptimiseForCapabilities = MIB_TASK_OPTIMISE_FOR_CAPABILITIES; m_iConcurrencyLimit = MIB_CONCURRENCY_LIMIT; m_iStepDownWaitInterval = MIB_TPP_STEP_DOWN_WAIT_INTERVAL; m_bUseStepDown = MIB_TPP_USE_STEP_DOWN; m_bUseConcurrentTasks = MIB_TPP_USE_CONCURRENT_TASKS; m_bAbortTask = MIB_TPP_ABORT_TASK; m_bUseSimpleFormat = MIB_TPP_SIMPLE_FORMAT; m_iScriptEngineCount = 0; // // Initialise the performance counters // pCounters = new PerformanceCounters(MIB_INITIALISE_PROCESS_COUNTERS); // // Expose MIB/WMI to instrumentation // Instrumentation.Publish(this); } #endregion #region Properties // //********************************************************************** /// <summary> /// Property to get/set the Performance Counters Instance /// </summary> //********************************************************************** // [IgnoreMember] public PerformanceCounters pCounters { get { lock(mibLock) { return Counters; } } set { lock(mibLock) { Counters = value; } } } // //********************************************************************** /// <summary> /// Property to change the Task Queue Limit /// </summary> //********************************************************************** // public int iTaskQueue { get { lock(mibLock) { return m_iTaskQueue; } } set { lock(mibLock) { m_iTaskQueue = value; } } } // //********************************************************************** /// <summary> /// Property to change the Task Pre Processor Threads /// </summary> //********************************************************************** // public int iTaskPreProcessorThreads { get { lock(mibLock) { return m_iTaskPreProcessorThreads; } } set { lock(mibLock) { m_iTaskPreProcessorThreads = value; } } } // //********************************************************************** /// <summary> /// Property to change the Script Pre Processor Threads /// </summary> //********************************************************************** // public int iScriptPreProcessorThreads { get { lock(mibLock) { return m_iScriptPreProcessorThreads; } } set { lock(mibLock) { m_iScriptPreProcessorThreads = value; } } } // //********************************************************************** /// <summary> /// Property to change the VOC Threads /// </summary> //********************************************************************** // public int iVOCThreads { get { lock(mibLock) { return m_iVOCThreads; } } set { lock(mibLock) { m_iVOCThreads = value; } } } // //********************************************************************** /// <summary> /// Property to change the Inference Engine Threads /// </summary> //********************************************************************** // public int iInferenceThreads { get { lock(mibLock) { return m_iInferenceThreads; } } set { lock(mibLock) { m_iInferenceThreads = value; } } } // //********************************************************************** /// <summary> /// Property to change the Generic Machine Simulator Threads /// </summary> //********************************************************************** // public int iMachineSimilatorThreads { get { lock(mibLock) { return m_iMachineSimilatorThreads; } } set { lock(mibLock) { m_iMachineSimilatorThreads = value; } } } // //********************************************************************** /// <summary> /// Property to change the Task PreProcessor Wait Interval /// </summary> //********************************************************************** // public int iTaskPreProcessorWaitInterval { get { lock(mibLock) { return m_iTaskPreProcessorWaitInterval; } } set { lock(mibLock) { m_iTaskPreProcessorWaitInterval = value; } } } // //********************************************************************** /// <summary> /// Property to change the Virtual Output Vessel Constructor Wait Interval /// </summary> //********************************************************************** // public int iVOCWaitInterval { get { lock(mibLock) { return m_iVOCWaitInterval; } } set { lock(mibLock) { m_iVOCWaitInterval = value; } } } // //********************************************************************** /// <summary> /// Property to change the Capability PreProcessor Thread Count /// </summary> //********************************************************************** // public int iCapabilityPreProcessorThreads { get { lock(mibLock) { return m_iCapabilityPreProcessorThreads; } } set { lock(mibLock) { m_iCapabilityPreProcessorThreads = value; } } } // //********************************************************************** /// <summary> /// Property to change the Capability PreProcessor Wait Interval /// </summary> //********************************************************************** // public int iCapabilityPreProcessorWaitInterval { get { lock(mibLock) { return m_iCapabilityPreProcessorWaitInterval; } } set { lock(mibLock) { m_iCapabilityPreProcessorWaitInterval = value; } } } // //********************************************************************** /// <summary> /// Property to change the Finite State Engine Wait Interval /// </summary> //********************************************************************** // public int iFiniteStateEngineWaitInterval { get { lock(mibLock) { return m_iFiniteStateEngineWaitInterval; } } set { lock(mibLock) { m_iFiniteStateEngineWaitInterval = value; } } } // //********************************************************************** /// <summary> /// Property to change the Script PreProcessor Wait Interval /// </summary> //********************************************************************** // public int iScriptPreProcessorWaitInterval { get { lock(mibLock) { return m_iScriptPreProcessorWaitInterval; } } set { lock(mibLock) { m_iScriptPreProcessorWaitInterval = value; } } } // //********************************************************************** /// <summary> /// Property to change the Script PreProcessor Thread Pool Reference /// </summary> //********************************************************************** // public string sScriptPreProcessorPool { get { lock(mibLock) { return m_sScriptPreProcessorPool; } } set { lock(mibLock) { m_sScriptPreProcessorPool = value; } } } // //********************************************************************** /// <summary> /// Property to change the Script PreProcessor Number of Isolated Threads /// </summary> //********************************************************************** // public int iScriptPreProcessorNumThreads { get { lock(mibLock) { return m_iScriptPreProcessorNumThreads; } } set { lock(mibLock) { m_iScriptPreProcessorNumThreads = value; } } } // //********************************************************************** /// <summary> /// Property to change the Script PreProcessor Number of Concurrent Threads /// </summary> //********************************************************************** // public int iScriptPreProcessorNumConcurrentThreads { get { lock(mibLock) { return m_iScriptPreProcessorNumConcurrentThreads; } } set { lock(mibLock) { m_iScriptPreProcessorNumConcurrentThreads = value; } } } // //********************************************************************** /// <summary> /// Property to change the Script PreProcessor Action Event Timeout /// </summary> //********************************************************************** // public int iScriptPreProcessorActionEventTimeout { get { lock(mibLock) { return iScriptPreProcessorActionEventTimeout; } } set { lock(mibLock) { iScriptPreProcessorActionEventTimeout = value; } } } // //********************************************************************** /// <summary> /// Property to change the Inference Engine Wait Interval /// </summary> //********************************************************************** // public int iInferenceEngineWaitInterval { get { lock(mibLock) { return m_iInferenceEngineWaitInterval; } } set { lock(mibLock) { m_iInferenceEngineWaitInterval = value; } } } // //********************************************************************** /// <summary> /// Property to change the Inference Engine Thread Pool Reference /// </summary> //********************************************************************** // public string sInferenceEnginePool { get { lock(mibLock) { return m_sInferenceEnginePool; } } set { lock(mibLock) { m_sInferenceEnginePool = value; } } } // //********************************************************************** /// <summary> /// Property to change the Inference Engine Number of Isolated Threads /// </summary> //********************************************************************** // public int iInferenceEngineNumThreads { get { lock(mibLock) { return m_iInferenceEngineNumThreads; } } set { lock(mibLock) { m_iInferenceEngineNumThreads = value; } } } // //********************************************************************** /// <summary> /// Property to change the Inference Engine Find single Solution only /// </summary> //********************************************************************** // public bool bInferenceEngineSingleSolution { get { lock(mibLock) { return m_bFindFirstSolution; } } set { lock(mibLock) { m_bFindFirstSolution = value; } } } // //********************************************************************** /// <summary> /// Property to Retrieve the Logger StateName /// </summary> //********************************************************************** // public string sLoggerName { get { lock(mibLock) { return m_LoggingName; } } } // //********************************************************************** /// <summary> /// Property to Retrieve the Logger StateName /// </summary> //********************************************************************** // public string sLoggerInstance { get { lock(mibLock) { return m_LoggingSingleInstance; } } } // //********************************************************************** /// <summary> /// Property to support whether the Task PreProcessor should optimise the task against all known /// capabilities /// </summary> //********************************************************************** // public bool bOptimiseCapabilities { get { lock(mibLock) { return m_bOptimiseForCapabilities; } } set { lock(mibLock) { m_bOptimiseForCapabilities = value; } } } // //********************************************************************** /// <summary> /// Property to support the setting/retrieval of the thread concurrency limits for all work to be performed. /// </summary> //********************************************************************** // public int iConcurrencyLimit { get { lock(mibLock) { return m_iConcurrencyLimit; } } set { lock(mibLock) { m_iConcurrencyLimit = value; } } } // //********************************************************************** /// <summary> /// Property to retrieve the Step Down Wait Interval for the Task PreProcessor /// </summary> //********************************************************************** // public int iStepDownWaitInterval { get { lock(mibLock) { return m_iStepDownWaitInterval; } } set { lock(mibLock) { m_iStepDownWaitInterval = value; } } } // //********************************************************************** /// <summary> /// Property to retrieve the the use of Step Down intervals within the Task PreProcessor /// </summary> //********************************************************************** // public bool bUseStepDown { get { lock(mibLock) { return m_bUseStepDown; } } set { lock(mibLock) { m_bUseStepDown = value; } } } // //********************************************************************** /// <summary> /// Property to retrieve the the use of Concurrent Tasks within the Task PreProcessor /// </summary> //********************************************************************** // public bool bUseConcurrentTasks { get { lock(mibLock) { return m_bUseConcurrentTasks; } } set { lock(mibLock) { m_bUseConcurrentTasks = value; } } } // //********************************************************************** /// <summary> /// Property to retrieve the the use of Abort Task within the Task PreProcessor /// </summary> //********************************************************************** // public bool bAbortTask { get { lock(mibLock) { return m_bAbortTask; } } set { lock(mibLock) { m_bAbortTask = value; } } } // //********************************************************************** /// <summary> /// Property to retrieve the the use of SimpleFormat within the Task PreProcessor /// </summary> //********************************************************************** // public bool bUseSimpleFormat { get { lock(mibLock) { return m_bUseSimpleFormat; } } set { lock(mibLock) { bUseSimpleFormat = value; } } } // //********************************************************************** /// <summary> /// Property to increment the number of script engines being/been executed /// </summary> //********************************************************************** // public int iScriptEngineCount { get { lock(mibLock) { return m_iScriptEngineCount++; } } } // //********************************************************************** /// <summary> /// Property to retrieve the Operation System and Environment Details /// </summary> //********************************************************************** // public string[] sOSDetails { get { lock(mibLock) { return WMIObject.GetOSDetails; } } } // //********************************************************************** /// <summary> /// Property to retrieve the Environment details /// </summary> //********************************************************************** // public string[] sGetEnvironment { get { lock(mibLock) { return GetEnvironment(); } } } // //********************************************************************** /// <summary> /// Retrieve the Domain name of the instance /// </summary> //********************************************************************** // public string sDomainName { get { lock(mibLock) { return WMIObject.DomainName; } } } // //********************************************************************** /// <summary> /// Retrieve the Machine name of the instance /// </summary> //********************************************************************** // public string sMachineName { get { lock(mibLock) { return WMIObject.MachineName; } } } // //********************************************************************** /// <summary> /// Property to retrieve the Configuration Parameters /// </summary> //********************************************************************** // [IgnoreMember] public MIBConfig[] GetConfig { get { lock(mibLock) { return GetConfigParameters(); } } } #endregion #region Private Methods // //********************************************************************** /// <summary> /// Retrieve the app.config parameters /// </summary> /// <returns>an array of strings representing the environment</returns> //********************************************************************** // private string[] GetEnvironment() { ArrayList list = new ArrayList(); list.Add("** MIB Specific Parameters:"); list.Add("** MIB.Initialise.ProcessCounters = " + ConfigurationSettings.AppSettings["MIB.Initialise.ProcessCounters"]); list.Add("** MIB.Thread.ConcurrencyLimit = " + ConfigurationSettings.AppSettings["MIB.Thread.ConcurrencyLimit"]); list.Add("**"); list.Add("** Task PreProcessor Specific Parameters:"); list.Add("** TaskQueueLength = " + ConfigurationSettings.AppSettings["TaskQueueLength"]); list.Add("** TaskPreProcessorThreadCount = " + ConfigurationSettings.AppSettings["TaskPreProcessorThreadCount"]); list.Add("** TaskPreProcessor.WaitInterval = " + ConfigurationSettings.AppSettings["TaskPreProcessor.WaitInterval"]); list.Add("** TaskPreProcessor.OptimiseCapabilities = " + ConfigurationSettings.AppSettings["TaskPreProcessor.OptimiseCapabilities"]); list.Add("** TaskPreProcessor.UseStepDown = " + ConfigurationSettings.AppSettings["TaskPreProcessor.UseStepDown"]); list.Add("** TaskPreProcessor.StepDownWaitInterval = " + ConfigurationSettings.AppSettings["TaskPreProcessor.StepDownWaitInterval"]); list.Add("** TaskPreProcessor.UseConcurrentTasks = " + ConfigurationSettings.AppSettings["TaskPreProcessor.UseConcurrentTasks"]); list.Add("** TaskPreProcessor.AbortTask = " + ConfigurationSettings.AppSettings["TaskPreProcessor.AbortTask"]); list.Add("** TaskPreProcessor.UseSimpleFormat = " + ConfigurationSettings.AppSettings["TaskPreProcessor.UseSimpleFormat"]); list.Add("**"); list.Add("** Vessel Output Constructor Specific Parameters:"); list.Add("** VOCThreadCount = " + ConfigurationSettings.AppSettings["VOCThreadCount"]); list.Add("** VirtualOutputVesselConstructor.WaitInterval = " + ConfigurationSettings.AppSettings["VirtualOutputVesselConstructor.WaitInterval"]); list.Add("**"); list.Add("** Capability PreProcessor Specific Parameters:"); list.Add("** CapabilityPreProcessorThreadCount = " + ConfigurationSettings.AppSettings["CapabilityPreProcessorThreadCount"]); list.Add("** CapabilityPreProcessor.WaitInterval = " + ConfigurationSettings.AppSettings["CapabilityPreProcessor.WaitInterval"]); list.Add("**"); list.Add("** Script PreProcessor Specific Parameters:"); list.Add("** ScriptPreProcessorThreadCount = " + ConfigurationSettings.AppSettings["ScriptPreProcessorThreadCount"]); list.Add("** ScriptPreProcessor.WaitInterval = " + ConfigurationSettings.AppSettings["ScriptPreProcessor.WaitInterval"]); list.Add("** ScriptPreProcessor.Pool = " + ConfigurationSettings.AppSettings["ScriptPreProcessor.Pool"]); list.Add("** ScriptPreProcessor.NumThreads = " + ConfigurationSettings.AppSettings["ScriptPreProcessor.NumThreads"]); list.Add("** ScriptPreProcessor.NumConcurrentThreads = " + ConfigurationSettings.AppSettings["ScriptPreProcessor.NumConcurrentThreads"]); list.Add("** ScriptPreProcessor.ActionEventTimeout = " + ConfigurationSettings.AppSettings["ScriptPreProcessor.ActionEventTimeout"]); list.Add("**"); list.Add("** Inference Engine Specific Parameters:"); list.Add("** InferenceEngineThreadCount = " + ConfigurationSettings.AppSettings["InferenceEngineThreadCount"]); list.Add("** InferenceEngine.WaitInterval = " + ConfigurationSettings.AppSettings["InferenceEngine.WaitInterval"]); list.Add("** InferenceEngine.Pool = " + ConfigurationSettings.AppSettings["InferenceEngine.Pool"]); list.Add("** InferenceEngine.NumThreads = " + ConfigurationSettings.AppSettings["InferenceEngine.NumThreads"]); list.Add("** InferenceEngine.SingleSolution = " + ConfigurationSettings.AppSettings["InferenceEngine.SingleSolution"]); list.Add("**"); list.Add("** Generic Machine Simulator Specific Parameters:"); list.Add("** GenericMachineSimulatorThreadCount = " + ConfigurationSettings.AppSettings["GenericMachineSimulatorThreadCount"]); list.Add("** GenericMachineSimulators = " + ConfigurationSettings.AppSettings["GenericMachineSimulators"]); list.Add("**"); list.Add("** Finite State Engine Specific Parameters:"); list.Add("** FiniteStateEngine.WaitInterval = " + ConfigurationSettings.AppSettings["FiniteStateEngine.WaitInterval"]); list.Add("**"); list.Add("** Logging Specific Parameters:"); list.Add("** LoggerName = " + ConfigurationSettings.AppSettings["LoggerName"]); list.Add("** SingleInstance = " + ConfigurationSettings.AppSettings["SingleInstance"]); list.Add("**"); return (string[])list.ToArray(typeof(string)); } // //********************************************************************** /// <summary> /// Retrieve the app.config parameters /// </summary> /// <returns>an array of MIBConfig representing the environment</returns> //********************************************************************** // private MIBConfig[] GetConfigParameters() { ArrayList list = new ArrayList(); list.Add(new MIBConfig("MIB.Initialise.ProcessCounters", ConfigurationSettings.AppSettings["MIB.Initialise.ProcessCounters"].ToString())); list.Add(new MIBConfig("MIB.Thread.ConcurrencyLimit", ConfigurationSettings.AppSettings["MIB.Thread.ConcurrencyLimit"].ToString())); list.Add(new MIBConfig("TaskQueueLength", ConfigurationSettings.AppSettings["TaskQueueLength"].ToString())); list.Add(new MIBConfig("TaskPreProcessorThreadCount", ConfigurationSettings.AppSettings["TaskPreProcessorThreadCount"].ToString())); list.Add(new MIBConfig("TaskPreProcessor.WaitInterval", ConfigurationSettings.AppSettings["TaskPreProcessor.WaitInterval"].ToString())); list.Add(new MIBConfig("TaskPreProcessor.OptimiseCapabilities", ConfigurationSettings.AppSettings["TaskPreProcessor.OptimiseCapabilities"].ToString())); list.Add(new MIBConfig("TaskPreProcessor.UseStepDown", ConfigurationSettings.AppSettings["TaskPreProcessor.UseStepDown"].ToString())); list.Add(new MIBConfig("TaskPreProcessor.StepDownWaitInterval", ConfigurationSettings.AppSettings["TaskPreProcessor.StepDownWaitInterval"].ToString())); list.Add(new MIBConfig("TaskPreProcessor.UseConcurrentTasks", ConfigurationSettings.AppSettings["TaskPreProcessor.UseConcurrentTasks"].ToString())); list.Add(new MIBConfig("TaskPreProcessor.AbortTask", ConfigurationSettings.AppSettings["TaskPreProcessor.AbortTask"].ToString())); list.Add(new MIBConfig("TaskPreProcessor.UseSimpleFormat", ConfigurationSettings.AppSettings["TaskPreProcessor.UseSimpleFormat"].ToString())); list.Add(new MIBConfig("VOCThreadCount", ConfigurationSettings.AppSettings["VOCThreadCount"].ToString())); list.Add(new MIBConfig("VirtualOutputVesselConstructor.WaitInterval", ConfigurationSettings.AppSettings["VirtualOutputVesselConstructor.WaitInterval"].ToString())); list.Add(new MIBConfig("CapabilityPreProcessorThreadCount", ConfigurationSettings.AppSettings["CapabilityPreProcessorThreadCount"].ToString())); list.Add(new MIBConfig("CapabilityPreProcessor.WaitInterval", ConfigurationSettings.AppSettings["CapabilityPreProcessor.WaitInterval"].ToString())); list.Add(new MIBConfig("ScriptPreProcessorThreadCount", ConfigurationSettings.AppSettings["ScriptPreProcessorThreadCount"].ToString())); list.Add(new MIBConfig("ScriptPreProcessor.WaitInterval", ConfigurationSettings.AppSettings["ScriptPreProcessor.WaitInterval"].ToString())); list.Add(new MIBConfig("ScriptPreProcessor.Pool", ConfigurationSettings.AppSettings["ScriptPreProcessor.Pool"].ToString())); list.Add(new MIBConfig("ScriptPreProcessor.NumThreads", ConfigurationSettings.AppSettings["ScriptPreProcessor.NumThreads"].ToString())); list.Add(new MIBConfig("ScriptPreProcessor.NumConcurrentThreads", ConfigurationSettings.AppSettings["ScriptPreProcessor.NumConcurrentThreads"].ToString())); list.Add(new MIBConfig("ScriptPreProcessor.ActionEventTimeout", ConfigurationSettings.AppSettings["ScriptPreProcessor.ActionEventTimeout"].ToString())); list.Add(new MIBConfig("InferenceEngineThreadCount", ConfigurationSettings.AppSettings["InferenceEngineThreadCount"].ToString())); list.Add(new MIBConfig("InferenceEngine.WaitInterval", ConfigurationSettings.AppSettings["InferenceEngine.WaitInterval"].ToString())); list.Add(new MIBConfig("InferenceEngine.Pool", ConfigurationSettings.AppSettings["InferenceEngine.Pool"].ToString())); list.Add(new MIBConfig("InferenceEngine.NumThreads", ConfigurationSettings.AppSettings["InferenceEngine.NumThreads"].ToString())); list.Add(new MIBConfig("InferenceEngine.SingleSolution", ConfigurationSettings.AppSettings["InferenceEngine.SingleSolution"].ToString())); list.Add(new MIBConfig("GenericMachineSimulatorThreadCount", ConfigurationSettings.AppSettings["GenericMachineSimulatorThreadCount"].ToString())); list.Add(new MIBConfig("GenericMachineSimulators", ConfigurationSettings.AppSettings["GenericMachineSimulators"].ToString())); list.Add(new MIBConfig("FiniteStateEngine.WaitInterval", ConfigurationSettings.AppSettings["FiniteStateEngine.WaitInterval"].ToString())); list.Add(new MIBConfig("LoggerName", ConfigurationSettings.AppSettings["LoggerName"].ToString())); list.Add(new MIBConfig("SingleInstance", ConfigurationSettings.AppSettings["SingleInstance"].ToString())); return (MIBConfig[])list.ToArray(typeof(MIBConfig)); } #endregion #region Public Methods // //********************************************************************** /// <summary> /// Get Current Instance of the ManagedInformationBase /// </summary> /// <returns></returns> //********************************************************************** // public static MIBObject GetInstance() { return INSTANCE; } #endregion } }
// *********************************************************************** // Copyright (c) 2008 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Reflection; using System.Text; namespace NUnit.Framework.Internal { /// <summary> /// TypeHelper provides static methods that operate on Types. /// </summary> public class TypeHelper { /// <summary> /// Gets the display name for a Type as used by NUnit. /// </summary> /// <param name="type">The Type for which a display name is needed.</param> /// <returns>The display name for the Type</returns> public static string GetDisplayName(Type type) { #if true if (type.IsGenericParameter) return type.Name; if (type.IsGenericType) { string name = type.FullName; int index = name.IndexOf('['); if (index >= 0) name = name.Substring(0, index); index = name.LastIndexOf('.'); if (index >= 0) name = name.Substring(index+1); index = name.IndexOf('`'); if (index >= 0) name = name.Substring(0, index); StringBuilder sb = new StringBuilder(name); sb.Append("<"); int cnt = 0; foreach (Type t in type.GetGenericArguments()) { if (cnt++ > 0) sb.Append(","); sb.Append(GetDisplayName(t)); } sb.Append(">"); return sb.ToString(); } #endif int lastdot = type.FullName.LastIndexOf('.'); return lastdot >= 0 ? type.FullName.Substring(lastdot+1) : type.FullName; } /// <summary> /// Gets the display name for a Type as used by NUnit. /// </summary> /// <param name="type">The Type for which a display name is needed.</param> /// <param name="arglist">The arglist provided.</param> /// <returns>The display name for the Type</returns> public static string GetDisplayName(Type type, object[] arglist) { string baseName = GetDisplayName(type); if (arglist == null || arglist.Length == 0) return baseName; StringBuilder sb = new StringBuilder( baseName ); sb.Append("("); for (int i = 0; i < arglist.Length; i++) { if (i > 0) sb.Append(","); object arg = arglist[i]; string display = arg == null ? "null" : arg.ToString(); if (arg is double || arg is float) { if (display.IndexOf('.') == -1) display += ".0"; display += arg is double ? "d" : "f"; } else if (arg is decimal) display += "m"; else if (arg is long) display += "L"; else if (arg is ulong) display += "UL"; else if (arg is string) display = "\"" + display + "\""; sb.Append(display); } sb.Append(")"); return sb.ToString(); } /// <summary> /// Returns the best fit for a common type to be used in /// matching actual arguments to a methods Type parameters. /// </summary> /// <param name="type1">The first type.</param> /// <param name="type2">The second type.</param> /// <returns>Either type1 or type2, depending on which is more general.</returns> public static Type BestCommonType(Type type1, Type type2) { if (type1 == type2) return type1; if (type1 == null) return type2; if (type2 == null) return type1; if (TypeHelper.IsNumeric(type1) && TypeHelper.IsNumeric(type2)) { if (type1 == typeof(double)) return type1; if (type2 == typeof(double)) return type2; if (type1 == typeof(float)) return type1; if (type2 == typeof(float)) return type2; if (type1 == typeof(decimal)) return type1; if (type2 == typeof(decimal)) return type2; if (type1 == typeof(UInt64)) return type1; if (type2 == typeof(UInt64)) return type2; if (type1 == typeof(Int64)) return type1; if (type2 == typeof(Int64)) return type2; if (type1 == typeof(UInt32)) return type1; if (type2 == typeof(UInt32)) return type2; if (type1 == typeof(Int32)) return type1; if (type2 == typeof(Int32)) return type2; if (type1 == typeof(UInt16)) return type1; if (type2 == typeof(UInt16)) return type2; if (type1 == typeof(Int16)) return type1; if (type2 == typeof(Int16)) return type2; if (type1 == typeof(byte)) return type1; if (type2 == typeof(byte)) return type2; if (type1 == typeof(sbyte)) return type1; if (type2 == typeof(sbyte)) return type2; } return type1; } /// <summary> /// Determines whether the specified type is numeric. /// </summary> /// <param name="type">The type to be examined.</param> /// <returns> /// <c>true</c> if the specified type is numeric; otherwise, <c>false</c>. /// </returns> public static bool IsNumeric(Type type) { return type == typeof(double) || type == typeof(float) || type == typeof(decimal) || type == typeof(Int64) || type == typeof(Int32) || type == typeof(Int16) || type == typeof(UInt64) || type == typeof(UInt32) || type == typeof(UInt16) || type == typeof(byte) || type == typeof(sbyte); } /// <summary> /// Convert an argument list to the required paramter types. /// Currently, only widening numeric conversions are performed. /// </summary> /// <param name="arglist">An array of args to be converted</param> /// <param name="parameters">A ParamterInfo[] whose types will be used as targets</param> public static void ConvertArgumentList(object[] arglist, ParameterInfo[] parameters) { System.Diagnostics.Debug.Assert(arglist.Length == parameters.Length); for (int i = 0; i < parameters.Length; i++) { object arg = arglist[i]; if (arg != null && arg is IConvertible) { Type argType = arg.GetType(); Type targetType = parameters[i].ParameterType; bool convert = false; if (argType != targetType && !argType.IsAssignableFrom(targetType)) { if (IsNumeric(argType) && IsNumeric(targetType)) { if (targetType == typeof(double) || targetType == typeof(float)) convert = arg is int || arg is long || arg is short || arg is byte || arg is sbyte; else if (targetType == typeof(long)) convert = arg is int || arg is short || arg is byte || arg is sbyte; else if (targetType == typeof(short)) convert = arg is byte || arg is sbyte; } } if (convert) arglist[i] = Convert.ChangeType(arg, targetType, System.Globalization.CultureInfo.InvariantCulture); } } } #if true /// <summary> /// Creates an instance of a generic Type using the supplied Type arguments /// </summary> /// <param name="type">The generic type to be specialized.</param> /// <param name="typeArgs">The type args.</param> /// <returns>An instance of the generic type.</returns> public static Type MakeGenericType(Type type, Type[] typeArgs) { // TODO: Add error handling return type.MakeGenericType(typeArgs); } /// <summary> /// Determines whether this instance can deduce type args for a generic type from the supplied arguments. /// </summary> /// <param name="type">The type to be examined.</param> /// <param name="arglist">The arglist.</param> /// <param name="typeArgsOut">The type args to be used.</param> /// <returns> /// <c>true</c> if this the provided args give sufficient information to determine the type args to be used; otherwise, <c>false</c>. /// </returns> public static bool CanDeduceTypeArgsFromArgs(Type type, object[] arglist, ref Type[] typeArgsOut) { Type[] typeParameters = type.GetGenericArguments(); foreach (ConstructorInfo ctor in type.GetConstructors()) { ParameterInfo[] parameters = ctor.GetParameters(); if (parameters.Length != arglist.Length) continue; Type[] typeArgs = new Type[typeParameters.Length]; for (int i = 0; i < typeArgs.Length; i++) { for (int j = 0; j < arglist.Length; j++) { if (parameters[j].ParameterType.Equals(typeParameters[i])) typeArgs[i] = TypeHelper.BestCommonType( typeArgs[i], arglist[j].GetType()); } if (typeArgs[i] == null) { typeArgs = null; break; } } if (typeArgs != null) { typeArgsOut = typeArgs; return true; } } return false; } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using EventStoreLite.Indexes; using EventStoreLite.IoC; using Raven.Abstractions.Data; using Raven.Client; using Raven.Client.Linq; namespace EventStoreLite { /// <summary> /// Represents the event store. Use this class to create event store sessions. /// Typically, an instance of this class should be a singleton in your application. /// </summary> public class EventStore { private static readonly object InitLock = new object(); private static bool initialized; private readonly IServiceLocator container; private IEnumerable<Type> readModelTypes; internal EventStore(IServiceLocator container) { if (container == null) throw new ArgumentNullException("container"); this.container = container; } /// <summary> /// Rebuilds all read models. This is a potentially lengthy operation! /// </summary> public static void ReplayEvents(IServiceLocator locator) { if (!initialized) throw new InvalidOperationException("The event store must be initialized before first usage."); IDocumentStore documentStore = null; try { documentStore = (IDocumentStore)locator.Resolve(typeof(IDocumentStore)); DoReplayEvents(locator, documentStore); } finally { if (documentStore != null) locator.Release(documentStore); } } /// <summary> /// Initialize the event store. This will create the necessary /// indexes. This method can be called several times. /// </summary> /// <param name="documentStore">Document store.</param> /// <returns>Event store instance.</returns> /// <exception cref="ArgumentNullException"></exception> public EventStore Initialize(IDocumentStore documentStore) { if (documentStore == null) throw new ArgumentNullException("documentStore"); DoInitialize(documentStore); return this; } /// <summary> /// Opens a new event store session. /// </summary> /// <param name="documentStore">Document store.</param> /// <param name="session">Document session.</param> /// <returns>Event store session.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidOperationException"></exception> public IEventStoreSession OpenSession(IDocumentStore documentStore, IDocumentSession session) { if (!initialized) throw new InvalidOperationException("The event store must be initialized before first usage."); if (documentStore == null) throw new ArgumentNullException("documentStore"); if (session == null) throw new ArgumentNullException("session"); return new EventStoreSession(documentStore, session, new EventDispatcher(container)); } /// <summary> /// Migrates all store events. This will simply pass all events from all aggregates /// into the specified migrators. There is a chance of events coming in the wrong /// order, so don't rely on them coming in the order they were raised. They will, /// however, come in the correct order for each individual aggregate. /// </summary> /// <param name="eventMigrators">Event migrators.</param> /// <exception cref="ArgumentNullException"></exception> public void MigrateEvents(IEnumerable<IEventMigrator> eventMigrators) { if (!initialized) throw new InvalidOperationException("The event store must be initialized before first usage."); if (eventMigrators == null) throw new ArgumentNullException("eventMigrators"); // order by defined date eventMigrators = eventMigrators.OrderBy(x => x.DefinedOn()).ToList(); var current = 0; while (true) { var session = (IDocumentSession)container.Resolve(typeof(IDocumentSession)); try { // allow indexing to take its time var q = session.Query<EventStream>() .Customize(x => x.WaitForNonStaleResultsAsOf(DateTime.Now.AddSeconds(15))); var eventStreams = q.Skip(current).Take(128).ToList(); if (eventStreams.Count == 0) break; foreach (var eventStream in eventStreams) { var newHistory = new List<IDomainEvent>(); foreach (var domainEvent in eventStream.History) { var oldEvents = new List<IDomainEvent> { domainEvent }; foreach (var eventMigrator in eventMigrators) { var newEvents = new List<IDomainEvent>(); foreach (var migratedEvent in oldEvents) { newEvents.AddRange(eventMigrator.Migrate(migratedEvent, eventStream.Id)); } oldEvents = newEvents; } newHistory.AddRange(oldEvents); } eventStream.History = newHistory; } session.SaveChanges(); current += eventStreams.Count; } finally { container.Release(session); } } } internal EventStore SetReadModelTypes(IEnumerable<Type> types) { if (types == null) throw new ArgumentNullException("types"); readModelTypes = types; return this; } private static void DoReplayEvents(IServiceLocator locator, IDocumentStore documentStore) { // wait for indexing to complete WaitForIndexing(documentStore); // delete all read models documentStore.DatabaseCommands.DeleteByIndex("ReadModelIndex", new IndexQuery()); // load all event streams and dispatch events var dispatcher = new EventDispatcher(locator); var current = 0; while (true) { IDocumentSession session = null; try { session = (IDocumentSession)locator.Resolve(typeof(IDocumentSession)); var eventsQuery = session.Query<EventsIndex.Result, EventsIndex>() .Customize( x => x.WaitForNonStaleResultsAsOf(DateTime.Now.AddSeconds(15))) .OrderBy(x => x.ChangeSequence); var results = eventsQuery.Skip(current).Take(128).ToList(); if (results.Count == 0) break; foreach (var result in results) { var changeSequence = result.ChangeSequence; var ids = result.Id.Select(x => x.Id); var streams = session.Load<EventStream>(ids); var events = from stream in streams from @event in stream.History where @event.ChangeSequence == changeSequence orderby @event.TimeStamp select new { stream.Id, Event = @event }; foreach (var item in events) { dispatcher.Dispatch(item.Event, item.Id); } } session.SaveChanges(); current += results.Count; } finally { if (session != null) locator.Release(session); } } } private static void WaitForIndexing(IDocumentStore documentStore) { var indexingTask = Task.Factory.StartNew( () => { while (true) { var s = documentStore.DatabaseCommands.GetStatistics().StaleIndexes; if (!s.Contains("ReadModelIndex")) { break; } Thread.Sleep(500); } }); indexingTask.Wait(15000); } private void DoInitialize(IDocumentStore documentStore) { lock (InitLock) { new ReadModelIndex(readModelTypes).Execute(documentStore); new EventsIndex().Execute(documentStore); initialized = true; } } } }
using System; using System.Linq; using System.ComponentModel; using System.Diagnostics; #if __UNIFIED__ using Foundation; using UIKit; using RectangleF = CoreGraphics.CGRect; using SizeF = CoreGraphics.CGSize; using PointF = CoreGraphics.CGPoint; #else using System.Drawing; using MonoTouch.UIKit; using MonoTouch.Foundation; using nfloat=System.Single; using nint=System.Int32; using nuint=System.UInt32; #endif namespace Xamarin.Forms.Platform.iOS { public class ButtonRenderer : ViewRenderer<Button, UIButton> { UIColor _buttonTextColorDefaultDisabled; UIColor _buttonTextColorDefaultHighlighted; UIColor _buttonTextColorDefaultNormal; bool _titleChanged; SizeF _titleSize; // This looks like it should be a const under iOS Classic, // but that doesn't work under iOS // ReSharper disable once BuiltInTypeReferenceStyle // Under iOS Classic Resharper wants to suggest this use the built-in type ref // but under iOS that suggestion won't work readonly nfloat _minimumButtonHeight = 44; // Apple docs public override SizeF SizeThatFits(SizeF size) { var result = base.SizeThatFits(size); if (result.Height < _minimumButtonHeight) { result.Height = _minimumButtonHeight; } return result; } protected override void Dispose(bool disposing) { if (Control != null) Control.TouchUpInside -= OnButtonTouchUpInside; base.Dispose(disposing); } protected override void OnElementChanged(ElementChangedEventArgs<Button> e) { base.OnElementChanged(e); if (e.NewElement != null) { if (Control == null) { SetNativeControl(new UIButton(UIButtonType.RoundedRect)); Debug.Assert(Control != null, "Control != null"); _buttonTextColorDefaultNormal = Control.TitleColor(UIControlState.Normal); _buttonTextColorDefaultHighlighted = Control.TitleColor(UIControlState.Highlighted); _buttonTextColorDefaultDisabled = Control.TitleColor(UIControlState.Disabled); Control.TouchUpInside += OnButtonTouchUpInside; } UpdateText(); UpdateFont(); UpdateBorder(); UpdateImage(); UpdateTextColor(); } } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == Button.TextProperty.PropertyName) UpdateText(); else if (e.PropertyName == Button.TextColorProperty.PropertyName) UpdateTextColor(); else if (e.PropertyName == Button.FontProperty.PropertyName) UpdateFont(); else if (e.PropertyName == Button.BorderWidthProperty.PropertyName || e.PropertyName == Button.BorderRadiusProperty.PropertyName || e.PropertyName == Button.BorderColorProperty.PropertyName) UpdateBorder(); else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName) UpdateBackgroundVisibility(); else if (e.PropertyName == Button.ImageProperty.PropertyName) UpdateImage(); } void OnButtonTouchUpInside(object sender, EventArgs eventArgs) { ((IButtonController)Element)?.SendClicked(); } void UpdateBackgroundVisibility() { if (Forms.IsiOS7OrNewer) return; var model = Element; var shouldDrawImage = model.BackgroundColor == Color.Default; foreach (var control in Control.Subviews.Where(sv => !(sv is UILabel))) control.Alpha = shouldDrawImage ? 1.0f : 0.0f; } void UpdateBorder() { var uiButton = Control; var button = Element; if (button.BorderColor != Color.Default) uiButton.Layer.BorderColor = button.BorderColor.ToCGColor(); uiButton.Layer.BorderWidth = (float)button.BorderWidth; uiButton.Layer.CornerRadius = button.BorderRadius; UpdateBackgroundVisibility(); } void UpdateFont() { Control.TitleLabel.Font = Element.ToUIFont(); } async void UpdateImage() { IImageSourceHandler handler; FileImageSource source = Element.Image; if (source != null && (handler = Registrar.Registered.GetHandler<IImageSourceHandler>(source.GetType())) != null) { UIImage uiimage; try { uiimage = await handler.LoadImageAsync(source, scale: (float)UIScreen.MainScreen.Scale); } catch (OperationCanceledException) { uiimage = null; } UIButton button = Control; if (button != null && uiimage != null) { if (Forms.IsiOS7OrNewer) button.SetImage(uiimage.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), UIControlState.Normal); else button.SetImage(uiimage, UIControlState.Normal); button.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; ComputeEdgeInsets(Control, Element.ContentLayout); } } else { Control.SetImage(null, UIControlState.Normal); ClearEdgeInsets(Control); } ((IVisualElementController)Element).NativeSizeChanged(); } void UpdateText() { var newText = Element.Text; if (Control.Title(UIControlState.Normal) != newText) { Control.SetTitle(Element.Text, UIControlState.Normal); _titleChanged = true; } } void UpdateTextColor() { if (Element.TextColor == Color.Default) { Control.SetTitleColor(_buttonTextColorDefaultNormal, UIControlState.Normal); Control.SetTitleColor(_buttonTextColorDefaultHighlighted, UIControlState.Highlighted); Control.SetTitleColor(_buttonTextColorDefaultDisabled, UIControlState.Disabled); } else { Control.SetTitleColor(Element.TextColor.ToUIColor(), UIControlState.Normal); Control.SetTitleColor(Element.TextColor.ToUIColor(), UIControlState.Highlighted); Control.SetTitleColor(_buttonTextColorDefaultDisabled, UIControlState.Disabled); if (Forms.IsiOS7OrNewer) Control.TintColor = Element.TextColor.ToUIColor(); } } void ClearEdgeInsets(UIButton button) { if (button == null) { return; } Control.ImageEdgeInsets = new UIEdgeInsets(0, 0, 0, 0); Control.TitleEdgeInsets = new UIEdgeInsets(0, 0, 0, 0); Control.ContentEdgeInsets = new UIEdgeInsets(0, 0, 0, 0); } void ComputeEdgeInsets(UIButton button, Button.ButtonContentLayout layout) { if (button?.ImageView?.Image == null || string.IsNullOrEmpty(button.TitleLabel?.Text)) { return; } var position = layout.Position; var spacing = (nfloat)(layout.Spacing / 2); if (position == Button.ButtonContentLayout.ImagePosition.Left) { button.ImageEdgeInsets = new UIEdgeInsets(0, -spacing, 0, spacing); button.TitleEdgeInsets = new UIEdgeInsets(0, spacing, 0, -spacing); button.ContentEdgeInsets = new UIEdgeInsets(0, 2 * spacing, 0, 2 * spacing); return; } if (_titleChanged) { var stringToMeasure = new NSString(button.TitleLabel.Text); UIStringAttributes attribs = new UIStringAttributes { Font = button.TitleLabel.Font }; _titleSize = stringToMeasure.GetSizeUsingAttributes(attribs); _titleChanged = false; } var labelWidth = _titleSize.Width; var imageWidth = button.ImageView.Image.Size.Width; if (position == Button.ButtonContentLayout.ImagePosition.Right) { button.ImageEdgeInsets = new UIEdgeInsets(0, labelWidth + spacing, 0, -labelWidth - spacing); button.TitleEdgeInsets = new UIEdgeInsets(0, -imageWidth - spacing, 0, imageWidth + spacing); button.ContentEdgeInsets = new UIEdgeInsets(0, 2 * spacing, 0, 2 * spacing); return; } var imageVertOffset = (_titleSize.Height / 2); var titleVertOffset = (button.ImageView.Image.Size.Height / 2); var edgeOffset = (float)Math.Min(imageVertOffset, titleVertOffset); button.ContentEdgeInsets = new UIEdgeInsets(edgeOffset, 0, edgeOffset, 0); var horizontalImageOffset = labelWidth / 2; var horizontalTitleOffset = imageWidth / 2; if (position == Button.ButtonContentLayout.ImagePosition.Bottom) { imageVertOffset = -imageVertOffset; titleVertOffset = -titleVertOffset; } button.ImageEdgeInsets = new UIEdgeInsets(-imageVertOffset, horizontalImageOffset, imageVertOffset, -horizontalImageOffset); button.TitleEdgeInsets = new UIEdgeInsets(titleVertOffset, -horizontalTitleOffset, -titleVertOffset, horizontalTitleOffset); } } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Mapping { /// <summary> /// Creates the tabs collection with properties assigned for display models /// </summary> internal class TabsAndPropertiesResolver<TSource> : IValueResolver where TSource : IContentBase { private readonly ILocalizedTextService _localizedTextService; protected IEnumerable<string> IgnoreProperties { get; set; } public TabsAndPropertiesResolver(ILocalizedTextService localizedTextService) { if (localizedTextService == null) throw new ArgumentNullException("localizedTextService"); _localizedTextService = localizedTextService; IgnoreProperties = new List<string>(); } public TabsAndPropertiesResolver(ILocalizedTextService localizedTextService, IEnumerable<string> ignoreProperties) : this(localizedTextService) { if (ignoreProperties == null) throw new ArgumentNullException("ignoreProperties"); IgnoreProperties = ignoreProperties; } /// <summary> /// Implements the <see cref="IValueResolver"/> /// </summary> /// <param name="source"></param> /// <returns></returns> public ResolutionResult Resolve(ResolutionResult source) { if (source.Value != null && (source.Value is TSource) == false) throw new AutoMapperMappingException(string.Format("Value supplied is of type {0} but expected {1}.\nChange the value resolver source type, or redirect the source value supplied to the value resolver using FromMember.", new object[] { source.Value.GetType(), typeof (TSource) })); return source.New( //perform the mapping with the current umbraco context ResolveCore(source.Context.GetUmbracoContext(), (TSource)source.Value), typeof(List<Tab<ContentPropertyDisplay>>)); } /// <summary> /// Adds the container (listview) tab to the document /// </summary> /// <typeparam name="TPersisted"></typeparam> /// <param name="display"></param> /// <param name="entityType">This must be either 'content' or 'media'</param> /// <param name="dataTypeService"></param> /// <param name="localizedTextService"></param> internal static void AddListView<TPersisted>(TabbedContentItem<ContentPropertyDisplay, TPersisted> display, string entityType, IDataTypeService dataTypeService, ILocalizedTextService localizedTextService) where TPersisted : IContentBase { int dtdId; var customDtdName = Constants.Conventions.DataTypes.ListViewPrefix + display.ContentTypeAlias; switch (entityType) { case "content": dtdId = Constants.System.DefaultContentListViewDataTypeId; break; case "media": dtdId = Constants.System.DefaultMediaListViewDataTypeId; break; case "member": dtdId = Constants.System.DefaultMembersListViewDataTypeId; break; default: throw new ArgumentOutOfRangeException("entityType does not match a required value"); } //first try to get the custom one if there is one var dt = dataTypeService.GetDataTypeDefinitionByName(customDtdName) ?? dataTypeService.GetDataTypeDefinitionById(dtdId); if (dt == null) { throw new InvalidOperationException("No list view data type was found for this document type, ensure that the default list view data types exists and/or that your custom list view data type exists"); } var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dt.Id); var editor = PropertyEditorResolver.Current.GetByAlias(dt.PropertyEditorAlias); if (editor == null) { throw new NullReferenceException("The property editor with alias " + dt.PropertyEditorAlias + " does not exist"); } var listViewTab = new Tab<ContentPropertyDisplay>(); listViewTab.Alias = Constants.Conventions.PropertyGroups.ListViewGroupName; listViewTab.Label = localizedTextService.Localize("content/childItems"); listViewTab.Id = display.Tabs.Count() + 1; listViewTab.IsActive = true; var listViewConfig = editor.PreValueEditor.ConvertDbToEditor(editor.DefaultPreValues, preVals); //add the entity type to the config listViewConfig["entityType"] = entityType; //Override Tab Label if tabName is provided if (listViewConfig.ContainsKey("tabName")) { var configTabName = listViewConfig["tabName"]; if (configTabName != null && string.IsNullOrWhiteSpace(configTabName.ToString()) == false) listViewTab.Label = configTabName.ToString(); } var listViewProperties = new List<ContentPropertyDisplay>(); listViewProperties.Add(new ContentPropertyDisplay { Alias = string.Format("{0}containerView", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = "", Value = null, View = editor.ValueEditor.View, HideLabel = true, Config = listViewConfig }); listViewTab.Properties = listViewProperties; SetChildItemsTabPosition(display, listViewConfig, listViewTab); } private static void SetChildItemsTabPosition<TPersisted>(TabbedContentItem<ContentPropertyDisplay, TPersisted> display, IDictionary<string, object> listViewConfig, Tab<ContentPropertyDisplay> listViewTab) where TPersisted : IContentBase { // Find position of tab from config var tabIndexForChildItems = 0; if (listViewConfig["displayAtTabNumber"] != null && int.TryParse((string)listViewConfig["displayAtTabNumber"], out tabIndexForChildItems)) { // Tab position is recorded 1-based but we insert into collection 0-based tabIndexForChildItems--; // Ensure within bounds if (tabIndexForChildItems < 0) { tabIndexForChildItems = 0; } if (tabIndexForChildItems > display.Tabs.Count()) { tabIndexForChildItems = display.Tabs.Count(); } } // Recreate tab list with child items tab at configured position var tabs = new List<Tab<ContentPropertyDisplay>>(); tabs.AddRange(display.Tabs); tabs.Insert(tabIndexForChildItems, listViewTab); display.Tabs = tabs; } /// <summary> /// Create the list of tabs for the <see cref="IContentBase"/> /// </summary> /// <param name="umbracoContext"></param> /// <param name="content">Source value</param> /// <returns>Destination</returns> protected virtual List<Tab<ContentPropertyDisplay>> ResolveCore(UmbracoContext umbracoContext, TSource content) { var tabs = new List<Tab<ContentPropertyDisplay>>(); // add the tabs, for properties that belong to a tab // need to aggregate the tabs, as content.PropertyGroups contains all the composition tabs, // and there might be duplicates (content does not work like contentType and there is no // content.CompositionPropertyGroups). var groupsGroupsByName = content.PropertyGroups.OrderBy(x => x.SortOrder).GroupBy(x => x.Name); foreach (var groupsByName in groupsGroupsByName) { var properties = new List<Property>(); // merge properties for groups with the same name foreach (var group in groupsByName) { var groupProperties = content.GetPropertiesForGroup(group) .Where(x => IgnoreProperties.Contains(x.Alias) == false); // skip ignored properties.AddRange(groupProperties); } if (properties.Count == 0) continue; //map the properties var mappedProperties = MapProperties(umbracoContext, content, properties); // add the tab // we need to pick an identifier... there is no "right" way... var g = groupsByName.FirstOrDefault(x => x.Id == content.ContentTypeId) // try local ?? groupsByName.First(); // else pick one randomly var groupId = g.Id; var groupName = groupsByName.Key; tabs.Add(new Tab<ContentPropertyDisplay> { Id = groupId, Alias = groupName, Label = _localizedTextService.UmbracoDictionaryTranslate(groupName), Properties = mappedProperties, IsActive = false }); } MapGenericProperties(umbracoContext, content, tabs); // activate the first tab if (tabs.Count > 0) tabs[0].IsActive = true; return tabs; } /// <summary> /// Returns a collection of custom generic properties that exist on the generic properties tab /// </summary> /// <returns></returns> protected virtual IEnumerable<ContentPropertyDisplay> GetCustomGenericProperties(IContentBase content) { return Enumerable.Empty<ContentPropertyDisplay>(); } /// <summary> /// Maps properties on to the generic properties tab /// </summary> /// <param name="umbracoContext"></param> /// <param name="content"></param> /// <param name="tabs"></param> /// <remarks> /// The generic properties tab is responsible for /// setting up the properties such as Created date, updated date, template selected, etc... /// </remarks> protected virtual void MapGenericProperties(UmbracoContext umbracoContext, IContentBase content, List<Tab<ContentPropertyDisplay>> tabs) { // add the generic properties tab, for properties that don't belong to a tab // get the properties, map and translate them, then add the tab var noGroupProperties = content.GetNonGroupedProperties() .Where(x => IgnoreProperties.Contains(x.Alias) == false) // skip ignored .ToList(); var genericproperties = MapProperties(umbracoContext, content, noGroupProperties); tabs.Add(new Tab<ContentPropertyDisplay> { Id = 0, Label = _localizedTextService.Localize("general/properties"), Alias = "Generic properties", Properties = genericproperties }); var genericProps = tabs.Single(x => x.Id == 0); //store the current props to append to the newly inserted ones var currProps = genericProps.Properties.ToArray(); var contentProps = new List<ContentPropertyDisplay>(); var customProperties = GetCustomGenericProperties(content); if (customProperties != null) { //add the custom ones contentProps.AddRange(customProperties); } //now add the user props contentProps.AddRange(currProps); //re-assign genericProps.Properties = contentProps; //Show or hide properties tab based on wether it has or not any properties if (genericProps.Properties.Any() == false) { //loop throug the tabs, remove the one with the id of zero and exit the loop for (var i = 0; i < tabs.Count; i++) { if (tabs[i].Id != 0) continue; tabs.RemoveAt(i); break; } } } /// <summary> /// Maps a list of <see cref="Property"/> to a list of <see cref="ContentPropertyDisplay"/> /// </summary> /// <param name="umbracoContext"></param> /// <param name="content"></param> /// <param name="properties"></param> /// <returns></returns> protected virtual List<ContentPropertyDisplay> MapProperties(UmbracoContext umbracoContext, IContentBase content, List<Property> properties) { var result = Mapper.Map<IEnumerable<Property>, IEnumerable<ContentPropertyDisplay>>( // Sort properties so items from different compositions appear in correct order (see U4-9298). Map sorted properties. properties.OrderBy(prop => prop.PropertyType.SortOrder)) .ToList(); return result; } } }
using System; using System.Diagnostics; using System.Globalization; using System.Net; using System.Threading; using Orleans.AzureUtils; using Orleans.Runtime.Configuration; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Logging; using Orleans.AzureUtils.Utilities; using Orleans.Hosting.AzureCloudServices; using Orleans.Hosting; namespace Orleans.Runtime.Host { /// <summary> /// Wrapper class for an Orleans silo running in the current host process. /// </summary> public class AzureSilo { /// <summary> /// Amount of time to pause before retrying if a secondary silo is unable to connect to the primary silo for this deployment. /// Defaults to 5 seconds. /// </summary> public TimeSpan StartupRetryPause { get; set; } /// <summary> /// Number of times to retrying if a secondary silo is unable to connect to the primary silo for this deployment. /// Defaults to 120 times. /// </summary> public int MaxRetries { get; set; } /// <summary> /// The name of the configuration key value for locating the DataConnectionString setting from the Azure configuration for this role. /// Defaults to <c>DataConnectionString</c> /// </summary> public string DataConnectionConfigurationSettingName { get; set; } /// <summary> /// The name of the configuration key value for locating the OrleansSiloEndpoint setting from the Azure configuration for this role. /// Defaults to <c>OrleansSiloEndpoint</c> /// </summary> public string SiloEndpointConfigurationKeyName { get; set; } /// <summary> /// The name of the configuration key value for locating the OrleansProxyEndpoint setting from the Azure configuration for this role. /// Defaults to <c>OrleansProxyEndpoint</c> /// </summary> public string ProxyEndpointConfigurationKeyName { get; set; } /// <summary>delegate to add some configuration to the client</summary> public Action<ISiloHostBuilder> ConfigureSiloHostDelegate { get; set; } private SiloHost host; private OrleansSiloInstanceManager siloInstanceManager; private SiloInstanceTableEntry myEntry; private readonly ILogger logger; private readonly IServiceRuntimeWrapper serviceRuntimeWrapper; //TODO: hook this up with SiloBuilder when SiloBuilder supports create AzureSilo private static ILoggerFactory DefaultLoggerFactory = CreateDefaultLoggerFactory("AzureSilo.log"); private readonly ILoggerFactory loggerFactory = DefaultLoggerFactory; public AzureSilo() :this(new ServiceRuntimeWrapper(DefaultLoggerFactory), DefaultLoggerFactory) { } /// <summary> /// Constructor /// </summary> public AzureSilo(ILoggerFactory loggerFactory) : this(new ServiceRuntimeWrapper(loggerFactory), loggerFactory) { } public static ILoggerFactory CreateDefaultLoggerFactory(string filePath) { var factory = new LoggerFactory(); factory.AddProvider(new FileLoggerProvider(filePath)); if (ConsoleText.IsConsoleAvailable) factory.AddConsole(); return factory; } internal AzureSilo(IServiceRuntimeWrapper serviceRuntimeWrapper, ILoggerFactory loggerFactory) { this.serviceRuntimeWrapper = serviceRuntimeWrapper; DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName; SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName; ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName; StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes this.loggerFactory = loggerFactory; logger = loggerFactory.CreateLogger<AzureSilo>(); } /// <summary> /// Async method to validate specific cluster configuration /// </summary> /// <param name="config"></param> /// <returns>Task object of boolean type for this async method </returns> public async Task<bool> ValidateConfiguration(ClusterConfiguration config) { if (config.Globals.LivenessType == GlobalConfiguration.LivenessProviderType.AzureTable) { string clusterId = config.Globals.ClusterId ?? serviceRuntimeWrapper.DeploymentId; string connectionString = config.Globals.DataConnectionString ?? serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName); try { var manager = siloInstanceManager ?? await OrleansSiloInstanceManager.GetManager(clusterId, connectionString, loggerFactory); var instances = await manager.DumpSiloInstanceTable(); logger.Debug(instances); } catch (Exception exc) { var error = String.Format("Connecting to the storage table has failed with {0}", LogFormatter.PrintException(exc)); Trace.TraceError(error); logger.Error((int)AzureSiloErrorCode.AzureTable_34, error, exc); return false; } } return true; } /// <summary> /// Default cluster configuration /// </summary> /// <returns>Default ClusterConfiguration </returns> public static ClusterConfiguration DefaultConfiguration() { return DefaultConfiguration(new ServiceRuntimeWrapper(DefaultLoggerFactory)); } internal static ClusterConfiguration DefaultConfiguration(IServiceRuntimeWrapper serviceRuntimeWrapper) { var config = new ClusterConfiguration(); config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable; config.Globals.ClusterId = serviceRuntimeWrapper.DeploymentId; try { config.Globals.DataConnectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName); } catch (Exception exc) { if (exc.GetType().Name.Contains("RoleEnvironmentException")) { config.Globals.DataConnectionString = null; } else { throw; } } return config; } #region Azure RoleEntryPoint methods /// <summary> /// Initialize this Orleans silo for execution. Config data will be read from silo config file as normal /// </summary> /// <param name="deploymentId">Azure ClusterId this silo is running under. If null, defaults to the value from the configuration.</param> /// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param> /// <returns><c>true</c> is the silo startup was successful</returns> public bool Start(string deploymentId = null, string connectionString = null) { return Start(null, deploymentId, connectionString); } /// <summary> /// Initialize this Orleans silo for execution /// </summary> /// <param name="config">Use the specified config data.</param> /// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param> /// <returns><c>true</c> is the silo startup was successful</returns> public bool Start(ClusterConfiguration config, string connectionString = null) { if (config == null) throw new ArgumentNullException(nameof(config)); return Start(config, null, connectionString); } /// <summary> /// Initialize this Orleans silo for execution with the specified Azure clusterId /// </summary> /// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param> /// <param name="clusterId">Azure ClusterId this silo is running under</param> /// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param> /// <returns><c>true</c> if the silo startup was successful</returns> internal bool Start(ClusterConfiguration config, string clusterId, string connectionString) { if (config != null && clusterId != null) throw new ArgumentException("Cannot use config and clusterId on the same time"); // Program ident Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current); // Read endpoint info for this instance from Azure config string instanceName = serviceRuntimeWrapper.InstanceName; // Configure this Orleans silo instance if (config == null) { host = new SiloHost(instanceName); host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations } else { host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations } IPEndPoint myEndpoint = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName); IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName); host.SetSiloType(Silo.SiloType.Secondary); int generation = SiloAddress.AllocateNewGeneration(); // Bootstrap this Orleans silo instance // If clusterId was not direclty provided, take the value in the config. If it is not // in the config too, just take the ClusterId from Azure if (clusterId == null) clusterId = string.IsNullOrWhiteSpace(host.Config.Globals.ClusterId) ? serviceRuntimeWrapper.DeploymentId : host.Config.Globals.ClusterId; myEntry = new SiloInstanceTableEntry { DeploymentId = clusterId, Address = myEndpoint.Address.ToString(), Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture), Generation = generation.ToString(CultureInfo.InvariantCulture), HostName = host.Config.GetOrCreateNodeConfigurationForSilo(host.Name).DNSHostName, ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture), RoleName = serviceRuntimeWrapper.RoleName, SiloName = instanceName, UpdateZone = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture), FaultZone = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture), StartTime = LogFormatter.PrintDate(DateTime.UtcNow), PartitionKey = clusterId, RowKey = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation }; if (connectionString == null) connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName); try { siloInstanceManager = OrleansSiloInstanceManager.GetManager( clusterId, connectionString, this.loggerFactory).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result; } catch (Exception exc) { var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}", LogFormatter.PrintException(exc)); Trace.TraceError(error); logger.Error((int)AzureSiloErrorCode.AzureTable_34, error, exc); throw new OrleansException(error, exc); } // Always use Azure table for membership when running silo in Azure host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable); if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified || host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain) { host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable); } host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount); siloInstanceManager.RegisterSiloInstance(myEntry); // Initialize this Orleans silo instance host.SetDeploymentId(clusterId, connectionString); host.SetSiloEndpoint(myEndpoint, generation); host.SetProxyEndpoint(proxyEndpoint); host.ConfigureSiloHostDelegate = ConfigureSiloHostDelegate; host.InitializeOrleansSilo(); return StartSilo(); } /// <summary> /// Makes this Orleans silo begin executing and become active. /// Note: This method call will only return control back to the caller when the silo is shutdown. /// </summary> public void Run() { RunImpl(); } /// <summary> /// Makes this Orleans silo begin executing and become active. /// Note: This method call will only return control back to the caller when the silo is shutdown or /// an external request for cancellation has been issued. /// </summary> /// <param name="cancellationToken">Cancellation token.</param> public void Run(CancellationToken cancellationToken) { RunImpl(cancellationToken); } /// <summary> /// Stop this Orleans silo executing. /// </summary> public void Stop() { logger.Info(ErrorCode.Runtime_Error_100290, "Stopping {0}", this.GetType().FullName); serviceRuntimeWrapper.UnsubscribeFromStoppingNotification(this, HandleAzureRoleStopping); host.ShutdownOrleansSilo(); logger.Info(ErrorCode.Runtime_Error_100291, "Orleans silo '{0}' shutdown.", host.Name); } #endregion private bool StartSilo() { logger.Info(ErrorCode.Runtime_Error_100292, "Starting Orleans silo '{0}' as a {1} node.", host.Name, host.Type); bool ok = host.StartOrleansSilo(); if (ok) logger.Info(ErrorCode.Runtime_Error_100293, "Successfully started Orleans silo '{0}' as a {1} node.", host.Name, host.Type); else logger.Error(ErrorCode.Runtime_Error_100285, string.Format("Failed to start Orleans silo '{0}' as a {1} node.", host.Name, host.Type)); return ok; } private void HandleAzureRoleStopping(object sender, object e) { // Try to perform gracefull shutdown of Silo when we detect Azure role instance is being stopped logger.Info(ErrorCode.SiloStopping, "HandleAzureRoleStopping - starting to shutdown silo"); host.ShutdownOrleansSilo(); } /// <summary> /// Run method helper. /// </summary> /// <remarks> /// Makes this Orleans silo begin executing and become active. /// Note: This method call will only return control back to the caller when the silo is shutdown or /// an external request for cancellation has been issued. /// </remarks> /// <param name="cancellationToken">Optional cancellation token.</param> private void RunImpl(CancellationToken? cancellationToken = null) { logger.Info(ErrorCode.Runtime_Error_100289, "OrleansAzureHost entry point called"); // Hook up to receive notification of Azure role stopping events serviceRuntimeWrapper.SubscribeForStoppingNotification(this, HandleAzureRoleStopping); if (host.IsStarted) { if (cancellationToken.HasValue) host.WaitForOrleansSiloShutdown(cancellationToken.Value); else host.WaitForOrleansSiloShutdown(); } else throw new Exception("Silo failed to start correctly - aborting"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using CRP.Controllers.Filter; using CRP.Controllers.ViewModels; using CRP.Core.Domain; using CRP.Core.Resources; using CRP.Mvc.Controllers.ViewModels; using MvcContrib.Attributes; using UCDArch.Web.Controller; using UCDArch.Web.Validator; using MvcContrib; //using CRP.App_GlobalResources; namespace CRP.Controllers { [AdminOnlyAttribute] public class ApplicationManagementController : ApplicationController { // // GET: /ApplicationManagement/ /// <summary> /// Tested 20200415 /// </summary> /// <returns></returns> public ActionResult Index() { return View(); } #region Item Types /// <summary> /// GET: /ApplicationManagement/ListItemTypes /// Tested 20200415 (Fixed VIew) /// </summary> /// <returns></returns> public ActionResult ListItemTypes() { return View(Repository.OfType<ItemType>().Queryable.ToArray()); } /// <summary> /// GET: /ApplicationManagement/CreateItemType /// Tested 20200415 /// </summary> /// <returns></returns> public ActionResult CreateItemType() { return View(ItemTypeViewModel.Create(Repository)); } /// <summary> /// POST: /ApplicationManagement/CreateItemType /// </summary> /// <remarks> /// Description: /// Creates a new item type with defined extended properties /// PreCondition: /// Item type with same name doesn't already exist /// PostCondition: /// Item is created /// Extended properties passed in are saved /// Tested 20200415 /// </remarks> /// <param name="itemType"></param> /// <param name="extendedProperties"></param> /// <returns></returns> [HttpPost] public ActionResult CreateItemType(ItemType itemType, ExtendedProperty[] extendedProperties) { ModelState.Clear(); //foreach (var ep in extendedProperties) //{ // ep.ItemType = itemType; // if (ep.IsValid()) // { // itemType.AddExtendedProperty(ep); // } // else // { // ModelState.AddModelError("ExtendedProperty", "At least one extended property is not valid."); // } //} if (extendedProperties != null) { var duplicateCheck = new List<string>(); foreach (var list in extendedProperties) { if (duplicateCheck.Contains(list.Name)) { ModelState.AddModelError("ExtendedProperty", "Duplicate names not allowed. Extended property \"" + list.Name + "\" already exists."); break; } duplicateCheck.Add(list.Name); } } //Validation is done in the domain if (extendedProperties != null) { foreach (var ep in extendedProperties) { ep.ItemType = itemType; itemType.AddExtendedProperty(ep); } } MvcValidationAdapter.TransferValidationMessagesTo(ModelState, itemType.ValidationResults()); // make sure the item type doesn't already exist with the same name if (Repository.OfType<ItemType>().Queryable.Where(a => a.Name == itemType.Name).Any()) { // name already exists, we have a problem ModelState.AddModelError("Name", "A item type of the same name already exists."); } if (ModelState.IsValid) { Repository.OfType<ItemType>().EnsurePersistent(itemType); Message = NotificationMessages.STR_ObjectCreated.Replace(NotificationMessages.ObjectType, "Item Type"); return this.RedirectToAction(a => a.ListItemTypes()); } else { var viewModel = ItemTypeViewModel.Create(Repository); viewModel.ItemType = itemType; return View(viewModel); } } /// <summary> /// GET: /ApplicationManagement/EditItemType/{id} /// </summary> /// <param name="id"></param> /// Tested 20200416 Fixed formatting /// <returns></returns> public ActionResult EditItemType(int id) { var itemType = Repository.OfType<ItemType>().GetNullableById(id); if (itemType != null) { return View(itemType); } else { return this.RedirectToAction(a => a.ListItemTypes()); } } /// <summary> /// POST: /ApplicationManagement/EditItemType /// </summary> /// <remarks> /// Description: /// Saves the name and the is active flag /// PreCondition: /// The item type exists /// PostCondition: /// The item is updated /// </remarks> /// <param name="id"></param> /// <param name="itemType"></param> /// <returns></returns> [HttpPost] public ActionResult EditItemType(int id, [Bind(Exclude="Id")]ItemType itemType) { ModelState.Clear(); var it = Repository.OfType<ItemType>().GetNullableById(id); if (it == null) { return this.RedirectToAction(a => a.ListItemTypes()); } it.Name = itemType.Name; it.IsActive = itemType.IsActive; //Done: Review. I think this needs to pass in the id, get it, //copy over the fields which are edited, then check and persist that. //As the name should not be duplicate, that check would need to be added. MvcValidationAdapter.TransferValidationMessagesTo(ModelState, it.ValidationResults()); if (Repository.OfType<ItemType>().Queryable.Where(a => a.Name == it.Name && a.Id != id).Any()) { ModelState.AddModelError("Name", "The new name already exists with a different item type."); } if (ModelState.IsValid) { Repository.OfType<ItemType>().EnsurePersistent(it); Message = NotificationMessages.STR_ObjectSaved.Replace(NotificationMessages.ObjectType, "Item Type"); return View(it); //Display the updated itemType, not the passed itemType } else { return View(it); //Display the updated itemType, not the passed itemType } } /// <summary> /// Tested 20200416 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpPost] public ActionResult ToggleActive(int id) { var itemType = Repository.OfType<ItemType>().GetNullableById(id); if (itemType == null) { return this.RedirectToAction(a => a.ListItemTypes()); } itemType.IsActive = !itemType.IsActive; MvcValidationAdapter.TransferValidationMessagesTo(ModelState, itemType.ValidationResults()); if (ModelState.IsValid) { Repository.OfType<ItemType>().EnsurePersistent(itemType); Message = itemType.IsActive ? NotificationMessages.STR_Activated.Replace(NotificationMessages.ObjectType, "Item Type") : NotificationMessages.STR_Deactivated.Replace(NotificationMessages.ObjectType, "Item Type"); } return this.RedirectToAction(a => a.ListItemTypes()); } #endregion public ActionResult ViewUnCleared() { var compareDate = DateTime.UtcNow.AddDays(-5); //TODO: add in a date check to give it a few days to process var unclearedPaymentLogs = Repository.OfType<PaymentLog>().Queryable .Where(a => a.Credit && !a.Cleared && a.Accepted && a.ReturnedResults != null).Select(a => new UnclearedModel { Id = a.Id, Name = a.Name, Amount = a.Amount, DatePayment = a.DatePayment, Transaction = a.Transaction, GatewayTransactionId = a.GatewayTransactionId, TnPaymentDate = a.TnPaymentDate, IsOld = a.DatePayment < compareDate }).ToArray(); return View(unclearedPaymentLogs); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Osp; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveReadRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected TarArchiveReader archive; private CachedUserInfo m_userInfo; private string m_invPath; /// <value> /// We only use this to request modules /// </value> protected Scene m_scene; /// <value> /// The stream from which the inventory archive will be loaded. /// </value> private Stream m_loadStream; public InventoryArchiveReadRequest( Scene scene, CachedUserInfo userInfo, string invPath, string loadPath) : this( scene, userInfo, invPath, new GZipStream(new FileStream(loadPath, FileMode.Open), CompressionMode.Decompress)) { } public InventoryArchiveReadRequest( Scene scene, CachedUserInfo userInfo, string invPath, Stream loadStream) { m_scene = scene; m_userInfo = userInfo; m_invPath = invPath; m_loadStream = loadStream; } /// <summary> /// Execute the request /// </summary> /// <returns> /// A list of the inventory nodes loaded. If folders were loaded then only the root folders are /// returned /// </returns> public List<InventoryNodeBase> Execute() { string filePath = "ERROR"; int successfulAssetRestores = 0; int failedAssetRestores = 0; int successfulItemRestores = 0; List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>(); //InventoryFolderImpl rootDestinationFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath); InventoryFolderBase rootDestinationFolder = InventoryArchiveUtils.FindFolderByPath( m_scene.InventoryService, m_userInfo.UserProfile.ID, m_invPath); if (null == rootDestinationFolder) { // Possibly provide an option later on to automatically create this folder if it does not exist m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath); return nodesLoaded; } archive = new TarArchiveReader(m_loadStream); // In order to load identically named folders, we need to keep track of the folders that we have already // created Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>(); byte[] data; TarArchiveReader.TarEntryType entryType; try { while ((data = archive.ReadEntry(out filePath, out entryType)) != null) { if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { if (LoadAsset(filePath, data)) successfulAssetRestores++; else failedAssetRestores++; if ((successfulAssetRestores) % 50 == 0) m_log.DebugFormat( "[INVENTORY ARCHIVER]: Loaded {0} assets...", successfulAssetRestores); } else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH)) { InventoryFolderBase foundFolder = ReplicateArchivePathToUserInventory( filePath, TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType, rootDestinationFolder, foldersCreated, nodesLoaded); if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) { InventoryItemBase item = LoadItem(data, foundFolder); if (item != null) { successfulItemRestores++; // If we're loading an item directly into the given destination folder then we need to record // it separately from any loaded root folders if (rootDestinationFolder == foundFolder) nodesLoaded.Add(item); } } } } } finally { archive.Close(); } m_log.DebugFormat( "[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures", successfulAssetRestores, failedAssetRestores); m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", successfulItemRestores); return nodesLoaded; } public void Close() { if (m_loadStream != null) m_loadStream.Close(); } /// <summary> /// Replicate the inventory paths in the archive to the user's inventory as necessary. /// </summary> /// <param name="archivePath">The item archive path to replicate</param> /// <param name="isDir">Is the path we're dealing with a directory?</param> /// <param name="rootDestinationFolder">The root folder for the inventory load</param> /// <param name="foldersCreated"> /// The folders created so far. This method will add more folders if necessary /// </param> /// <param name="nodesLoaded"> /// Track the inventory nodes created. This is distinct from the folders created since for a particular folder /// chain, only the root node needs to be recorded /// </param> /// <returns>The last user inventory folder created or found for the archive path</returns> public InventoryFolderBase ReplicateArchivePathToUserInventory( string archivePath, bool isDir, InventoryFolderBase rootDestFolder, Dictionary <string, InventoryFolderBase> foldersCreated, List<InventoryNodeBase> nodesLoaded) { archivePath = archivePath.Substring(ArchiveConstants.INVENTORY_PATH.Length); // Remove the file portion if we aren't already dealing with a directory path if (!isDir) archivePath = archivePath.Remove(archivePath.LastIndexOf("/") + 1); string originalArchivePath = archivePath; // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID); InventoryFolderBase destFolder = null; // XXX: Nasty way of dealing with a path that has no directory component if (archivePath.Length > 0) { while (null == destFolder && archivePath.Length > 0) { if (foldersCreated.ContainsKey(archivePath)) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath); destFolder = foldersCreated[archivePath]; } else { // Don't include the last slash int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2); if (penultimateSlashIndex >= 0) { archivePath = archivePath.Remove(penultimateSlashIndex + 1); } else { m_log.DebugFormat( "[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}", originalArchivePath); archivePath = string.Empty; destFolder = rootDestFolder; } } } } else { destFolder = rootDestFolder; } string archivePathSectionToCreate = originalArchivePath.Substring(archivePath.Length); string[] rawDirsToCreate = archivePathSectionToCreate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); int i = 0; while (i < rawDirsToCreate.Length) { m_log.DebugFormat("[INVENTORY ARCHIVER]: Loading archived folder {0}", rawDirsToCreate[i]); int identicalNameIdentifierIndex = rawDirsToCreate[i].LastIndexOf( ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR); if (identicalNameIdentifierIndex < 0) { i++; continue; } string newFolderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex); newFolderName = InventoryArchiveUtils.UnescapeArchivePath(newFolderName); UUID newFolderId = UUID.Random(); // Asset type has to be Unknown here rather than Folder, otherwise the created folder can't be // deleted once the client has relogged. // The root folder appears to be labelled AssetType.Folder (shows up as "Category" in the client) // even though there is a AssetType.RootCategory destFolder = new InventoryFolderBase( newFolderId, newFolderName, m_userInfo.UserProfile.ID, (short)AssetType.Unknown, destFolder.ID, 1); m_scene.InventoryService.AddFolder(destFolder); // UUID newFolderId = UUID.Random(); // m_scene.InventoryService.AddFolder( // m_userInfo.CreateFolder( // folderName, newFolderId, (ushort)AssetType.Folder, foundFolder.ID); // m_log.DebugFormat("[INVENTORY ARCHIVER]: Retrieving newly created folder {0}", folderName); // foundFolder = foundFolder.GetChildFolder(newFolderId); // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Retrieved newly created folder {0} with ID {1}", // foundFolder.Name, foundFolder.ID); // Record that we have now created this folder archivePath += rawDirsToCreate[i] + "/"; m_log.DebugFormat("[INVENTORY ARCHIVER]: Loaded archive path {0}", archivePath); foldersCreated[archivePath] = destFolder; if (0 == i) nodesLoaded.Add(destFolder); i++; } return destFolder; /* string[] rawFolders = filePath.Split(new char[] { '/' }); // Find the folders that do exist along the path given int i = 0; bool noFolder = false; InventoryFolderImpl foundFolder = rootDestinationFolder; while (!noFolder && i < rawFolders.Length) { InventoryFolderImpl folder = foundFolder.FindFolderByPath(rawFolders[i]); if (null != folder) { m_log.DebugFormat("[INVENTORY ARCHIVER]: Found folder {0}", folder.Name); foundFolder = folder; i++; } else { noFolder = true; } } // Create any folders that did not previously exist while (i < rawFolders.Length) { m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0}", rawFolders[i]); UUID newFolderId = UUID.Random(); m_userInfo.CreateFolder( rawFolders[i++], newFolderId, (ushort)AssetType.Folder, foundFolder.ID); foundFolder = foundFolder.GetChildFolder(newFolderId); } */ } /// <summary> /// Load an item from the archive /// </summary> /// <param name="filePath">The archive path for the item</param> /// <param name="data">The raw item data</param> /// <param name="rootDestinationFolder">The root destination folder for loaded items</param> /// <param name="nodesLoaded">All the inventory nodes (items and folders) loaded so far</param> protected InventoryItemBase LoadItem(byte[] data, InventoryFolderBase loadFolder) { InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data); // Don't use the item ID that's in the file item.ID = UUID.Random(); UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.CommsManager); if (UUID.Zero != ospResolvedId) { item.CreatorIdAsUuid = ospResolvedId; // XXX: For now, don't preserve the OSPA in the creator id (which actually gets persisted to the // database). Instead, replace with the UUID that we found. item.CreatorId = ospResolvedId.ToString(); } else { item.CreatorIdAsUuid = m_userInfo.UserProfile.ID; } item.Owner = m_userInfo.UserProfile.ID; // Reset folder ID to the one in which we want to load it item.Folder = loadFolder.ID; //m_userInfo.AddItem(item); m_scene.InventoryService.AddItem(item); return item; } /// <summary> /// Load an asset /// </summary> /// <param name="assetFilename"></param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> private bool LoadAsset(string assetPath, byte[] data) { //IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>(); // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); if (i == -1) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); return false; } string extension = filename.Substring(i); string uuid = filename.Remove(filename.Length - extension.Length); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) { sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; if (assetType == (sbyte)AssetType.Unknown) m_log.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid); //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); AssetBase asset = new AssetBase(new UUID(uuid), "RandomName", assetType); asset.Data = data; m_scene.AssetService.Store(asset); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); return false; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using NodaTime; using QuantConnect.Securities; namespace QuantConnect.Scheduling { /// <summary> /// Provides a builder class to allow for fluent syntax when constructing new events /// </summary> /// <remarks> /// This builder follows the following steps for event creation: /// /// 1. Specify an event name (optional) /// 2. Specify an IDateRule /// 3. Specify an ITimeRule /// a. repeat 3. to define extra time rules (optional) /// 4. Specify additional where clause (optional) /// 5. Register event via call to Run /// </remarks> public class FluentScheduledEventBuilder : IFluentSchedulingDateSpecifier, IFluentSchedulingRunnable { private IDateRule _dateRule; private ITimeRule _timeRule; private Func<DateTime, bool> _predicate; private readonly string _name; private readonly ScheduleManager _schedule; private readonly SecurityManager _securities; /// <summary> /// Initializes a new instance of the <see cref="FluentScheduledEventBuilder"/> class /// </summary> /// <param name="schedule">The schedule to send created events to</param> /// <param name="securities">The algorithm's security manager</param> /// <param name="name">A specific name for this event</param> public FluentScheduledEventBuilder(ScheduleManager schedule, SecurityManager securities, string name = null) { _name = name; _schedule = schedule; _securities = securities; } private FluentScheduledEventBuilder SetTimeRule(ITimeRule rule) { // if it's not set, just set it if (_timeRule == null) { _timeRule = rule; return this; } // if it's already a composite, open it up and make a new composite // prevent nesting composites var compositeTimeRule = _timeRule as CompositeTimeRule; if (compositeTimeRule != null) { var rules = compositeTimeRule.Rules; _timeRule = new CompositeTimeRule(rules.Concat(new[] { rule })); return this; } // create a composite from the existing rule and the new rules _timeRule = new CompositeTimeRule(_timeRule, rule); return this; } #region DateRules and TimeRules delegation /// <summary> /// Creates events on each of the specified day of week /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Every(params DayOfWeek[] days) { _dateRule = _schedule.DateRules.Every(days); return this; } /// <summary> /// Creates events on every day of the year /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay() { _dateRule = _schedule.DateRules.EveryDay(); return this; } /// <summary> /// Creates events on every trading day of the year for the symbol /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay(Symbol symbol) { _dateRule = _schedule.DateRules.EveryDay(symbol); return this; } /// <summary> /// Creates events on the first day of the month /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart() { _dateRule = _schedule.DateRules.MonthStart(); return this; } /// <summary> /// Creates events on the first trading day of the month /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart(Symbol symbol) { _dateRule = _schedule.DateRules.MonthStart(symbol); return this; } /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Where(Func<DateTime, bool> predicate) { _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } /// <summary> /// Creates events that fire at the specific time of day in the algorithm's time zone /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay) { return SetTimeRule(_schedule.TimeRules.At(timeOfDay)); } /// <summary> /// Creates events that fire a specified number of minutes after market open /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.AfterMarketOpen(Symbol symbol, double minutesAfterOpen, bool extendedMarketOpen) { return SetTimeRule(_schedule.TimeRules.AfterMarketOpen(symbol, minutesAfterOpen, extendedMarketOpen)); } /// <summary> /// Creates events that fire a specified numer of minutes before market close /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.BeforeMarketClose(Symbol symbol, double minuteBeforeClose, bool extendedMarketClose) { return SetTimeRule(_schedule.TimeRules.BeforeMarketClose(symbol, minuteBeforeClose, extendedMarketClose)); } /// <summary> /// Creates events that fire on a period define by the specified interval /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.Every(TimeSpan interval) { return SetTimeRule(_schedule.TimeRules.Every(interval)); } /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingTimeSpecifier.Where(Func<DateTime, bool> predicate) { _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent IFluentSchedulingRunnable.Run(Action callback) { return ((IFluentSchedulingRunnable)this).Run((name, time) => callback()); } /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent IFluentSchedulingRunnable.Run(Action<DateTime> callback) { return ((IFluentSchedulingRunnable)this).Run((name, time) => callback(time)); } /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent IFluentSchedulingRunnable.Run(Action<string, DateTime> callback) { var name = _name ?? _dateRule.Name + ": " + _timeRule.Name; // back the date up to ensure we get all events, the event scheduler will skip past events that whose time has passed var dates = _dateRule.GetDates(_securities.UtcTime.Date.AddDays(-1), Time.EndOfTime); var eventTimes = _timeRule.CreateUtcEventTimes(dates); if (_predicate != null) { eventTimes = eventTimes.Where(_predicate); } var scheduledEvent = new ScheduledEvent(name, eventTimes, callback); _schedule.Add(scheduledEvent); return scheduledEvent; } /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingRunnable IFluentSchedulingRunnable.Where(Func<DateTime, bool> predicate) { _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } /// <summary> /// Filters the event times to only include times where the symbol's market is considered open /// </summary> IFluentSchedulingRunnable IFluentSchedulingRunnable.DuringMarketHours(Symbol symbol, bool extendedMarket) { var security = GetSecurity(symbol); Func<DateTime, bool> predicate = time => { var localTime = time.ConvertFromUtc(security.Exchange.TimeZone); return security.Exchange.IsOpenDuringBar(localTime, localTime, extendedMarket); }; _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(int year, int month, int day) { _dateRule = _schedule.DateRules.On(year, month, day); return this; } IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(params DateTime[] dates) { _dateRule = _schedule.DateRules.On(dates); return this; } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second) { return SetTimeRule(_schedule.TimeRules.At(hour, minute, second)); } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, DateTimeZone timeZone) { return SetTimeRule(_schedule.TimeRules.At(hour, minute, 0, timeZone)); } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second, DateTimeZone timeZone) { return SetTimeRule(_schedule.TimeRules.At(hour, minute, second, timeZone)); } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay, DateTimeZone timeZone) { return SetTimeRule(_schedule.TimeRules.At(timeOfDay, timeZone)); } private Security GetSecurity(Symbol symbol) { Security security; if (!_securities.TryGetValue(symbol, out security)) { throw new KeyNotFoundException($"{symbol} not found in portfolio. Request this data when initializing the algorithm."); } return security; } #endregion } /// <summary> /// Specifies the date rule component of a scheduled event /// </summary> public interface IFluentSchedulingDateSpecifier { /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate); /// <summary> /// Creates events only on the specified date /// </summary> IFluentSchedulingTimeSpecifier On(int year, int month, int day); /// <summary> /// Creates events only on the specified dates /// </summary> IFluentSchedulingTimeSpecifier On(params DateTime[] dates); /// <summary> /// Creates events on each of the specified day of week /// </summary> IFluentSchedulingTimeSpecifier Every(params DayOfWeek[] days); /// <summary> /// Creates events on every day of the year /// </summary> IFluentSchedulingTimeSpecifier EveryDay(); /// <summary> /// Creates events on every trading day of the year for the symbol /// </summary> IFluentSchedulingTimeSpecifier EveryDay(Symbol symbol); /// <summary> /// Creates events on the first day of the month /// </summary> IFluentSchedulingTimeSpecifier MonthStart(); /// <summary> /// Creates events on the first trading day of the month /// </summary> IFluentSchedulingTimeSpecifier MonthStart(Symbol symbol); } /// <summary> /// Specifies the time rule component of a scheduled event /// </summary> public interface IFluentSchedulingTimeSpecifier { /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(int hour, int minute, int second = 0); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(int hour, int minute, DateTimeZone timeZone); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(int hour, int minute, int second, DateTimeZone timeZone); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(TimeSpan timeOfDay, DateTimeZone timeZone); /// <summary> /// Creates events that fire at the specific time of day in the algorithm's time zone /// </summary> IFluentSchedulingRunnable At(TimeSpan timeOfDay); /// <summary> /// Creates events that fire on a period define by the specified interval /// </summary> IFluentSchedulingRunnable Every(TimeSpan interval); /// <summary> /// Creates events that fire a specified number of minutes after market open /// </summary> IFluentSchedulingRunnable AfterMarketOpen(Symbol symbol, double minutesAfterOpen = 0, bool extendedMarketOpen = false); /// <summary> /// Creates events that fire a specified numer of minutes before market close /// </summary> IFluentSchedulingRunnable BeforeMarketClose(Symbol symbol, double minuteBeforeClose = 0, bool extendedMarketClose = false); } /// <summary> /// Specifies the callback component of a scheduled event, as well as final filters /// </summary> public interface IFluentSchedulingRunnable : IFluentSchedulingTimeSpecifier { /// <summary> /// Filters the event times using the predicate /// </summary> new IFluentSchedulingRunnable Where(Func<DateTime, bool> predicate); /// <summary> /// Filters the event times to only include times where the symbol's market is considered open /// </summary> IFluentSchedulingRunnable DuringMarketHours(Symbol symbol, bool extendedMarket = false); /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent Run(Action callback); /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent Run(Action<DateTime> callback); /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent Run(Action<string, DateTime> callback); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Buffers.Text { public static partial class CustomFormatter { private static bool TryFormatInt64(long value, ulong mask, Span<byte> buffer, out int bytesWritten, StandardFormat format, SymbolTable symbolTable) { if (format.IsDefault) { format = 'G'; } if (value >= 0) { return TryFormatUInt64(unchecked((ulong)value), buffer, out bytesWritten, format, symbolTable); } else if (format.Symbol == 'x' || format.Symbol == 'X') { return TryFormatUInt64(unchecked((ulong)value) & mask, buffer, out bytesWritten, format, symbolTable); } else { if (!symbolTable.TryEncode(SymbolTable.Symbol.MinusSign, buffer, out int minusSignBytes)) { bytesWritten = 0; return false; } if (!TryFormatUInt64(unchecked((ulong)-value), buffer.Slice(minusSignBytes), out int digitBytes, format, symbolTable)) { bytesWritten = 0; return false; } bytesWritten = digitBytes + minusSignBytes; return true; } } private static bool TryFormatUInt64(ulong value, Span<byte> buffer, out int bytesWritten, StandardFormat format, SymbolTable symbolTable) { if (format.IsDefault) { format = 'G'; } switch (format.Symbol) { case 'x': case 'X': if (symbolTable == SymbolTable.InvariantUtf8) return TryFormatHexadecimalInvariantCultureUtf8(value, buffer, out bytesWritten, format); else if (symbolTable == SymbolTable.InvariantUtf16) return TryFormatHexadecimalInvariantCultureUtf16(value, buffer, out bytesWritten, format); else throw new NotSupportedException(); case 'd': case 'D': case 'g': case 'G': if (symbolTable == SymbolTable.InvariantUtf8) return TryFormatDecimalInvariantCultureUtf8(value, buffer, out bytesWritten, format); else if (symbolTable == SymbolTable.InvariantUtf16) return TryFormatDecimalInvariantCultureUtf16(value, buffer, out bytesWritten, format); else return TryFormatDecimal(value, buffer, out bytesWritten, format, symbolTable); case 'n': case 'N': return TryFormatDecimal(value, buffer, out bytesWritten, format, symbolTable); default: throw new FormatException(); } } private static bool TryFormatDecimalInvariantCultureUtf16(ulong value, Span<byte> buffer, out int bytesWritten, StandardFormat format) { char symbol = char.ToUpperInvariant(format.Symbol); Precondition.Require(symbol == 'D' || symbol == 'G'); // Count digits var valueToCountDigits = value; var digitsCount = 1; while (valueToCountDigits >= 10UL) { valueToCountDigits = valueToCountDigits / 10UL; digitsCount++; } var index = 0; var bytesCount = digitsCount * 2; // If format is D and precision is greater than digits count, append leading zeros if ((symbol == 'D') && format.HasPrecision) { var leadingZerosCount = format.Precision - digitsCount; if (leadingZerosCount > 0) { bytesCount += leadingZerosCount * 2; } if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } while (leadingZerosCount-- > 0) { buffer[index++] = (byte)'0'; buffer[index++] = 0; } } else if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } index = bytesCount; while (digitsCount-- > 0) { ulong digit = value % 10UL; value /= 10UL; buffer[--index] = 0; buffer[--index] = (byte)(digit + (ulong)'0'); } bytesWritten = bytesCount; return true; } private static bool TryFormatDecimalInvariantCultureUtf8(ulong value, Span<byte> buffer, out int bytesWritten, StandardFormat format) { char symbol = char.ToUpperInvariant(format.Symbol); Precondition.Require(symbol == 'D' || symbol == 'G'); // Count digits var valueToCountDigits = value; var digitsCount = 1; while (valueToCountDigits >= 10UL) { valueToCountDigits = valueToCountDigits / 10UL; digitsCount++; } var index = 0; var bytesCount = digitsCount; // If format is D and precision is greater than digits count, append leading zeros if ((symbol == 'D') && format.HasPrecision) { var leadingZerosCount = format.Precision - digitsCount; if (leadingZerosCount > 0) { bytesCount += leadingZerosCount; } if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } while (leadingZerosCount-- > 0) { buffer[index++] = (byte)'0'; } } else if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } index = bytesCount; while (digitsCount-- > 0) { ulong digit = value % 10UL; value /= 10UL; buffer[--index] = (byte)(digit + (ulong)'0'); } bytesWritten = bytesCount; return true; } private static bool TryFormatHexadecimalInvariantCultureUtf16(ulong value, Span<byte> buffer, out int bytesWritten, StandardFormat format) { Precondition.Require(format.Symbol == 'X' || format.Symbol == 'x'); byte firstDigitOffset = (byte)'0'; byte firstHexCharOffset = format.Symbol == 'x' ? (byte)'a' : (byte)'A'; firstHexCharOffset -= 10; // Count amount of hex digits var hexDigitsCount = 1; ulong valueToCount = value; if (valueToCount > 0xFFFFFFFF) { hexDigitsCount += 8; valueToCount >>= 0x20; } if (valueToCount > 0xFFFF) { hexDigitsCount += 4; valueToCount >>= 0x10; } if (valueToCount > 0xFF) { hexDigitsCount += 2; valueToCount >>= 0x8; } if (valueToCount > 0xF) { hexDigitsCount++; } var bytesCount = hexDigitsCount * 2; // Count leading zeros var leadingZerosCount = format.HasPrecision ? format.Precision - hexDigitsCount : 0; bytesCount += leadingZerosCount > 0 ? leadingZerosCount * 2 : 0; if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } var index = bytesCount; while (hexDigitsCount-- > 0) { byte digit = (byte)(value & 0xF); value >>= 0x4; digit += digit < 10 ? firstDigitOffset : firstHexCharOffset; buffer[--index] = 0; buffer[--index] = digit; } // Write leading zeros if any while (leadingZerosCount-- > 0) { buffer[--index] = 0; buffer[--index] = firstDigitOffset; } bytesWritten = bytesCount; return true; } private static bool TryFormatHexadecimalInvariantCultureUtf8(ulong value, Span<byte> buffer, out int bytesWritten, StandardFormat format) { Precondition.Require(format.Symbol == 'X' || format.Symbol == 'x'); byte firstDigitOffset = (byte)'0'; byte firstHexCharOffset = format.Symbol == 'X' ? (byte)'A' : (byte)'a'; firstHexCharOffset -= 10; // Count amount of hex digits var hexDigitsCount = 1; ulong valueToCount = value; if (valueToCount > 0xFFFFFFFF) { hexDigitsCount += 8; valueToCount >>= 0x20; } if (valueToCount > 0xFFFF) { hexDigitsCount += 4; valueToCount >>= 0x10; } if (valueToCount > 0xFF) { hexDigitsCount += 2; valueToCount >>= 0x8; } if (valueToCount > 0xF) { hexDigitsCount++; } var bytesCount = hexDigitsCount; // Count leading zeros var leadingZerosCount = format.HasPrecision ? format.Precision - hexDigitsCount : 0; bytesCount += leadingZerosCount > 0 ? leadingZerosCount : 0; if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } var index = bytesCount; while (hexDigitsCount-- > 0) { byte digit = (byte)(value & 0xF); value >>= 0x4; digit += digit < 10 ? firstDigitOffset : firstHexCharOffset; buffer[--index] = digit; } // Write leading zeros if any while (leadingZerosCount-- > 0) { buffer[--index] = firstDigitOffset; } bytesWritten = bytesCount; return true; } // TODO: this whole routine is too slow. It does div and mod twice, which are both costly (especially that some JITs cannot optimize it). // It does it twice to avoid reversing the formatted buffer, which can be tricky given it should handle arbitrary cultures. // One optimization I thought we could do is to do div/mod once and store digits in a temp buffer (but that would allocate). Modification to the idea would be to store the digits in a local struct // Another idea possibly worth tying would be to special case cultures that have constant digit size, and go back to the format + reverse buffer approach. private static bool TryFormatDecimal(ulong value, Span<byte> buffer, out int bytesWritten, StandardFormat format, SymbolTable symbolTable) { char symbol = char.ToUpperInvariant(format.Symbol); Precondition.Require(symbol == 'D' || format.Symbol == 'G' || format.Symbol == 'N'); // Reverse value on decimal basis, count digits and trailing zeros before the decimal separator ulong reversedValueExceptFirst = 0; var digitsCount = 1; var trailingZerosCount = 0; // We reverse the digits in numeric form because reversing encoded digits is hard and/or costly. // If value contains 20 digits, its reversed value will not fit into ulong size. // So reverse it till last digit (reversedValueExceptFirst will have all the digits except the first one). while (value >= 10) { var digit = value % 10UL; value = value / 10UL; if (reversedValueExceptFirst == 0 && digit == 0) { trailingZerosCount++; } else { reversedValueExceptFirst = reversedValueExceptFirst * 10UL + digit; digitsCount++; } } bytesWritten = 0; int digitBytes; // If format is D and precision is greater than digitsCount + trailingZerosCount, append leading zeros if (symbol == 'D' && format.HasPrecision) { var leadingZerosCount = format.Precision - digitsCount - trailingZerosCount; while (leadingZerosCount-- > 0) { if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } } // Append first digit if (!symbolTable.TryEncode((SymbolTable.Symbol)value, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsCount--; if (symbol == 'N') { const int GroupSize = 3; // Count amount of digits before first group separator. It will be reset to groupSize every time digitsLeftInGroup == zero var digitsLeftInGroup = (digitsCount + trailingZerosCount) % GroupSize; if (digitsLeftInGroup == 0) { if (digitsCount + trailingZerosCount > 0) { // There is a new group immediately after the first digit if (!symbolTable.TryEncode(SymbolTable.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } digitsLeftInGroup = GroupSize; } // Append digits while (reversedValueExceptFirst > 0) { if (digitsLeftInGroup == 0) { if (!symbolTable.TryEncode(SymbolTable.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsLeftInGroup = GroupSize; } var nextDigit = reversedValueExceptFirst % 10UL; reversedValueExceptFirst = reversedValueExceptFirst / 10UL; if (!symbolTable.TryEncode((SymbolTable.Symbol)nextDigit, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsLeftInGroup--; } // Append trailing zeros if any while (trailingZerosCount-- > 0) { if (digitsLeftInGroup == 0) { if (!symbolTable.TryEncode(SymbolTable.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsLeftInGroup = GroupSize; } if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsLeftInGroup--; } } else { while (reversedValueExceptFirst > 0) { var bufferSlice = buffer.Slice(bytesWritten); var nextDigit = reversedValueExceptFirst % 10UL; reversedValueExceptFirst = reversedValueExceptFirst / 10UL; if (!symbolTable.TryEncode((SymbolTable.Symbol)nextDigit, bufferSlice, out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } // Append trailing zeros if any while (trailingZerosCount-- > 0) { if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } } // If format is N and precision is not defined or is greater than zero, append trailing zeros after decimal point if (symbol == 'N') { int trailingZerosAfterDecimalCount = format.HasPrecision ? format.Precision : 2; if (trailingZerosAfterDecimalCount > 0) { if (!symbolTable.TryEncode(SymbolTable.Symbol.DecimalSeparator, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; while (trailingZerosAfterDecimalCount-- > 0) { if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } } } return true; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #if !UNIX using Dbg = System.Management.Automation; using System; using System.Text; using System.Security.Cryptography; using System.Collections.Generic; using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Provider; using System.Management.Automation.Security; using System.Runtime.InteropServices; using DWORD = System.UInt32; namespace System.Management.Automation { /// <summary> /// Defines the possible status when validating integrity of catalog. /// </summary> public enum CatalogValidationStatus { /// <summary> /// Status when catalog is not tampered. /// </summary> Valid, /// <summary> /// Status when catalog is tampered. /// </summary> ValidationFailed } /// <summary> /// Object returned by Catalog Cmdlets. /// </summary> public class CatalogInformation { /// <summary> /// Status of catalog. /// </summary> public CatalogValidationStatus Status { get; set; } /// <summary> /// Hash Algorithm used to calculate the hashes of files in Catalog. /// </summary> public string HashAlgorithm { get; set; } /// <summary> /// Dictionary mapping files relative paths to their hash values found from Catalog. /// </summary> public Dictionary<string, string> CatalogItems { get; set; } /// <summary> /// Dictionary mapping files relative paths to their hash values. /// </summary> public Dictionary<string, string> PathItems { get; set; } /// <summary> /// Signature for the catalog. /// </summary> public Signature Signature { get; set; } } /// <summary> /// Helper functions for Windows Catalog functionality. /// </summary> internal static class CatalogHelper { // Catalog Version is (0X100 = 256) for Catalog Version 1 private static int catalogVersion1 = 256; // Catalog Version is (0X200 = 512) for Catalog Version 2 private static int catalogVersion2 = 512; // Hash Algorithms supported by Windows Catalog private static string HashAlgorithmSHA1 = "SHA1"; private static string HashAlgorithmSHA256 = "SHA256"; private static PSCmdlet _cmdlet = null; /// <summary> /// Find out the Version of Catalog by reading its Meta data. We can have either version 1 or version 2 catalog. /// </summary> /// <param name="catalogHandle">Handle to open catalog file.</param> /// <returns>Version of the catalog.</returns> private static int GetCatalogVersion(IntPtr catalogHandle) { int catalogVersion = -1; IntPtr catalogData = NativeMethods.CryptCATStoreFromHandle(catalogHandle); NativeMethods.CRYPTCATSTORE catalogInfo = Marshal.PtrToStructure<NativeMethods.CRYPTCATSTORE>(catalogData); if (catalogInfo.dwPublicVersion == catalogVersion2) { catalogVersion = 2; } // One Windows 7 this API sent version information as decimal 1 not hex (0X100 = 256) // so we are checking for that value as well. Reason we are not checking for version 2 above in // this scenario because catalog version 2 is not supported on win7. else if ((catalogInfo.dwPublicVersion == catalogVersion1) || (catalogInfo.dwPublicVersion == 1)) { catalogVersion = 1; } else { // catalog version we don't understand Exception exception = new InvalidOperationException(StringUtil.Format(CatalogStrings.UnKnownCatalogVersion, catalogVersion1.ToString("X"), catalogVersion2.ToString("X"))); ErrorRecord errorRecord = new ErrorRecord(exception, "UnKnownCatalogVersion", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } return catalogVersion; } /// <summary> /// HashAlgorithm used by the Catalog. It is based on the version of Catalog. /// </summary> /// <param name="catalogVersion">Path of the output catalog file.</param> /// <returns>Version of the catalog.</returns> private static string GetCatalogHashAlgorithm(int catalogVersion) { string hashAlgorithm = string.Empty; if (catalogVersion == 1) { hashAlgorithm = HashAlgorithmSHA1; } else if (catalogVersion == 2) { hashAlgorithm = HashAlgorithmSHA256; } else { // version we don't understand Exception exception = new InvalidOperationException(StringUtil.Format(CatalogStrings.UnKnownCatalogVersion, "1.0", "2.0")); ErrorRecord errorRecord = new ErrorRecord(exception, "UnKnownCatalogVersion", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } return hashAlgorithm; } /// <summary> /// Generate the Catalog Definition File representing files and folders. /// </summary> /// <param name="Path">Path of expected output .cdf file.</param> /// <param name="catalogFilePath">Path of the output catalog file.</param> /// <param name="cdfFilePath">Path of the catalog definition file.</param> /// <param name="catalogVersion">Version of catalog.</param> /// <param name="hashAlgorithm">Hash method used to generate hashes for the Catalog.</param> /// <returns>HashSet for the relative Path for files in Catalog.</returns> internal static string GenerateCDFFile(Collection<string> Path, string catalogFilePath, string cdfFilePath, int catalogVersion, string hashAlgorithm) { HashSet<string> relativePaths = new HashSet<string>(); string cdfHeaderContent = string.Empty; string cdfFilesContent = string.Empty; int catAttributeCount = 0; // First create header and files section for the catalog then write in file cdfHeaderContent += "[CatalogHeader]" + Environment.NewLine; cdfHeaderContent += @"Name=" + catalogFilePath + Environment.NewLine; cdfHeaderContent += "CatalogVersion=" + catalogVersion + Environment.NewLine; cdfHeaderContent += "HashAlgorithms=" + hashAlgorithm + Environment.NewLine; cdfFilesContent += "[CatalogFiles]" + Environment.NewLine; foreach (string catalogFile in Path) { if (System.IO.Directory.Exists(catalogFile)) { var directoryItems = Directory.EnumerateFiles(catalogFile, "*.*", SearchOption.AllDirectories); foreach (string fileItem in directoryItems) { ProcessFileToBeAddedInCatalogDefinitionFile(new FileInfo(fileItem), new DirectoryInfo(catalogFile), ref relativePaths, ref cdfHeaderContent, ref cdfFilesContent, ref catAttributeCount); } } else if (System.IO.File.Exists(catalogFile)) { ProcessFileToBeAddedInCatalogDefinitionFile(new FileInfo(catalogFile), null, ref relativePaths, ref cdfHeaderContent, ref cdfFilesContent, ref catAttributeCount); } } using (System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(new FileStream(cdfFilePath, FileMode.Create))) { fileWriter.WriteLine(cdfHeaderContent); fileWriter.WriteLine(); fileWriter.WriteLine(cdfFilesContent); } return cdfFilePath; } /// <summary> /// Get file attribute (Relative path in our case) from catalog. /// </summary> /// <param name="fileToHash">File to hash.</param> /// <param name="dirInfo">Directory information about file needed to calculate relative file path.</param> /// <param name="relativePaths">Working set of relative paths of all files.</param> /// <param name="cdfHeaderContent">Content to be added in CatalogHeader section of cdf File.</param> /// <param name="cdfFilesContent">Content to be added in CatalogFiles section of cdf File.</param> /// <param name="catAttributeCount">Indicating the current no of catalog header level attributes.</param> /// <returns>Void.</returns> internal static void ProcessFileToBeAddedInCatalogDefinitionFile(FileInfo fileToHash, DirectoryInfo dirInfo, ref HashSet<string> relativePaths, ref string cdfHeaderContent, ref string cdfFilesContent, ref int catAttributeCount) { string relativePath = string.Empty; if (dirInfo != null) { // Relative path of the file is the path inside the containing folder excluding folder Name relativePath = fileToHash.FullName.Substring(dirInfo.FullName.Length).TrimStart('\\'); } else { relativePath = fileToHash.Name; } if (!relativePaths.Contains(relativePath)) { relativePaths.Add(relativePath); if (fileToHash.Length != 0) { cdfFilesContent += "<HASH>" + fileToHash.FullName + "=" + fileToHash.FullName + Environment.NewLine; cdfFilesContent += "<HASH>" + fileToHash.FullName + "ATTR1=0x10010001:FilePath:" + relativePath + Environment.NewLine; } else { // zero length files are added as catalog level attributes because they can not be hashed cdfHeaderContent += "CATATTR" + (++catAttributeCount) + "=0x10010001:FilePath:" + relativePath + Environment.NewLine; } } else { // If Files have same relative paths we can not distinguish them for // Validation. So failing. ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.FoundDuplicateFilesRelativePath, relativePath)), "FoundDuplicateFilesRelativePath", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } } /// <summary> /// Generate the Catalog file for Input Catalog Definition File. /// </summary> /// <param name="cdfFilePath">Path to the Input .cdf file.</param> internal static void GenerateCatalogFile(string cdfFilePath) { string pwszFilePath = cdfFilePath; NativeMethods.CryptCATCDFOpenCallBack catOpenCallBack = new NativeMethods.CryptCATCDFOpenCallBack(ParseErrorCallback); // Open CDF File IntPtr resultCDF = NativeMethods.CryptCATCDFOpen(pwszFilePath, catOpenCallBack); // navigate CDF header and files sections if (resultCDF != IntPtr.Zero) { // First navigate all catalog level attributes entries first, they represent zero size files IntPtr catalogAttr = IntPtr.Zero; do { catalogAttr = NativeMethods.CryptCATCDFEnumCatAttributes(resultCDF, catalogAttr, catOpenCallBack); if (catalogAttr != IntPtr.Zero) { string filePath = ProcessFilePathAttributeInCatalog(catalogAttr); _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, filePath, filePath)); } } while (catalogAttr != IntPtr.Zero); // navigate all the files hash entries in the .cdf file IntPtr memberInfo = IntPtr.Zero; try { IntPtr memberFile = IntPtr.Zero; NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack memberCallBack = new NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack(ParseErrorCallback); string fileName = string.Empty; do { memberFile = NativeMethods.CryptCATCDFEnumMembersByCDFTagEx(resultCDF, memberFile, memberCallBack, ref memberInfo, true, IntPtr.Zero); fileName = Marshal.PtrToStringUni(memberFile); if (!string.IsNullOrEmpty(fileName)) { IntPtr memberAttr = IntPtr.Zero; string fileRelativePath = string.Empty; do { memberAttr = NativeMethods.CryptCATCDFEnumAttributesWithCDFTag(resultCDF, memberFile, memberInfo, memberAttr, memberCallBack); if (memberAttr != IntPtr.Zero) { fileRelativePath = ProcessFilePathAttributeInCatalog(memberAttr); if (!string.IsNullOrEmpty(fileRelativePath)) { // Found the attribute we are looking for // Filename we read from the above API has <Hash> appended to its name as per CDF file tags convention // Truncating that Information from the string. string itemName = fileName.Substring(6); _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, itemName, fileRelativePath)); break; } } } while (memberAttr != IntPtr.Zero); } } while (fileName != null); } finally { NativeMethods.CryptCATCDFClose(resultCDF); } } else { // If we are not able to open CDF file we can not continue generating catalog ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.UnableToOpenCatalogDefinitionFile), "UnableToOpenCatalogDefinitionFile", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } } /// <summary> /// To generate Catalog for the folder. /// </summary> /// <param name="Path">Path to folder or File.</param> /// <param name="catalogFilePath">Catalog File Path.</param> /// <param name="catalogVersion">Catalog File Path.</param> /// <param name="cmdlet">Instance of cmdlet calling this method.</param> /// <returns>True if able to generate .cat file or false.</returns> internal static FileInfo GenerateCatalog(PSCmdlet cmdlet, Collection<string> Path, string catalogFilePath, int catalogVersion) { _cmdlet = cmdlet; string hashAlgorithm = GetCatalogHashAlgorithm(catalogVersion); if (!string.IsNullOrEmpty(hashAlgorithm)) { // Generate Path for Catalog Definition File string cdfFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()); cdfFilePath = cdfFilePath + ".cdf"; try { cdfFilePath = GenerateCDFFile(Path, catalogFilePath, cdfFilePath, catalogVersion, hashAlgorithm); if (!File.Exists(cdfFilePath)) { // If we are not able to generate catalog definition file we can not continue generating catalog // throw PSTraceSource.NewInvalidOperationException("catalog", CatalogStrings.CatalogDefinitionFileNotGenerated); ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.CatalogDefinitionFileNotGenerated), "CatalogDefinitionFileNotGenerated", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } GenerateCatalogFile(cdfFilePath); if (File.Exists(catalogFilePath)) { return new FileInfo(catalogFilePath); } } finally { File.Delete(cdfFilePath); } } return null; } /// <summary> /// Get file attribute (Relative path in our case) from catalog. /// </summary> /// <param name="memberAttrInfo">Pointer to current attribute of catalog member.</param> /// <returns>Value of the attribute.</returns> internal static string ProcessFilePathAttributeInCatalog(IntPtr memberAttrInfo) { string relativePath = string.Empty; NativeMethods.CRYPTCATATTRIBUTE currentMemberAttr = Marshal.PtrToStructure<NativeMethods.CRYPTCATATTRIBUTE>(memberAttrInfo); // check if this is the attribute we are looking for // catalog generated other way not using New-FileCatalog can have attributes we don't understand if (currentMemberAttr.pwszReferenceTag.Equals("FilePath", StringComparison.OrdinalIgnoreCase)) { // find the size for the current attribute value and then allocate buffer and copy from byte array int attrValueSize = (int)currentMemberAttr.cbValue; byte[] attrValue = new byte[attrValueSize]; Marshal.Copy(currentMemberAttr.pbValue, attrValue, 0, attrValueSize); relativePath = System.Text.Encoding.Unicode.GetString(attrValue); relativePath = relativePath.TrimEnd('\0'); } return relativePath; } /// <summary> /// Make a hash for the file. /// </summary> /// <param name="filePath">Path of the file.</param> /// <param name="hashAlgorithm">Used to calculate Hash.</param> /// <returns>HashValue for the file.</returns> internal static string CalculateFileHash(string filePath, string hashAlgorithm) { string hashValue = string.Empty; IntPtr catAdmin = IntPtr.Zero; // To get handle to the hash algorithm to be used to calculate hashes if (!NativeMethods.CryptCATAdminAcquireContext2(ref catAdmin, IntPtr.Zero, hashAlgorithm, IntPtr.Zero, 0)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToAcquireHashAlgorithmContext, hashAlgorithm)), "UnableToAcquireHashAlgorithmContext", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } DWORD GENERIC_READ = 0x80000000; DWORD OPEN_EXISTING = 3; IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // Open the file that is to be hashed for reading and get its handle IntPtr fileHandle = NativeMethods.CreateFile(filePath, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, IntPtr.Zero); if (fileHandle != INVALID_HANDLE_VALUE) { try { DWORD hashBufferSize = 0; IntPtr hashBuffer = IntPtr.Zero; // Call first time to get the size of expected buffer to hold new hash value if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } int size = (int)hashBufferSize; hashBuffer = Marshal.AllocHGlobal(size); try { // Call second time to actually get the hash value if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } byte[] hashBytes = new byte[size]; Marshal.Copy(hashBuffer, hashBytes, 0, size); hashValue = BitConverter.ToString(hashBytes).Replace("-", string.Empty); } finally { if (hashBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(hashBuffer); } } } finally { NativeMethods.CryptCATAdminReleaseContext(catAdmin, 0); NativeMethods.CloseHandle(fileHandle); } } else { // If we are not able to open file that is to be hashed we can not continue with catalog validation ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToReadFileToHash, filePath)), "UnableToReadFileToHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } return hashValue; } /// <summary> /// Make list of hashes for given Catalog File. /// </summary> /// <param name="catalogFilePath">Path to the folder having catalog file.</param> /// <param name="excludedPatterns"></param> /// <param name="catalogVersion">The version of input catalog we read from catalog meta data after opening it.</param> /// <returns>Dictionary mapping files relative paths to HashValues.</returns> internal static Dictionary<string, string> GetHashesFromCatalog(string catalogFilePath, WildcardPattern[] excludedPatterns, out int catalogVersion) { IntPtr resultCatalog = NativeMethods.CryptCATOpen(catalogFilePath, 0, IntPtr.Zero, 1, 0); IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); Dictionary<string, string> catalogHashes = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase); catalogVersion = 0; if (resultCatalog != INVALID_HANDLE_VALUE) { try { IntPtr catAttrInfo = IntPtr.Zero; // First traverse all catalog level attributes to get information about zero size file. do { catAttrInfo = NativeMethods.CryptCATEnumerateCatAttr(resultCatalog, catAttrInfo); // If we found attribute it is a file information retrieve its relative path // and add it to catalog hash collection if its not in excluded files criteria if (catAttrInfo != IntPtr.Zero) { string relativePath = ProcessFilePathAttributeInCatalog(catAttrInfo); if (!string.IsNullOrEmpty(relativePath)) { ProcessCatalogFile(relativePath, string.Empty, excludedPatterns, ref catalogHashes); } } } while (catAttrInfo != IntPtr.Zero); catalogVersion = GetCatalogVersion(resultCatalog); IntPtr memberInfo = IntPtr.Zero; // Next Navigate all members in Catalog files and get their relative paths and hashes do { memberInfo = NativeMethods.CryptCATEnumerateMember(resultCatalog, memberInfo); if (memberInfo != IntPtr.Zero) { NativeMethods.CRYPTCATMEMBER currentMember = Marshal.PtrToStructure<NativeMethods.CRYPTCATMEMBER>(memberInfo); NativeMethods.SIP_INDIRECT_DATA pIndirectData = Marshal.PtrToStructure<NativeMethods.SIP_INDIRECT_DATA>(currentMember.pIndirectData); // For Catalog version 2 CryptoAPI puts hashes of file attributes(relative path in our case) in Catalog as well // We validate those along with file hashes so we are skipping duplicate entries if (!((catalogVersion == 2) && (pIndirectData.DigestAlgorithm.pszObjId.Equals(new Oid("SHA1").Value, StringComparison.OrdinalIgnoreCase)))) { string relativePath = string.Empty; IntPtr memberAttrInfo = IntPtr.Zero; do { memberAttrInfo = NativeMethods.CryptCATEnumerateAttr(resultCatalog, memberInfo, memberAttrInfo); if (memberAttrInfo != IntPtr.Zero) { relativePath = ProcessFilePathAttributeInCatalog(memberAttrInfo); if (!string.IsNullOrEmpty(relativePath)) { break; } } } while (memberAttrInfo != IntPtr.Zero); // If we did not find any Relative Path for the item in catalog we should quit // This catalog must not be valid for our use as catalogs generated using New-FileCatalog // always contains relative file Paths if (string.IsNullOrEmpty(relativePath)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } ProcessCatalogFile(relativePath, currentMember.pwszReferenceTag, excludedPatterns, ref catalogHashes); } } } while (memberInfo != IntPtr.Zero); } finally { NativeMethods.CryptCATClose(resultCatalog); } } else { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } return catalogHashes; } /// <summary> /// Process file in path for its relative paths. /// </summary> /// <param name="relativePath">Relative path of file found in catalog.</param> /// <param name="fileHash">Hash of file found in catalog.</param> /// <param name="excludedPatterns">Skip file from validation if it matches these patterns.</param> /// <param name="catalogHashes">Collection of hashes of catalog.</param> /// <returns>Void.</returns> internal static void ProcessCatalogFile(string relativePath, string fileHash, WildcardPattern[] excludedPatterns, ref Dictionary<string, string> catalogHashes) { // Found the attribute we are looking for _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.FoundFileHashInCatalogItem, relativePath, fileHash)); // Only add the file for validation if it does not meet exclusion criteria if (!CheckExcludedCriteria((new FileInfo(relativePath)).Name, excludedPatterns)) { // Add relativePath mapping to hashvalue for each file catalogHashes.Add(relativePath, fileHash); } else { // Verbose about skipping file from catalog _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.SkipValidationOfCatalogFile, relativePath)); } } /// <summary> /// Process file in path for its relative paths. /// </summary> /// <param name="fileToHash">File to hash.</param> /// <param name="dirInfo">Directory information about file needed to calculate relative file path.</param> /// <param name="hashAlgorithm">Used to calculate Hash.</param> /// <param name="excludedPatterns">Skip file if it matches these patterns.</param> /// <param name="fileHashes">Collection of hashes of files.</param> /// <returns>Void.</returns> internal static void ProcessPathFile(FileInfo fileToHash, DirectoryInfo dirInfo, string hashAlgorithm, WildcardPattern[] excludedPatterns, ref Dictionary<string, string> fileHashes) { string relativePath = string.Empty; string exclude = string.Empty; if (dirInfo != null) { // Relative path of the file is the path inside the containing folder excluding folder Name relativePath = fileToHash.FullName.Substring(dirInfo.FullName.Length).TrimStart('\\'); exclude = fileToHash.Name; } else { relativePath = fileToHash.Name; exclude = relativePath; } if (!CheckExcludedCriteria(exclude, excludedPatterns)) { string fileHash = string.Empty; if (fileToHash.Length != 0) { fileHash = CalculateFileHash(fileToHash.FullName, hashAlgorithm); } if (!fileHashes.ContainsKey(relativePath)) { fileHashes.Add(relativePath, fileHash); _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.FoundFileInPath, relativePath, fileHash)); } else { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.FoundDuplicateFilesRelativePath, relativePath)), "FoundDuplicateFilesRelativePath", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } } else { // Verbose about skipping file from path _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.SkipValidationOfPathFile, relativePath)); } } /// <summary> /// Generate the hashes of all the files in given folder. /// </summary> /// <param name="folderPaths">Path to folder or File.</param> /// <param name="catalogFilePath">Catalog file path it should be skipped when calculating the hashes.</param> /// <param name="hashAlgorithm">Used to calculate Hash.</param> /// <param name="excludedPatterns"></param> /// <returns>Dictionary mapping file relative paths to hashes..</returns> internal static Dictionary<string, string> CalculateHashesFromPath(Collection<string> folderPaths, string catalogFilePath, string hashAlgorithm, WildcardPattern[] excludedPatterns) { // Create a HashTable of file Hashes Dictionary<string, string> fileHashes = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase); foreach (string folderPath in folderPaths) { if (System.IO.Directory.Exists(folderPath)) { var directoryItems = Directory.EnumerateFiles(folderPath, "*.*", SearchOption.AllDirectories); foreach (string fileItem in directoryItems) { // if its the catalog file we are validating we will skip it if (string.Equals(fileItem, catalogFilePath, StringComparison.OrdinalIgnoreCase)) continue; ProcessPathFile(new FileInfo(fileItem), new DirectoryInfo(folderPath), hashAlgorithm, excludedPatterns, ref fileHashes); } } else if (System.IO.File.Exists(folderPath)) { ProcessPathFile(new FileInfo(folderPath), null, hashAlgorithm, excludedPatterns, ref fileHashes); } } return fileHashes; } /// <summary> /// Compare Dictionary objects. /// </summary> /// <param name="catalogItems">Hashes extracted from Catalog.</param> /// <param name="pathItems">Hashes created from folders path.</param> /// <returns>True if both collections are same.</returns> internal static bool CompareDictionaries(Dictionary<string, string> catalogItems, Dictionary<string, string> pathItems) { bool Status = true; List<string> relativePathsFromFolder = pathItems.Keys.ToList(); List<string> relativePathsFromCatalog = catalogItems.Keys.ToList(); // Find entires those are not in both list lists. These should be empty lists for success // Hashes in Catalog should be exact similar to the ones from folder List<string> relativePathsNotInFolder = relativePathsFromFolder.Except(relativePathsFromCatalog, StringComparer.CurrentCultureIgnoreCase).ToList(); List<string> relativePathsNotInCatalog = relativePathsFromCatalog.Except(relativePathsFromFolder, StringComparer.CurrentCultureIgnoreCase).ToList(); // Found extra hashes in Folder if ((relativePathsNotInFolder.Count != 0) || (relativePathsNotInCatalog.Count != 0)) { Status = false; } foreach (KeyValuePair<string, string> item in catalogItems) { string catalogHashValue = (string)catalogItems[item.Key]; if (pathItems.ContainsKey(item.Key)) { string folderHashValue = (string)pathItems[item.Key]; if (folderHashValue.Equals(catalogHashValue)) { continue; } else { Status = false; } } } return Status; } /// <summary> /// To Validate the Integrity of Catalog. /// </summary> /// <param name="catalogFolders">Folder for which catalog is created.</param> /// <param name="catalogFilePath">File Name of the Catalog.</param> /// <param name="excludedPatterns"></param> /// <param name="cmdlet">Instance of cmdlet calling this method.</param> /// <returns>Information about Catalog.</returns> internal static CatalogInformation ValidateCatalog(PSCmdlet cmdlet, Collection<string> catalogFolders, string catalogFilePath, WildcardPattern[] excludedPatterns) { _cmdlet = cmdlet; int catalogVersion = 0; Dictionary<string, string> catalogHashes = GetHashesFromCatalog(catalogFilePath, excludedPatterns, out catalogVersion); string hashAlgorithm = GetCatalogHashAlgorithm(catalogVersion); if (!string.IsNullOrEmpty(hashAlgorithm)) { Dictionary<string, string> fileHashes = CalculateHashesFromPath(catalogFolders, catalogFilePath, hashAlgorithm, excludedPatterns); CatalogInformation catalog = new CatalogInformation(); catalog.CatalogItems = catalogHashes; catalog.PathItems = fileHashes; bool status = CompareDictionaries(catalogHashes, fileHashes); if (status == true) { catalog.Status = CatalogValidationStatus.Valid; } else { catalog.Status = CatalogValidationStatus.ValidationFailed; } catalog.HashAlgorithm = hashAlgorithm; catalog.Signature = SignatureHelper.GetSignature(catalogFilePath, null); return catalog; } return null; } /// <summary> /// Check if file meets the skip validation criteria. /// </summary> /// <param name="filename"></param> /// <param name="excludedPatterns"></param> /// <returns>True if match is found else false.</returns> internal static bool CheckExcludedCriteria(string filename, WildcardPattern[] excludedPatterns) { if (excludedPatterns != null) { foreach (WildcardPattern patternItem in excludedPatterns) { if (patternItem.IsMatch(filename)) { return true; } } } return false; } /// <summary> /// Call back when error is thrown by catalog API's. /// </summary> private static void ParseErrorCallback(DWORD dwErrorArea, DWORD dwLocalError, string pwszLine) { switch (dwErrorArea) { case NativeConstants.CRYPTCAT_E_AREA_HEADER: break; case NativeConstants.CRYPTCAT_E_AREA_MEMBER: break; case NativeConstants.CRYPTCAT_E_AREA_ATTRIBUTE: break; default: break; } switch (dwLocalError) { case NativeConstants.CRYPTCAT_E_CDF_MEMBER_FILE_PATH: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToFindFileNameOrPathForCatalogMember, pwszLine)), "UnableToFindFileNameOrPathForCatalogMember", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } case NativeConstants.CRYPTCAT_E_CDF_MEMBER_INDIRECTDATA: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, pwszLine)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } case NativeConstants.CRYPTCAT_E_CDF_MEMBER_FILENOTFOUND: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToFindFileToHash, pwszLine)), "UnableToFindFileToHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } case NativeConstants.CRYPTCAT_E_CDF_BAD_GUID_CONV: break; case NativeConstants.CRYPTCAT_E_CDF_ATTR_TYPECOMBO: break; case NativeConstants.CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES: break; case NativeConstants.CRYPTCAT_E_CDF_UNSUPPORTED: break; case NativeConstants.CRYPTCAT_E_CDF_DUPLICATE: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.FoundDuplicateFileMemberInCatalog, pwszLine)), "FoundDuplicateFileMemberInCatalog", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } case NativeConstants.CRYPTCAT_E_CDF_TAGNOTFOUND: break; default: break; } } } } #endif
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using System.Net.NetworkInformation; using System.Threading; using System.Text; namespace ProxySwitcher.Core.NativeWifi { /// <summary> /// Represents a client to the Zeroconf (Native Wifi) service. /// </summary> /// <remarks> /// This class is the entrypoint to Native Wifi management. To manage WiFi settings, create an instance /// of this class. /// </remarks> public class WlanClient : IDisposable { /// <summary> /// Represents a Wifi network interface. /// </summary> public class WlanInterface { private readonly WlanClient client; private Wlan.WlanInterfaceInfo info; #region Events /// <summary> /// Represents a method that will handle <see cref="WlanNotification"/> events. /// </summary> /// <param name="notifyData">The notification data.</param> public delegate void WlanNotificationEventHandler(Wlan.WlanNotificationData notifyData); /// <summary> /// Represents a method that will handle <see cref="WlanConnectionNotification"/> events. /// </summary> /// <param name="notifyData">The notification data.</param> /// <param name="connNotifyData">The notification data.</param> public delegate void WlanConnectionNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData); /// <summary> /// Represents a method that will handle <see cref="WlanReasonNotification"/> events. /// </summary> /// <param name="notifyData">The notification data.</param> /// <param name="reasonCode">The reason code.</param> public delegate void WlanReasonNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode); /// <summary> /// Occurs when an event of any kind occurs on a WLAN interface. /// </summary> public event WlanNotificationEventHandler WlanNotification; /// <summary> /// Occurs when a WLAN interface changes connection state. /// </summary> public event WlanConnectionNotificationEventHandler WlanConnectionNotification; /// <summary> /// Occurs when a WLAN operation fails due to some reason. /// </summary> public event WlanReasonNotificationEventHandler WlanReasonNotification; #endregion #region Event queue private bool queueEvents; private readonly AutoResetEvent eventQueueFilled = new AutoResetEvent(false); private readonly Queue<object> eventQueue = new Queue<object>(); private struct WlanConnectionNotificationEventData { public Wlan.WlanNotificationData notifyData; public Wlan.WlanConnectionNotificationData connNotifyData; } private struct WlanReasonNotificationData { public Wlan.WlanNotificationData notifyData; public Wlan.WlanReasonCode reasonCode; } #endregion internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info) { this.client = client; this.info = info; } /// <summary> /// Sets a parameter of the interface whose data type is <see cref="int"/>. /// </summary> /// <param name="opCode">The opcode of the parameter.</param> /// <param name="value">The value to set.</param> private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value) { IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int)); Marshal.WriteInt32(valuePtr, value); try { Wlan.ThrowIfError( Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero)); } finally { Marshal.FreeHGlobal(valuePtr); } } /// <summary> /// Gets a parameter of the interface whose data type is <see cref="int"/>. /// </summary> /// <param name="opCode">The opcode of the parameter.</param> /// <returns>The integer value.</returns> private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode) { IntPtr valuePtr; int valueSize; Wlan.WlanOpcodeValueType opcodeValueType; Wlan.ThrowIfError( Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType)); try { return Marshal.ReadInt32(valuePtr); } finally { Wlan.WlanFreeMemory(valuePtr); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="WlanInterface"/> is automatically configured. /// </summary> /// <value><c>true</c> if "autoconf" is enabled; otherwise, <c>false</c>.</value> public bool Autoconf { get { return GetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled) != 0; } set { SetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled, value ? 1 : 0); } } /// <summary> /// Gets or sets the BSS type for the indicated interface. /// </summary> /// <value>The type of the BSS.</value> public Wlan.Dot11BssType BssType { get { return (Wlan.Dot11BssType) GetInterfaceInt(Wlan.WlanIntfOpcode.BssType); } set { SetInterfaceInt(Wlan.WlanIntfOpcode.BssType, (int)value); } } /// <summary> /// Gets the state of the interface. /// </summary> /// <value>The state of the interface.</value> public Wlan.WlanInterfaceState InterfaceState { get { return (Wlan.WlanInterfaceState)GetInterfaceInt(Wlan.WlanIntfOpcode.InterfaceState); } } /// <summary> /// Gets the channel. /// </summary> /// <value>The channel.</value> /// <remarks>Not supported on Windows XP SP2.</remarks> public int Channel { get { return GetInterfaceInt(Wlan.WlanIntfOpcode.ChannelNumber); } } /// <summary> /// Gets the RSSI. /// </summary> /// <value>The RSSI.</value> /// <remarks>Not supported on Windows XP SP2.</remarks> public int RSSI { get { return GetInterfaceInt(Wlan.WlanIntfOpcode.RSSI); } } /// <summary> /// Gets the radio state. /// </summary> /// <value>The radio state.</value> /// <remarks>Not supported on Windows XP.</remarks> public Wlan.WlanRadioState RadioState { get { int valueSize; IntPtr valuePtr; Wlan.WlanOpcodeValueType opcodeValueType; Wlan.ThrowIfError( Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.RadioState, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType)); try { return (Wlan.WlanRadioState)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanRadioState)); } finally { Wlan.WlanFreeMemory(valuePtr); } } } /// <summary> /// Gets the current operation mode. /// </summary> /// <value>The current operation mode.</value> /// <remarks>Not supported on Windows XP SP2.</remarks> public Wlan.Dot11OperationMode CurrentOperationMode { get { return (Wlan.Dot11OperationMode) GetInterfaceInt(Wlan.WlanIntfOpcode.CurrentOperationMode); } } /// <summary> /// Gets the attributes of the current connection. /// </summary> /// <value>The current connection attributes.</value> /// <exception cref="Win32Exception">An exception with code 0x0000139F (The group or resource is not in the correct state to perform the requested operation.) will be thrown if the interface is not connected to a network.</exception> public Wlan.WlanConnectionAttributes CurrentConnection { get { int valueSize; IntPtr valuePtr; Wlan.WlanOpcodeValueType opcodeValueType; Wlan.ThrowIfError( Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType)); try { return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes)); } finally { Wlan.WlanFreeMemory(valuePtr); } } } /// <summary> /// Requests a scan for available networks. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Scan() { Wlan.ThrowIfError( Wlan.WlanScan(client.clientHandle, info.interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)); } /// <summary> /// Converts a pointer to a available networks list (header + entries) to an array of available network entries. /// </summary> /// <param name="availNetListPtr">A pointer to an available networks list's header.</param> /// <returns>An array of available network entries.</returns> private static Wlan.WlanAvailableNetwork[] ConvertAvailableNetworkListPtr(IntPtr availNetListPtr) { Wlan.WlanAvailableNetworkListHeader availNetListHeader = (Wlan.WlanAvailableNetworkListHeader)Marshal.PtrToStructure(availNetListPtr, typeof(Wlan.WlanAvailableNetworkListHeader)); long availNetListIt = availNetListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanAvailableNetworkListHeader)); Wlan.WlanAvailableNetwork[] availNets = new Wlan.WlanAvailableNetwork[availNetListHeader.numberOfItems]; for (int i = 0; i < availNetListHeader.numberOfItems; ++i) { availNets[i] = (Wlan.WlanAvailableNetwork)Marshal.PtrToStructure(new IntPtr(availNetListIt), typeof(Wlan.WlanAvailableNetwork)); availNetListIt += Marshal.SizeOf(typeof(Wlan.WlanAvailableNetwork)); } return availNets; } /// <summary> /// Retrieves the list of available networks. /// </summary> /// <param name="flags">Controls the type of networks returned.</param> /// <returns>A list of the available networks.</returns> public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags) { IntPtr availNetListPtr; Wlan.ThrowIfError( Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr)); try { return ConvertAvailableNetworkListPtr(availNetListPtr); } finally { Wlan.WlanFreeMemory(availNetListPtr); } } /// <summary> /// Converts a pointer to a BSS list (header + entries) to an array of BSS entries. /// </summary> /// <param name="bssListPtr">A pointer to a BSS list's header.</param> /// <returns>An array of BSS entries.</returns> private static Wlan.WlanBssEntry[] ConvertBssListPtr(IntPtr bssListPtr) { Wlan.WlanBssListHeader bssListHeader = (Wlan.WlanBssListHeader)Marshal.PtrToStructure(bssListPtr, typeof(Wlan.WlanBssListHeader)); long bssListIt = bssListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanBssListHeader)); Wlan.WlanBssEntry[] bssEntries = new Wlan.WlanBssEntry[bssListHeader.numberOfItems]; for (int i=0; i<bssListHeader.numberOfItems; ++i) { bssEntries[i] = (Wlan.WlanBssEntry)Marshal.PtrToStructure(new IntPtr(bssListIt), typeof(Wlan.WlanBssEntry)); bssListIt += Marshal.SizeOf(typeof(Wlan.WlanBssEntry)); } return bssEntries; } /// <summary> /// Retrieves the basic service sets (BSS) list of all available networks. /// </summary> public Wlan.WlanBssEntry[] GetNetworkBssList() { IntPtr bssListPtr; Wlan.ThrowIfError( Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr)); try { return ConvertBssListPtr(bssListPtr); } finally { Wlan.WlanFreeMemory(bssListPtr); } } /// <summary> /// Retrieves the basic service sets (BSS) list of the specified network. /// </summary> /// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param> /// <param name="bssType">Indicates the BSS type of the network.</param> /// <param name="securityEnabled">Indicates whether security is enabled on the network.</param> public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled) { IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid)); Marshal.StructureToPtr(ssid, ssidPtr, false); try { IntPtr bssListPtr; Wlan.ThrowIfError( Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr)); try { return ConvertBssListPtr(bssListPtr); } finally { Wlan.WlanFreeMemory(bssListPtr); } } finally { Marshal.FreeHGlobal(ssidPtr); } } /// <summary> /// Connects to a network defined by a connection parameters structure. /// </summary> /// <param name="connectionParams">The connection paramters.</param> protected void Connect(Wlan.WlanConnectionParameters connectionParams) { Wlan.ThrowIfError( Wlan.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero)); } /// <summary> /// Requests a connection (association) to the specified wireless network. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile) { Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters(); connectionParams.wlanConnectionMode = connectionMode; connectionParams.profile = profile; connectionParams.dot11BssType = bssType; connectionParams.flags = 0; Connect(connectionParams); } /// <summary> /// Connects (associates) to the specified wireless network, returning either on a success to connect /// or a failure. /// </summary> /// <param name="connectionMode"></param> /// <param name="bssType"></param> /// <param name="profile"></param> /// <param name="connectTimeout"></param> /// <returns></returns> public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, int connectTimeout) { queueEvents = true; try { Connect(connectionMode, bssType, profile); while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true)) { lock (eventQueue) { while (eventQueue.Count != 0) { object e = eventQueue.Dequeue(); if (e is WlanConnectionNotificationEventData) { WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e; // Check if the conditions are good to indicate either success or failure. if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM) { switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode) { case Wlan.WlanNotificationCodeAcm.ConnectionComplete: if (wlanConnectionData.connNotifyData.profileName == profile) return true; break; } } break; } } } } } finally { queueEvents = false; eventQueue.Clear(); } return false; // timeout expired and no "connection complete" } /// <summary> /// Connects to the specified wireless network. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags) { Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters(); connectionParams.wlanConnectionMode = connectionMode; connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid)); Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false); connectionParams.dot11BssType = bssType; connectionParams.flags = flags; Connect(connectionParams); Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType()); Marshal.FreeHGlobal(connectionParams.dot11SsidPtr); } /// <summary> /// Deletes a profile. /// </summary> /// <param name="profileName"> /// The name of the profile to be deleted. Profile names are case-sensitive. /// On Windows XP SP2, the supplied name must match the profile name derived automatically from the SSID of the network. For an infrastructure network profile, the SSID must be supplied for the profile name. For an ad hoc network profile, the supplied name must be the SSID of the ad hoc network followed by <c>-adhoc</c>. /// </param> public void DeleteProfile(string profileName) { Wlan.ThrowIfError( Wlan.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero)); } /// <summary> /// Sets the profile. /// </summary> /// <param name="flags">The flags to set on the profile.</param> /// <param name="profileXml">The XML representation of the profile. On Windows XP SP 2, special care should be taken to adhere to its limitations.</param> /// <param name="overwrite">If a profile by the given name already exists, then specifies whether to overwrite it (if <c>true</c>) or return an error (if <c>false</c>).</param> /// <returns>The resulting code indicating a success or the reason why the profile wasn't valid.</returns> public Wlan.WlanReasonCode SetProfile(Wlan.WlanProfileFlags flags, string profileXml, bool overwrite) { Wlan.WlanReasonCode reasonCode; Wlan.ThrowIfError( Wlan.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode)); return reasonCode; } /// <summary> /// Gets the profile's XML specification. /// </summary> /// <param name="profileName">The name of the profile.</param> /// <returns>The XML document.</returns> public string GetProfileXml(string profileName) { IntPtr profileXmlPtr; Wlan.WlanProfileFlags flags; Wlan.WlanAccess access; Wlan.ThrowIfError( Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags, out access)); try { return Marshal.PtrToStringUni(profileXmlPtr); } finally { Wlan.WlanFreeMemory(profileXmlPtr); } } /// <summary> /// Gets the information of all profiles on this interface. /// </summary> /// <returns>The profiles information.</returns> public Wlan.WlanProfileInfo[] GetProfiles() { IntPtr profileListPtr; Wlan.ThrowIfError( Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr)); try { Wlan.WlanProfileInfoListHeader header = (Wlan.WlanProfileInfoListHeader) Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader)); Wlan.WlanProfileInfo[] profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems]; long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header); for (int i=0; i<header.numberOfItems; ++i) { Wlan.WlanProfileInfo profileInfo = (Wlan.WlanProfileInfo) Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(Wlan.WlanProfileInfo)); profileInfos[i] = profileInfo; profileListIterator += Marshal.SizeOf(profileInfo); } return profileInfos; } finally { Wlan.WlanFreeMemory(profileListPtr); } } internal void OnWlanConnection(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData) { if (WlanConnectionNotification != null) WlanConnectionNotification(notifyData, connNotifyData); if (queueEvents) { WlanConnectionNotificationEventData queuedEvent = new WlanConnectionNotificationEventData(); queuedEvent.notifyData = notifyData; queuedEvent.connNotifyData = connNotifyData; EnqueueEvent(queuedEvent); } } internal void OnWlanReason(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode) { if (WlanReasonNotification != null) WlanReasonNotification(notifyData, reasonCode); if (queueEvents) { WlanReasonNotificationData queuedEvent = new WlanReasonNotificationData(); queuedEvent.notifyData = notifyData; queuedEvent.reasonCode = reasonCode; EnqueueEvent(queuedEvent); } } internal void OnWlanNotification(Wlan.WlanNotificationData notifyData) { if (WlanNotification != null) WlanNotification(notifyData); } /// <summary> /// Enqueues a notification event to be processed serially. /// </summary> private void EnqueueEvent(object queuedEvent) { lock (eventQueue) eventQueue.Enqueue(queuedEvent); eventQueueFilled.Set(); } /// <summary> /// Gets the network interface of this wireless interface. /// </summary> /// <remarks> /// The network interface allows querying of generic network properties such as the interface's IP address. /// </remarks> public NetworkInterface NetworkInterface { get { // Do not cache the NetworkInterface; We need it fresh // each time cause otherwise it caches the IP information. foreach (NetworkInterface netIface in NetworkInterface.GetAllNetworkInterfaces()) { Guid netIfaceGuid = new Guid(netIface.Id); if (netIfaceGuid.Equals(info.interfaceGuid)) { return netIface; } } return null; } } /// <summary> /// The GUID of the interface (same content as the <see cref="System.Net.NetworkInformation.NetworkInterface.Id"/> value). /// </summary> public Guid InterfaceGuid { get { return info.interfaceGuid; } } /// <summary> /// The description of the interface. /// This is a user-immutable string containing the vendor and model name of the adapter. /// </summary> public string InterfaceDescription { get { return info.interfaceDescription; } } /// <summary> /// The friendly name given to the interface by the user (e.g. "Local Area Network Connection"). /// </summary> public string InterfaceName { get { return NetworkInterface.Name; } } } private IntPtr clientHandle; private uint negotiatedVersion; private readonly Wlan.WlanNotificationCallbackDelegate wlanNotificationCallback; private readonly Dictionary<Guid,WlanInterface> ifaces = new Dictionary<Guid,WlanInterface>(); /// <summary> /// Creates a new instance of a Native Wifi service client. /// </summary> public WlanClient() { Wlan.ThrowIfError( Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle)); try { Wlan.WlanNotificationSource prevSrc; wlanNotificationCallback = OnWlanNotification; Wlan.ThrowIfError( Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc)); } catch { Close(); throw; } } void IDisposable.Dispose() { GC.SuppressFinalize(this); Close(); } ~WlanClient() { Close(); } /// <summary> /// Closes the handle. /// </summary> private void Close() { if (clientHandle != IntPtr.Zero) { Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero); clientHandle = IntPtr.Zero; } } private static Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData) { int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData)); if (notifyData.dataSize < expectedSize) return null; Wlan.WlanConnectionNotificationData connNotifyData = (Wlan.WlanConnectionNotificationData) Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData)); if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success) { IntPtr profileXmlPtr = new IntPtr( notifyData.dataPtr.ToInt64() + Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64()); connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr); } return connNotifyData; } private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context) { WlanInterface wlanIface; ifaces.TryGetValue(notifyData.interfaceGuid, out wlanIface); switch(notifyData.notificationSource) { case Wlan.WlanNotificationSource.ACM: switch((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode) { case Wlan.WlanNotificationCodeAcm.ConnectionStart: case Wlan.WlanNotificationCodeAcm.ConnectionComplete: case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail: case Wlan.WlanNotificationCodeAcm.Disconnecting: case Wlan.WlanNotificationCodeAcm.Disconnected: Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData); if (connNotifyData.HasValue) if (wlanIface != null) wlanIface.OnWlanConnection(notifyData, connNotifyData.Value); break; case Wlan.WlanNotificationCodeAcm.ScanFail: { int expectedSize = Marshal.SizeOf(typeof (int)); if (notifyData.dataSize >= expectedSize) { Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode) Marshal.ReadInt32(notifyData.dataPtr); if (wlanIface != null) wlanIface.OnWlanReason(notifyData, reasonCode); } } break; } break; case Wlan.WlanNotificationSource.MSM: switch((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode) { case Wlan.WlanNotificationCodeMsm.Associating: case Wlan.WlanNotificationCodeMsm.Associated: case Wlan.WlanNotificationCodeMsm.Authenticating: case Wlan.WlanNotificationCodeMsm.Connected: case Wlan.WlanNotificationCodeMsm.RoamingStart: case Wlan.WlanNotificationCodeMsm.RoamingEnd: case Wlan.WlanNotificationCodeMsm.Disassociating: case Wlan.WlanNotificationCodeMsm.Disconnected: case Wlan.WlanNotificationCodeMsm.PeerJoin: case Wlan.WlanNotificationCodeMsm.PeerLeave: case Wlan.WlanNotificationCodeMsm.AdapterRemoval: Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData); if (connNotifyData.HasValue) if (wlanIface != null) wlanIface.OnWlanConnection(notifyData, connNotifyData.Value); break; } break; } if (wlanIface != null) wlanIface.OnWlanNotification(notifyData); } /// <summary> /// Gets the WLAN interfaces. /// </summary> /// <value>The WLAN interfaces.</value> public WlanInterface[] Interfaces { get { IntPtr ifaceList; Wlan.ThrowIfError( Wlan.WlanEnumInterfaces(clientHandle, IntPtr.Zero, out ifaceList)); try { Wlan.WlanInterfaceInfoListHeader header = (Wlan.WlanInterfaceInfoListHeader) Marshal.PtrToStructure(ifaceList, typeof (Wlan.WlanInterfaceInfoListHeader)); Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header); WlanInterface[] interfaces = new WlanInterface[header.numberOfItems]; List<Guid> currentIfaceGuids = new List<Guid>(); for (int i = 0; i < header.numberOfItems; ++i) { Wlan.WlanInterfaceInfo info = (Wlan.WlanInterfaceInfo) Marshal.PtrToStructure(new IntPtr(listIterator), typeof (Wlan.WlanInterfaceInfo)); listIterator += Marshal.SizeOf(info); currentIfaceGuids.Add(info.interfaceGuid); WlanInterface wlanIface; if (!ifaces.TryGetValue(info.interfaceGuid, out wlanIface)) { wlanIface = new WlanInterface(this, info); ifaces[info.interfaceGuid] = wlanIface; } interfaces[i] = wlanIface; } // Remove stale interfaces Queue<Guid> deadIfacesGuids = new Queue<Guid>(); foreach (Guid ifaceGuid in ifaces.Keys) { if (!currentIfaceGuids.Contains(ifaceGuid)) deadIfacesGuids.Enqueue(ifaceGuid); } while(deadIfacesGuids.Count != 0) { Guid deadIfaceGuid = deadIfacesGuids.Dequeue(); ifaces.Remove(deadIfaceGuid); } return interfaces; } finally { Wlan.WlanFreeMemory(ifaceList); } } } /// <summary> /// Gets a string that describes a specified reason code. /// </summary> /// <param name="reasonCode">The reason code.</param> /// <returns>The string.</returns> public string GetStringForReasonCode(Wlan.WlanReasonCode reasonCode) { StringBuilder sb = new StringBuilder(1024); // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size Wlan.ThrowIfError( Wlan.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero)); return sb.ToString(); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 5:11:31 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** #pragma warning disable 1591 namespace DotSpatial.Projections.ProjectedCategories { /// <summary> /// UtmWgs1984 /// </summary> public class UtmWgs1984 : CoordinateSystemCategory { #region Private Variables public readonly ProjectionInfo WGS1984ComplexUTMZone20N; public readonly ProjectionInfo WGS1984ComplexUTMZone21N; public readonly ProjectionInfo WGS1984ComplexUTMZone22N; public readonly ProjectionInfo WGS1984ComplexUTMZone23N; public readonly ProjectionInfo WGS1984ComplexUTMZone24N; public readonly ProjectionInfo WGS1984ComplexUTMZone25N; public readonly ProjectionInfo WGS1984ComplexUTMZone26N; public readonly ProjectionInfo WGS1984ComplexUTMZone27N; public readonly ProjectionInfo WGS1984ComplexUTMZone28N; public readonly ProjectionInfo WGS1984ComplexUTMZone29N; public readonly ProjectionInfo WGS1984ComplexUTMZone30N; public readonly ProjectionInfo WGS1984UTMZone10N; public readonly ProjectionInfo WGS1984UTMZone10S; public readonly ProjectionInfo WGS1984UTMZone11N; public readonly ProjectionInfo WGS1984UTMZone11S; public readonly ProjectionInfo WGS1984UTMZone12N; public readonly ProjectionInfo WGS1984UTMZone12S; public readonly ProjectionInfo WGS1984UTMZone13N; public readonly ProjectionInfo WGS1984UTMZone13S; public readonly ProjectionInfo WGS1984UTMZone14N; public readonly ProjectionInfo WGS1984UTMZone14S; public readonly ProjectionInfo WGS1984UTMZone15N; public readonly ProjectionInfo WGS1984UTMZone15S; public readonly ProjectionInfo WGS1984UTMZone16N; public readonly ProjectionInfo WGS1984UTMZone16S; public readonly ProjectionInfo WGS1984UTMZone17N; public readonly ProjectionInfo WGS1984UTMZone17S; public readonly ProjectionInfo WGS1984UTMZone18N; public readonly ProjectionInfo WGS1984UTMZone18S; public readonly ProjectionInfo WGS1984UTMZone19N; public readonly ProjectionInfo WGS1984UTMZone19S; public readonly ProjectionInfo WGS1984UTMZone1N; public readonly ProjectionInfo WGS1984UTMZone1S; public readonly ProjectionInfo WGS1984UTMZone20N; public readonly ProjectionInfo WGS1984UTMZone20S; public readonly ProjectionInfo WGS1984UTMZone21N; public readonly ProjectionInfo WGS1984UTMZone21S; public readonly ProjectionInfo WGS1984UTMZone22N; public readonly ProjectionInfo WGS1984UTMZone22S; public readonly ProjectionInfo WGS1984UTMZone23N; public readonly ProjectionInfo WGS1984UTMZone23S; public readonly ProjectionInfo WGS1984UTMZone24N; public readonly ProjectionInfo WGS1984UTMZone24S; public readonly ProjectionInfo WGS1984UTMZone25N; public readonly ProjectionInfo WGS1984UTMZone25S; public readonly ProjectionInfo WGS1984UTMZone26N; public readonly ProjectionInfo WGS1984UTMZone26S; public readonly ProjectionInfo WGS1984UTMZone27N; public readonly ProjectionInfo WGS1984UTMZone27S; public readonly ProjectionInfo WGS1984UTMZone28N; public readonly ProjectionInfo WGS1984UTMZone28S; public readonly ProjectionInfo WGS1984UTMZone29N; public readonly ProjectionInfo WGS1984UTMZone29S; public readonly ProjectionInfo WGS1984UTMZone2N; public readonly ProjectionInfo WGS1984UTMZone2S; public readonly ProjectionInfo WGS1984UTMZone30N; public readonly ProjectionInfo WGS1984UTMZone30S; public readonly ProjectionInfo WGS1984UTMZone31N; public readonly ProjectionInfo WGS1984UTMZone31S; public readonly ProjectionInfo WGS1984UTMZone32N; public readonly ProjectionInfo WGS1984UTMZone32S; public readonly ProjectionInfo WGS1984UTMZone33N; public readonly ProjectionInfo WGS1984UTMZone33S; public readonly ProjectionInfo WGS1984UTMZone34N; public readonly ProjectionInfo WGS1984UTMZone34S; public readonly ProjectionInfo WGS1984UTMZone35N; public readonly ProjectionInfo WGS1984UTMZone35S; public readonly ProjectionInfo WGS1984UTMZone36N; public readonly ProjectionInfo WGS1984UTMZone36S; public readonly ProjectionInfo WGS1984UTMZone37N; public readonly ProjectionInfo WGS1984UTMZone37S; public readonly ProjectionInfo WGS1984UTMZone38N; public readonly ProjectionInfo WGS1984UTMZone38S; public readonly ProjectionInfo WGS1984UTMZone39N; public readonly ProjectionInfo WGS1984UTMZone39S; public readonly ProjectionInfo WGS1984UTMZone3N; public readonly ProjectionInfo WGS1984UTMZone3S; public readonly ProjectionInfo WGS1984UTMZone40N; public readonly ProjectionInfo WGS1984UTMZone40S; public readonly ProjectionInfo WGS1984UTMZone41N; public readonly ProjectionInfo WGS1984UTMZone41S; public readonly ProjectionInfo WGS1984UTMZone42N; public readonly ProjectionInfo WGS1984UTMZone42S; public readonly ProjectionInfo WGS1984UTMZone43N; public readonly ProjectionInfo WGS1984UTMZone43S; public readonly ProjectionInfo WGS1984UTMZone44N; public readonly ProjectionInfo WGS1984UTMZone44S; public readonly ProjectionInfo WGS1984UTMZone45N; public readonly ProjectionInfo WGS1984UTMZone45S; public readonly ProjectionInfo WGS1984UTMZone46N; public readonly ProjectionInfo WGS1984UTMZone46S; public readonly ProjectionInfo WGS1984UTMZone47N; public readonly ProjectionInfo WGS1984UTMZone47S; public readonly ProjectionInfo WGS1984UTMZone48N; public readonly ProjectionInfo WGS1984UTMZone48S; public readonly ProjectionInfo WGS1984UTMZone49N; public readonly ProjectionInfo WGS1984UTMZone49S; public readonly ProjectionInfo WGS1984UTMZone4N; public readonly ProjectionInfo WGS1984UTMZone4S; public readonly ProjectionInfo WGS1984UTMZone50N; public readonly ProjectionInfo WGS1984UTMZone50S; public readonly ProjectionInfo WGS1984UTMZone51N; public readonly ProjectionInfo WGS1984UTMZone51S; public readonly ProjectionInfo WGS1984UTMZone52N; public readonly ProjectionInfo WGS1984UTMZone52S; public readonly ProjectionInfo WGS1984UTMZone53N; public readonly ProjectionInfo WGS1984UTMZone53S; public readonly ProjectionInfo WGS1984UTMZone54N; public readonly ProjectionInfo WGS1984UTMZone54S; public readonly ProjectionInfo WGS1984UTMZone55N; public readonly ProjectionInfo WGS1984UTMZone55S; public readonly ProjectionInfo WGS1984UTMZone56N; public readonly ProjectionInfo WGS1984UTMZone56S; public readonly ProjectionInfo WGS1984UTMZone57N; public readonly ProjectionInfo WGS1984UTMZone57S; public readonly ProjectionInfo WGS1984UTMZone58N; public readonly ProjectionInfo WGS1984UTMZone58S; public readonly ProjectionInfo WGS1984UTMZone59N; public readonly ProjectionInfo WGS1984UTMZone59S; public readonly ProjectionInfo WGS1984UTMZone5N; public readonly ProjectionInfo WGS1984UTMZone5S; public readonly ProjectionInfo WGS1984UTMZone60N; public readonly ProjectionInfo WGS1984UTMZone60S; public readonly ProjectionInfo WGS1984UTMZone6N; public readonly ProjectionInfo WGS1984UTMZone6S; public readonly ProjectionInfo WGS1984UTMZone7N; public readonly ProjectionInfo WGS1984UTMZone7S; public readonly ProjectionInfo WGS1984UTMZone8N; public readonly ProjectionInfo WGS1984UTMZone8S; public readonly ProjectionInfo WGS1984UTMZone9N; public readonly ProjectionInfo WGS1984UTMZone9S; #endregion #region Constructors /// <summary> /// Creates a new instance of UtmWgs1984 /// </summary> public UtmWgs1984() { WGS1984ComplexUTMZone20N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone21N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone22N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone23N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone24N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone25N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone26N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone27N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone28N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone29N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone30N = ProjectionInfo.FromProj4String("+ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone10N = ProjectionInfo.FromProj4String("+proj=utm +zone=10 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone10S = ProjectionInfo.FromProj4String("+proj=utm +zone=10 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone11N = ProjectionInfo.FromProj4String("+proj=utm +zone=11 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone11S = ProjectionInfo.FromProj4String("+proj=utm +zone=11 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone12N = ProjectionInfo.FromProj4String("+proj=utm +zone=12 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone12S = ProjectionInfo.FromProj4String("+proj=utm +zone=12 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone13N = ProjectionInfo.FromProj4String("+proj=utm +zone=13 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone13S = ProjectionInfo.FromProj4String("+proj=utm +zone=13 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone14N = ProjectionInfo.FromProj4String("+proj=utm +zone=14 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone14S = ProjectionInfo.FromProj4String("+proj=utm +zone=14 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone15N = ProjectionInfo.FromProj4String("+proj=utm +zone=15 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone15S = ProjectionInfo.FromProj4String("+proj=utm +zone=15 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone16N = ProjectionInfo.FromProj4String("+proj=utm +zone=16 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone16S = ProjectionInfo.FromProj4String("+proj=utm +zone=16 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone17N = ProjectionInfo.FromProj4String("+proj=utm +zone=17 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone17S = ProjectionInfo.FromProj4String("+proj=utm +zone=17 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone18N = ProjectionInfo.FromProj4String("+proj=utm +zone=18 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone18S = ProjectionInfo.FromProj4String("+proj=utm +zone=18 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone19N = ProjectionInfo.FromProj4String("+proj=utm +zone=19 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone19S = ProjectionInfo.FromProj4String("+proj=utm +zone=19 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone1N = ProjectionInfo.FromProj4String("+proj=utm +zone=1 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone1S = ProjectionInfo.FromProj4String("+proj=utm +zone=1 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone20N = ProjectionInfo.FromProj4String("+proj=utm +zone=20 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone20S = ProjectionInfo.FromProj4String("+proj=utm +zone=20 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone21N = ProjectionInfo.FromProj4String("+proj=utm +zone=21 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone21S = ProjectionInfo.FromProj4String("+proj=utm +zone=21 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone22N = ProjectionInfo.FromProj4String("+proj=utm +zone=22 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone22S = ProjectionInfo.FromProj4String("+proj=utm +zone=22 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone23N = ProjectionInfo.FromProj4String("+proj=utm +zone=23 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone23S = ProjectionInfo.FromProj4String("+proj=utm +zone=23 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone24N = ProjectionInfo.FromProj4String("+proj=utm +zone=24 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone24S = ProjectionInfo.FromProj4String("+proj=utm +zone=24 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone25N = ProjectionInfo.FromProj4String("+proj=utm +zone=25 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone25S = ProjectionInfo.FromProj4String("+proj=utm +zone=25 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone26N = ProjectionInfo.FromProj4String("+proj=utm +zone=26 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone26S = ProjectionInfo.FromProj4String("+proj=utm +zone=26 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone27N = ProjectionInfo.FromProj4String("+proj=utm +zone=27 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone27S = ProjectionInfo.FromProj4String("+proj=utm +zone=27 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone28N = ProjectionInfo.FromProj4String("+proj=utm +zone=28 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone28S = ProjectionInfo.FromProj4String("+proj=utm +zone=28 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone29N = ProjectionInfo.FromProj4String("+proj=utm +zone=29 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone29S = ProjectionInfo.FromProj4String("+proj=utm +zone=29 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone2N = ProjectionInfo.FromProj4String("+proj=utm +zone=2 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone2S = ProjectionInfo.FromProj4String("+proj=utm +zone=2 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone30N = ProjectionInfo.FromProj4String("+proj=utm +zone=30 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone30S = ProjectionInfo.FromProj4String("+proj=utm +zone=30 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone31N = ProjectionInfo.FromProj4String("+proj=utm +zone=31 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone31S = ProjectionInfo.FromProj4String("+proj=utm +zone=31 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone32N = ProjectionInfo.FromProj4String("+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone32S = ProjectionInfo.FromProj4String("+proj=utm +zone=32 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone33N = ProjectionInfo.FromProj4String("+proj=utm +zone=33 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone33S = ProjectionInfo.FromProj4String("+proj=utm +zone=33 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone34N = ProjectionInfo.FromProj4String("+proj=utm +zone=34 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone34S = ProjectionInfo.FromProj4String("+proj=utm +zone=34 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone35N = ProjectionInfo.FromProj4String("+proj=utm +zone=35 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone35S = ProjectionInfo.FromProj4String("+proj=utm +zone=35 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone36N = ProjectionInfo.FromProj4String("+proj=utm +zone=36 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone36S = ProjectionInfo.FromProj4String("+proj=utm +zone=36 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone37N = ProjectionInfo.FromProj4String("+proj=utm +zone=37 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone37S = ProjectionInfo.FromProj4String("+proj=utm +zone=37 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone38N = ProjectionInfo.FromProj4String("+proj=utm +zone=38 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone38S = ProjectionInfo.FromProj4String("+proj=utm +zone=38 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone39N = ProjectionInfo.FromProj4String("+proj=utm +zone=39 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone39S = ProjectionInfo.FromProj4String("+proj=utm +zone=39 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone3N = ProjectionInfo.FromProj4String("+proj=utm +zone=3 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone3S = ProjectionInfo.FromProj4String("+proj=utm +zone=3 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone40N = ProjectionInfo.FromProj4String("+proj=utm +zone=40 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone40S = ProjectionInfo.FromProj4String("+proj=utm +zone=40 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone41N = ProjectionInfo.FromProj4String("+proj=utm +zone=41 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone41S = ProjectionInfo.FromProj4String("+proj=utm +zone=41 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone42N = ProjectionInfo.FromProj4String("+proj=utm +zone=42 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone42S = ProjectionInfo.FromProj4String("+proj=utm +zone=42 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone43N = ProjectionInfo.FromProj4String("+proj=utm +zone=43 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone43S = ProjectionInfo.FromProj4String("+proj=utm +zone=43 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone44N = ProjectionInfo.FromProj4String("+proj=utm +zone=44 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone44S = ProjectionInfo.FromProj4String("+proj=utm +zone=44 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone45N = ProjectionInfo.FromProj4String("+proj=utm +zone=45 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone45S = ProjectionInfo.FromProj4String("+proj=utm +zone=45 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone46N = ProjectionInfo.FromProj4String("+proj=utm +zone=46 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone46S = ProjectionInfo.FromProj4String("+proj=utm +zone=46 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone47N = ProjectionInfo.FromProj4String("+proj=utm +zone=47 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone47S = ProjectionInfo.FromProj4String("+proj=utm +zone=47 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone48N = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone48S = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone49N = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone49S = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone4N = ProjectionInfo.FromProj4String("+proj=utm +zone=4 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone4S = ProjectionInfo.FromProj4String("+proj=utm +zone=4 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone50N = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone50S = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone51N = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone51S = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone52N = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone52S = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone53N = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone53S = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone54N = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone54S = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone55N = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone55S = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone56N = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone56S = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone57N = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone57S = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone58N = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone58S = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone59N = ProjectionInfo.FromProj4String("+proj=utm +zone=59 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone59S = ProjectionInfo.FromProj4String("+proj=utm +zone=59 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone5N = ProjectionInfo.FromProj4String("+proj=utm +zone=5 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone5S = ProjectionInfo.FromProj4String("+proj=utm +zone=5 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone60N = ProjectionInfo.FromProj4String("+proj=utm +zone=60 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone60S = ProjectionInfo.FromProj4String("+proj=utm +zone=60 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone6N = ProjectionInfo.FromProj4String("+proj=utm +zone=6 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone6S = ProjectionInfo.FromProj4String("+proj=utm +zone=6 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone7N = ProjectionInfo.FromProj4String("+proj=utm +zone=7 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone7S = ProjectionInfo.FromProj4String("+proj=utm +zone=7 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone8N = ProjectionInfo.FromProj4String("+proj=utm +zone=8 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone8S = ProjectionInfo.FromProj4String("+proj=utm +zone=8 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone9N = ProjectionInfo.FromProj4String("+proj=utm +zone=9 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984UTMZone9S = ProjectionInfo.FromProj4String("+proj=utm +zone=9 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); WGS1984ComplexUTMZone20N.Name = "WGS_1984_Complex_UTM_Zone_20N"; WGS1984ComplexUTMZone21N.Name = "WGS_1984_Complex_UTM_Zone_21N"; WGS1984ComplexUTMZone22N.Name = "WGS_1984_Complex_UTM_Zone_22N"; WGS1984ComplexUTMZone23N.Name = "WGS_1984_Complex_UTM_Zone_23N"; WGS1984ComplexUTMZone24N.Name = "WGS_1984_Complex_UTM_Zone_24N"; WGS1984ComplexUTMZone25N.Name = "WGS_1984_Complex_UTM_Zone_25N"; WGS1984ComplexUTMZone26N.Name = "WGS_1984_Complex_UTM_Zone_26N"; WGS1984ComplexUTMZone27N.Name = "WGS_1984_Complex_UTM_Zone_27N"; WGS1984ComplexUTMZone28N.Name = "WGS_1984_Complex_UTM_Zone_28N"; WGS1984ComplexUTMZone29N.Name = "WGS_1984_Complex_UTM_Zone_29N"; WGS1984ComplexUTMZone30N.Name = "WGS_1984_Complex_UTM_Zone_30N"; WGS1984UTMZone10N.Name = "WGS_1984_UTM_Zone_10N"; WGS1984UTMZone10S.Name = "WGS_1984_UTM_Zone_10S"; WGS1984UTMZone11N.Name = "WGS_1984_UTM_Zone_11N"; WGS1984UTMZone11S.Name = "WGS_1984_UTM_Zone_11S"; WGS1984UTMZone12N.Name = "WGS_1984_UTM_Zone_12N"; WGS1984UTMZone12S.Name = "WGS_1984_UTM_Zone_12S"; WGS1984UTMZone13N.Name = "WGS_1984_UTM_Zone_13N"; WGS1984UTMZone13S.Name = "WGS_1984_UTM_Zone_13S"; WGS1984UTMZone14N.Name = "WGS_1984_UTM_Zone_14N"; WGS1984UTMZone14S.Name = "WGS_1984_UTM_Zone_14S"; WGS1984UTMZone15N.Name = "WGS_1984_UTM_Zone_15N"; WGS1984UTMZone15S.Name = "WGS_1984_UTM_Zone_15S"; WGS1984UTMZone16N.Name = "WGS_1984_UTM_Zone_16N"; WGS1984UTMZone16S.Name = "WGS_1984_UTM_Zone_16S"; WGS1984UTMZone17N.Name = "WGS_1984_UTM_Zone_17N"; WGS1984UTMZone17S.Name = "WGS_1984_UTM_Zone_17S"; WGS1984UTMZone18N.Name = "WGS_1984_UTM_Zone_18N"; WGS1984UTMZone18S.Name = "WGS_1984_UTM_Zone_18S"; WGS1984UTMZone19N.Name = "WGS_1984_UTM_Zone_19N"; WGS1984UTMZone19S.Name = "WGS_1984_UTM_Zone_19S"; WGS1984UTMZone1N.Name = "WGS_1984_UTM_Zone_1N"; WGS1984UTMZone1S.Name = "WGS_1984_UTM_Zone_1S"; WGS1984UTMZone20N.Name = "WGS_1984_UTM_Zone_20N"; WGS1984UTMZone20S.Name = "WGS_1984_UTM_Zone_20S"; WGS1984UTMZone21N.Name = "WGS_1984_UTM_Zone_21N"; WGS1984UTMZone21S.Name = "WGS_1984_UTM_Zone_21S"; WGS1984UTMZone22N.Name = "WGS_1984_UTM_Zone_22N"; WGS1984UTMZone22S.Name = "WGS_1984_UTM_Zone_22S"; WGS1984UTMZone23N.Name = "WGS_1984_UTM_Zone_23N"; WGS1984UTMZone23S.Name = "WGS_1984_UTM_Zone_23S"; WGS1984UTMZone24N.Name = "WGS_1984_UTM_Zone_24N"; WGS1984UTMZone24S.Name = "WGS_1984_UTM_Zone_24S"; WGS1984UTMZone25N.Name = "WGS_1984_UTM_Zone_25N"; WGS1984UTMZone25S.Name = "WGS_1984_UTM_Zone_25S"; WGS1984UTMZone26N.Name = "WGS_1984_UTM_Zone_26N"; WGS1984UTMZone26S.Name = "WGS_1984_UTM_Zone_26S"; WGS1984UTMZone27N.Name = "WGS_1984_UTM_Zone_27N"; WGS1984UTMZone27S.Name = "WGS_1984_UTM_Zone_27S"; WGS1984UTMZone28N.Name = "WGS_1984_UTM_Zone_28N"; WGS1984UTMZone28S.Name = "WGS_1984_UTM_Zone_28S"; WGS1984UTMZone29N.Name = "WGS_1984_UTM_Zone_29N"; WGS1984UTMZone29S.Name = "WGS_1984_UTM_Zone_29S"; WGS1984UTMZone2N.Name = "WGS_1984_UTM_Zone_2N"; WGS1984UTMZone2S.Name = "WGS_1984_UTM_Zone_2S"; WGS1984UTMZone30N.Name = "WGS_1984_UTM_Zone_30N"; WGS1984UTMZone30S.Name = "WGS_1984_UTM_Zone_30S"; WGS1984UTMZone31N.Name = "WGS_1984_UTM_Zone_31N"; WGS1984UTMZone31S.Name = "WGS_1984_UTM_Zone_31S"; WGS1984UTMZone32N.Name = "WGS_1984_UTM_Zone_32N"; WGS1984UTMZone32S.Name = "WGS_1984_UTM_Zone_32S"; WGS1984UTMZone33N.Name = "WGS_1984_UTM_Zone_33N"; WGS1984UTMZone33S.Name = "WGS_1984_UTM_Zone_33S"; WGS1984UTMZone34N.Name = "WGS_1984_UTM_Zone_34N"; WGS1984UTMZone34S.Name = "WGS_1984_UTM_Zone_34S"; WGS1984UTMZone35N.Name = "WGS_1984_UTM_Zone_35N"; WGS1984UTMZone35S.Name = "WGS_1984_UTM_Zone_35S"; WGS1984UTMZone36N.Name = "WGS_1984_UTM_Zone_36N"; WGS1984UTMZone36S.Name = "WGS_1984_UTM_Zone_36S"; WGS1984UTMZone37N.Name = "WGS_1984_UTM_Zone_37N"; WGS1984UTMZone37S.Name = "WGS_1984_UTM_Zone_37S"; WGS1984UTMZone38N.Name = "WGS_1984_UTM_Zone_38N"; WGS1984UTMZone38S.Name = "WGS_1984_UTM_Zone_38S"; WGS1984UTMZone39N.Name = "WGS_1984_UTM_Zone_39N"; WGS1984UTMZone39S.Name = "WGS_1984_UTM_Zone_39S"; WGS1984UTMZone3N.Name = "WGS_1984_UTM_Zone_3N"; WGS1984UTMZone3S.Name = "WGS_1984_UTM_Zone_3S"; WGS1984UTMZone40N.Name = "WGS_1984_UTM_Zone_40N"; WGS1984UTMZone40S.Name = "WGS_1984_UTM_Zone_40S"; WGS1984UTMZone41N.Name = "WGS_1984_UTM_Zone_41N"; WGS1984UTMZone41S.Name = "WGS_1984_UTM_Zone_41S"; WGS1984UTMZone42N.Name = "WGS_1984_UTM_Zone_42N"; WGS1984UTMZone42S.Name = "WGS_1984_UTM_Zone_42S"; WGS1984UTMZone43N.Name = "WGS_1984_UTM_Zone_43N"; WGS1984UTMZone43S.Name = "WGS_1984_UTM_Zone_43S"; WGS1984UTMZone44N.Name = "WGS_1984_UTM_Zone_44N"; WGS1984UTMZone44S.Name = "WGS_1984_UTM_Zone_44S"; WGS1984UTMZone45N.Name = "WGS_1984_UTM_Zone_45N"; WGS1984UTMZone45S.Name = "WGS_1984_UTM_Zone_45S"; WGS1984UTMZone46N.Name = "WGS_1984_UTM_Zone_46N"; WGS1984UTMZone46S.Name = "WGS_1984_UTM_Zone_46S"; WGS1984UTMZone47N.Name = "WGS_1984_UTM_Zone_47N"; WGS1984UTMZone47S.Name = "WGS_1984_UTM_Zone_47S"; WGS1984UTMZone48N.Name = "WGS_1984_UTM_Zone_48N"; WGS1984UTMZone48S.Name = "WGS_1984_UTM_Zone_48S"; WGS1984UTMZone49N.Name = "WGS_1984_UTM_Zone_49N"; WGS1984UTMZone49S.Name = "WGS_1984_UTM_Zone_49S"; WGS1984UTMZone4N.Name = "WGS_1984_UTM_Zone_4N"; WGS1984UTMZone4S.Name = "WGS_1984_UTM_Zone_4S"; WGS1984UTMZone50N.Name = "WGS_1984_UTM_Zone_50N"; WGS1984UTMZone50S.Name = "WGS_1984_UTM_Zone_50S"; WGS1984UTMZone51N.Name = "WGS_1984_UTM_Zone_51N"; WGS1984UTMZone51S.Name = "WGS_1984_UTM_Zone_51S"; WGS1984UTMZone52N.Name = "WGS_1984_UTM_Zone_52N"; WGS1984UTMZone52S.Name = "WGS_1984_UTM_Zone_52S"; WGS1984UTMZone53N.Name = "WGS_1984_UTM_Zone_53N"; WGS1984UTMZone53S.Name = "WGS_1984_UTM_Zone_53S"; WGS1984UTMZone54N.Name = "WGS_1984_UTM_Zone_54N"; WGS1984UTMZone54S.Name = "WGS_1984_UTM_Zone_54S"; WGS1984UTMZone55N.Name = "WGS_1984_UTM_Zone_55N"; WGS1984UTMZone55S.Name = "WGS_1984_UTM_Zone_55S"; WGS1984UTMZone56N.Name = "WGS_1984_UTM_Zone_56N"; WGS1984UTMZone56S.Name = "WGS_1984_UTM_Zone_56S"; WGS1984UTMZone57N.Name = "WGS_1984_UTM_Zone_57N"; WGS1984UTMZone57S.Name = "WGS_1984_UTM_Zone_57S"; WGS1984UTMZone58N.Name = "WGS_1984_UTM_Zone_58N"; WGS1984UTMZone58S.Name = "WGS_1984_UTM_Zone_58S"; WGS1984UTMZone59N.Name = "WGS_1984_UTM_Zone_59N"; WGS1984UTMZone59S.Name = "WGS_1984_UTM_Zone_59S"; WGS1984UTMZone5N.Name = "WGS_1984_UTM_Zone_5N"; WGS1984UTMZone5S.Name = "WGS_1984_UTM_Zone_5S"; WGS1984UTMZone60N.Name = "WGS_1984_UTM_Zone_60N"; WGS1984UTMZone60S.Name = "WGS_1984_UTM_Zone_60S"; WGS1984UTMZone6N.Name = "WGS_1984_UTM_Zone_6N"; WGS1984UTMZone6S.Name = "WGS_1984_UTM_Zone_6S"; WGS1984UTMZone7N.Name = "WGS_1984_UTM_Zone_7N"; WGS1984UTMZone7S.Name = "WGS_1984_UTM_Zone_7S"; WGS1984UTMZone8N.Name = "WGS_1984_UTM_Zone_8N"; WGS1984UTMZone8S.Name = "WGS_1984_UTM_Zone_8S"; WGS1984UTMZone9N.Name = "WGS_1984_UTM_Zone_9N"; WGS1984UTMZone9S.Name = "WGS_1984_UTM_Zone_9S"; WGS1984ComplexUTMZone20N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone21N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone22N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone23N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone24N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone25N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone26N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone27N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone28N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone29N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone30N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone10N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone10S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone11N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone11S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone12N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone12S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone13N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone13S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone14N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone14S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone15N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone15S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone16N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone16S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone17N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone17S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone18N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone18S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone19N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone19S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone1N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone1S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone20N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone20S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone21N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone21S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone22N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone22S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone23N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone23S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone24N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone24S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone25N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone25S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone26N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone26S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone27N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone27S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone28N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone28S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone29N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone29S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone2N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone2S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone30N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone30S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone31N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone31S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone32N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone32S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone33N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone33S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone34N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone34S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone35N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone35S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone36N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone36S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone37N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone37S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone38N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone38S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone39N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone39S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone3N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone3S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone40N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone40S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone41N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone41S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone42N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone42S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone43N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone43S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone44N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone44S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone45N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone45S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone46N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone46S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone47N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone47S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone48N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone48S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone49N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone49S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone4N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone4S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone50N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone50S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone51N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone51S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone52N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone52S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone53N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone53S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone54N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone54S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone55N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone55S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone56N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone56S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone57N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone57S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone58N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone58S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone59N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone59S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone5N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone5S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone60N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone60S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone6N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone6S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone7N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone7S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone8N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone8S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone9N.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984UTMZone9S.GeographicInfo.Name = "GCS_WGS_1984"; WGS1984ComplexUTMZone20N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone21N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone22N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone23N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone24N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone25N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone26N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone27N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone28N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone29N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984ComplexUTMZone30N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone10N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone10S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone11N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone11S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone12N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone12S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone13N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone13S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone14N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone14S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone15N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone15S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone16N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone16S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone17N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone17S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone18N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone18S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone19N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone19S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone1N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone1S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone20N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone20S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone21N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone21S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone22N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone22S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone23N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone23S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone24N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone24S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone25N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone25S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone26N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone26S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone27N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone27S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone28N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone28S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone29N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone29S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone2N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone2S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone30N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone30S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone31N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone31S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone32N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone32S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone33N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone33S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone34N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone34S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone35N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone35S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone36N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone36S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone37N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone37S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone38N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone38S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone39N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone39S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone3N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone3S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone40N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone40S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone41N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone41S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone42N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone42S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone43N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone43S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone44N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone44S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone45N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone45S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone46N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone46S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone47N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone47S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone48N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone48S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone49N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone49S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone4N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone4S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone50N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone50S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone51N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone51S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone52N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone52S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone53N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone53S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone54N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone54S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone55N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone55S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone56N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone56S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone57N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone57S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone58N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone58S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone59N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone59S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone5N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone5S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone60N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone60S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone6N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone6S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone7N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone7S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone8N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone8S.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone9N.GeographicInfo.Datum.Name = "D_WGS_1984"; WGS1984UTMZone9S.GeographicInfo.Datum.Name = "D_WGS_1984"; } #endregion } } #pragma warning restore 1591
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// Queue to provide sliding window capabilities for auto size functionality /// It provides caching capabilities (either the first N objects in a group /// or all the objects in a group) /// </summary> internal sealed class OutputGroupQueue { /// <summary> /// Create a grouping cache. /// </summary> /// <param name="callBack">Notification callback to be called when the desired number of objects is reached.</param> /// <param name="objectCount">Max number of objects to be cached.</param> internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification callBack, int objectCount) { _notificationCallBack = callBack; _objectCount = objectCount; } /// <summary> /// Create a time-bounded grouping cache. /// </summary> /// <param name="callBack">Notification callback to be called when the desired number of objects is reached.</param> /// <param name="groupingDuration">Max amount of time to cache of objects.</param> internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification callBack, TimeSpan groupingDuration) { _notificationCallBack = callBack; _groupingDuration = groupingDuration; } /// <summary> /// Add an object to the cache. /// </summary> /// <param name="o">Object to add.</param> /// <returns>Objects the cache needs to return. It can be null.</returns> internal List<PacketInfoData> Add(PacketInfoData o) { FormatStartData fsd = o as FormatStartData; if (fsd != null) { // just cache the reference (used during the notification call) _formatStartData = fsd; } UpdateObjectCount(o); // STATE TRANSITION: we are not processing and we start if (!_processingGroup && (o is GroupStartData)) { // just set the flag and start caching _processingGroup = true; _currentObjectCount = 0; if (_groupingDuration > TimeSpan.MinValue) { _groupingTimer = Stopwatch.StartNew(); } _queue.Enqueue(o); return null; } // STATE TRANSITION: we are processing and we stop if (_processingGroup && ((o is GroupEndData) || (_objectCount > 0) && (_currentObjectCount >= _objectCount)) || ((_groupingTimer != null) && (_groupingTimer.Elapsed > _groupingDuration)) ) { // reset the object count _currentObjectCount = 0; if (_groupingTimer != null) { _groupingTimer.Stop(); _groupingTimer = null; } // add object to queue, to be picked up _queue.Enqueue(o); // we are at the end of a group, drain the queue Notify(); _processingGroup = false; List<PacketInfoData> retVal = new List<PacketInfoData>(); while (_queue.Count > 0) { retVal.Add(_queue.Dequeue()); } return retVal; } // NO STATE TRANSITION: check the state we are in if (_processingGroup) { // we are in the caching state _queue.Enqueue(o); return null; } // we are not processing, so just return it List<PacketInfoData> ret = new List<PacketInfoData>(); ret.Add(o); return ret; } private void UpdateObjectCount(PacketInfoData o) { // add only of it's not a control message // and it's not out of band FormatEntryData fed = o as FormatEntryData; if (fed == null || fed.outOfBand) return; _currentObjectCount++; } private void Notify() { if (_notificationCallBack == null) return; // filter out the out of band data, since they do not participate in the // auto resize algorithm List<PacketInfoData> validObjects = new List<PacketInfoData>(); foreach (PacketInfoData x in _queue) { FormatEntryData fed = x as FormatEntryData; if (fed != null && fed.outOfBand) continue; validObjects.Add(x); } _notificationCallBack(_formatStartData, validObjects); } /// <summary> /// Remove a single object from the queue. /// </summary> /// <returns>Object retrieved, null if queue is empty.</returns> internal PacketInfoData Dequeue() { if (_queue.Count == 0) return null; return _queue.Dequeue(); } /// <summary> /// Queue to store the currently cached objects. /// </summary> private readonly Queue<PacketInfoData> _queue = new Queue<PacketInfoData>(); /// <summary> /// Number of objects to compute the best fit. /// Zero: all the objects /// a positive number N: use the first N. /// </summary> private readonly int _objectCount = 0; /// <summary> /// Maximum amount of time for record processing to compute the best fit. /// MaxValue: all the objects. /// A positive timespan: use all objects that have been processed within the timeframe. /// </summary> private readonly TimeSpan _groupingDuration = TimeSpan.MinValue; private Stopwatch _groupingTimer = null; /// <summary> /// Notification callback to be called when we have accumulated enough /// data to compute a hint. /// </summary> private readonly FormattedObjectsCache.ProcessCachedGroupNotification _notificationCallBack = null; /// <summary> /// Reference kept to be used during notification. /// </summary> private FormatStartData _formatStartData = null; /// <summary> /// State flag to signal we are queuing. /// </summary> private bool _processingGroup = false; /// <summary> /// Current object count. /// </summary> private int _currentObjectCount = 0; } /// <summary> /// Facade class managing the front end and the autosize cache. /// </summary> internal sealed class FormattedObjectsCache { /// <summary> /// Delegate to allow notifications when the autosize queue is about to be drained. /// </summary> /// <param name="formatStartData">Current Fs control message.</param> /// <param name="objects">Enumeration of PacketInfoData objects.</param> internal delegate void ProcessCachedGroupNotification(FormatStartData formatStartData, List<PacketInfoData> objects); /// <summary> /// Decide right away if we need a front end cache (e.g. printing) /// </summary> /// <param name="cacheFrontEnd">If true, create a front end cache object.</param> internal FormattedObjectsCache(bool cacheFrontEnd) { if (cacheFrontEnd) _frontEndQueue = new Queue<PacketInfoData>(); } /// <summary> /// If needed, add a back end autosize (grouping) cache. /// </summary> /// <param name="callBack">Notification callback to be called when the desired number of objects is reached.</param> /// <param name="objectCount">Max number of objects to be cached.</param> internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, int objectCount) { if (callBack != null) _groupQueue = new OutputGroupQueue(callBack, objectCount); } /// <summary> /// If needed, add a back end autosize (grouping) cache. /// </summary> /// <param name="callBack">Notification callback to be called when the desired number of objects is reached.</param> /// <param name="groupingDuration">Max amount of time to cache of objects.</param> internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, TimeSpan groupingDuration) { if (callBack != null) _groupQueue = new OutputGroupQueue(callBack, groupingDuration); } /// <summary> /// Add an object to the cache. the behavior depends on the object added, the /// objects already in the cache and the cache settings. /// </summary> /// <param name="o">Object to add.</param> /// <returns>List of objects the cache is flushing.</returns> internal List<PacketInfoData> Add(PacketInfoData o) { // if neither there, pass thru if (_frontEndQueue == null && _groupQueue == null) { List<PacketInfoData> retVal = new List<PacketInfoData>(); retVal.Add(o); return retVal; } // if front present, add to front if (_frontEndQueue != null) { _frontEndQueue.Enqueue(o); return null; } // if back only, add to back return _groupQueue.Add(o); } /// <summary> /// Remove all the objects from the cache. /// </summary> /// <returns>All the objects that were in the cache.</returns> internal List<PacketInfoData> Drain() { // if neither there,we did not cache at all if (_frontEndQueue == null && _groupQueue == null) { return null; } List<PacketInfoData> retVal = new List<PacketInfoData>(); if (_frontEndQueue != null) { if (_groupQueue == null) { // drain the front queue and return the data while (_frontEndQueue.Count > 0) retVal.Add(_frontEndQueue.Dequeue()); return retVal; } // move from the front to the back queue while (_frontEndQueue.Count > 0) { List<PacketInfoData> groupQueueOut = _groupQueue.Add(_frontEndQueue.Dequeue()); if (groupQueueOut != null) foreach (PacketInfoData x in groupQueueOut) retVal.Add(x); } } // drain the back queue while (true) { PacketInfoData obj = _groupQueue.Dequeue(); if (obj == null) break; retVal.Add(obj); } return retVal; } /// <summary> /// Front end queue (if present, cache ALL, if not, bypass) /// </summary> private readonly Queue<PacketInfoData> _frontEndQueue; /// <summary> /// Back end grouping queue. /// </summary> private OutputGroupQueue _groupQueue = null; } }