context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace Nancy.Diagnostics { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Nancy.Bootstrapper; using Nancy.Configuration; using Nancy.Cookies; using Nancy.Cryptography; using Nancy.Culture; using Nancy.Json; using Nancy.Localization; using Nancy.ModelBinding; using Nancy.Responses; using Nancy.Responses.Negotiation; using Nancy.Routing; using Nancy.Routing.Constraints; using Nancy.Routing.Trie; /// <summary> /// Pipeline hook to handle diagnostics dashboard requests. /// </summary> public static class DiagnosticsHook { private static readonly CancellationToken CancellationToken = new CancellationToken(); private const string PipelineKey = "__Diagnostics"; internal const string ItemsKey = "DIAGS_REQUEST"; /// <summary> /// Enables the diagnostics dashboard and will intercept all requests that are passed to /// the condigured paths. /// </summary> public static void Enable(IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable<IResponseProcessor> responseProcessors, IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable<IRouteMetadataProvider> routeMetadataProviders, ITextResource textResource, INancyEnvironment environment) { var diagnosticsConfiguration = environment.GetValue<DiagnosticsConfiguration>(); var diagnosticsEnvironment = GetDiagnosticsEnvironment(); var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment); var diagnosticsRouteCache = new RouteCache( diagnosticsModuleCatalog, new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource, environment), new DefaultRouteSegmentExtractor(), new DefaultRouteDescriptionProvider(), cultureService, routeMetadataProviders); var diagnosticsRouteResolver = new DefaultRouteResolver( diagnosticsModuleCatalog, new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator, diagnosticsEnvironment, environment), diagnosticsRouteCache, new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints)), environment); var serializer = new DefaultObjectSerializer(); pipelines.BeforeRequest.AddItemToStartOfPipeline( new PipelineItem<Func<NancyContext, Response>>( PipelineKey, ctx => { if (!ctx.ControlPanelEnabled) { return null; } if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase)) { return null; } ctx.Items[ItemsKey] = true; var resourcePrefix = string.Concat(diagnosticsConfiguration.Path, "/Resources/"); if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase)) { var resourceNamespace = "Nancy.Diagnostics.Resources"; var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty; if (!string.IsNullOrEmpty(path)) { resourceNamespace += string.Format(".{0}", path.Replace(Path.DirectorySeparatorChar, '.')); } return new EmbeddedFileResponse( typeof(DiagnosticsHook).Assembly, resourceNamespace, Path.GetFileName(ctx.Request.Url.Path)); } RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx); return ValidateConfiguration(diagnosticsConfiguration) ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer, diagnosticsEnvironment) : GetDiagnosticsHelpView(ctx, diagnosticsEnvironment); })); } /// <summary> /// Gets a special <see cref="INancyEnvironment"/> instance that is separate from the /// one used by the application. /// </summary> /// <returns></returns> private static INancyEnvironment GetDiagnosticsEnvironment() { var diagnosticsEnvironment = new DefaultNancyEnvironment(); diagnosticsEnvironment.Json(retainCasing: false); diagnosticsEnvironment.AddValue(ViewConfiguration.Default); return diagnosticsEnvironment; } private static bool ValidateConfiguration(DiagnosticsConfiguration configuration) { return !string.IsNullOrWhiteSpace(configuration.Password) && !string.IsNullOrWhiteSpace(configuration.CookieName) && !string.IsNullOrWhiteSpace(configuration.Path) && configuration.SlidingTimeout != 0; } public static void Disable(IPipelines pipelines) { pipelines.BeforeRequest.RemoveByName(PipelineKey); } private static Response GetDiagnosticsHelpView(NancyContext ctx, INancyEnvironment environment) { return (StaticConfiguration.IsRunningDebug) ? new DiagnosticsViewRenderer(ctx, environment)["help"] : HttpStatusCode.NotFound; } private static Response GetDiagnosticsLoginView(NancyContext ctx, INancyEnvironment environment) { var renderer = new DiagnosticsViewRenderer(ctx, environment); return renderer["login"]; } private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer, INancyEnvironment environment) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); if (session == null) { var view = GetDiagnosticsLoginView(ctx, environment); view.WithCookie( new NancyCookie(diagnosticsConfiguration.CookieName, string.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return view; } var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Parameters; ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before); if (ctx.Response == null) { // Don't care about async here, so just get the result var task = resolveResult.Route.Invoke(resolveResult.Parameters, CancellationToken); task.Wait(); ctx.Response = task.Result; } if (ctx.Request.Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase)) { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResult.After != null) { resolveResult.After.Invoke(ctx, CancellationToken); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); return ctx.Response; } private static void AddUpdateSessionCookie(DiagnosticsSession session, NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { if (context.Response == null) { return; } session.Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout); var serializedSession = serializer.Serialize(session); var encryptedSession = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Encrypt(serializedSession); var hmacBytes = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession); var hmacString = Convert.ToBase64String(hmacBytes); var cookie = new NancyCookie(diagnosticsConfiguration.CookieName, string.Format("{1}{0}", encryptedSession, hmacString), true); context.Response.WithCookie(cookie); } private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { if (context.Request == null) { return null; } if (IsLoginRequest(context, diagnosticsConfiguration)) { return ProcessLogin(context, diagnosticsConfiguration, serializer); } if (!context.Request.Cookies.ContainsKey(diagnosticsConfiguration.CookieName)) { return null; } var encryptedValue = context.Request.Cookies[diagnosticsConfiguration.CookieName]; var hmacStringLength = Base64Helpers.GetBase64Length(diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength); var encryptedSession = encryptedValue.Substring(hmacStringLength); var hmacString = encryptedValue.Substring(0, hmacStringLength); var hmacBytes = Convert.FromBase64String(hmacString); var newHmac = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession); var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength); if (!hmacValid) { return null; } var decryptedValue = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Decrypt(encryptedSession); var session = serializer.Deserialize(decryptedValue) as DiagnosticsSession; if (session == null || session.Expiry < DateTime.Now || !SessionPasswordValid(session, diagnosticsConfiguration.Password)) { return null; } return session; } private static bool SessionPasswordValid(DiagnosticsSession session, string realPassword) { var newHash = DiagnosticsSession.GenerateSaltedHash(realPassword, session.Salt); return (newHash.Length == session.Hash.Length && newHash.SequenceEqual(session.Hash)); } private static DiagnosticsSession ProcessLogin(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { string password = context.Request.Form.Password; if (!string.Equals(password, diagnosticsConfiguration.Password, StringComparison.Ordinal)) { return null; } var salt = DiagnosticsSession.GenerateRandomSalt(); var hash = DiagnosticsSession.GenerateSaltedHash(password, salt); var session = new DiagnosticsSession { Hash = hash, Salt = salt, Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout) }; return session; } private static bool IsLoginRequest(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration) { return context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase) && context.Request.Url.BasePath.TrimEnd('/').EndsWith(diagnosticsConfiguration.Path) && context.Request.Url.Path == "/"; } private static void ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq) { if (resolveResultPreReq == null) { return; } var resolveResultPreReqResponse = resolveResultPreReq.Invoke(context, cancellationToken).Result; if (resolveResultPreReqResponse != null) { context.Response = resolveResultPreReqResponse; } } private static void RewriteDiagnosticsUrl(DiagnosticsConfiguration diagnosticsConfiguration, NancyContext ctx) { ctx.Request.Url.BasePath = string.Concat(ctx.Request.Url.BasePath, diagnosticsConfiguration.Path); ctx.Request.Url.Path = ctx.Request.Url.Path.Substring(diagnosticsConfiguration.Path.Length); if (ctx.Request.Url.Path.Length.Equals(0)) { ctx.Request.Url.Path = "/"; } } } }
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.CloudFront.Model { /// <summary> /// <para> A complex type that describes how CloudFront processes requests. You can create up to 10 cache behaviors.You must create at least as /// many cache behaviors (including the default cache behavior) as you have origins if you want CloudFront to distribute objects from all of the /// origins. Each cache behavior specifies the one origin from which you want CloudFront to get objects. If you have two origins and only the /// default cache behavior, the default cache behavior will cause CloudFront to get objects from one of the origins, but the other origin will /// never be used. If you don't want to specify any cache behaviors, include only an empty CacheBehaviors element. Don't include an empty /// CacheBehavior element, or CloudFront returns a MalformedXML error. To delete all cache behaviors in an existing distribution, update the /// distribution configuration and include only an empty CacheBehaviors element. To add, change, or remove one or more cache behaviors, update /// the distribution configuration and specify all of the cache behaviors that you want to include in the updated distribution. </para> /// </summary> public class CacheBehavior { private string pathPattern; private string targetOriginId; private ForwardedValues forwardedValues; private TrustedSigners trustedSigners; private string viewerProtocolPolicy; private long? minTTL; /// <summary> /// The pattern (for example, images/*.jpg) that specifies which requests you want this cache behavior to apply to. When CloudFront receives an /// end-user request, the requested path is compared with path patterns in the order in which cache behaviors are listed in the distribution. /// The path pattern for the default cache behavior is * and cannot be changed. If the request for an object does not match the path pattern for /// any cache behaviors, CloudFront applies the behavior in the default cache behavior. /// /// </summary> public string PathPattern { get { return this.pathPattern; } set { this.pathPattern = value; } } /// <summary> /// Sets the PathPattern property /// </summary> /// <param name="pathPattern">The value to set for the PathPattern property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CacheBehavior WithPathPattern(string pathPattern) { this.pathPattern = pathPattern; return this; } // Check to see if PathPattern property is set internal bool IsSetPathPattern() { return this.pathPattern != null; } /// <summary> /// The value of ID for the origin that you want CloudFront to route requests to when a request matches the path pattern either for a cache /// behavior or for the default cache behavior. /// /// </summary> public string TargetOriginId { get { return this.targetOriginId; } set { this.targetOriginId = value; } } /// <summary> /// Sets the TargetOriginId property /// </summary> /// <param name="targetOriginId">The value to set for the TargetOriginId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CacheBehavior WithTargetOriginId(string targetOriginId) { this.targetOriginId = targetOriginId; return this; } // Check to see if TargetOriginId property is set internal bool IsSetTargetOriginId() { return this.targetOriginId != null; } /// <summary> /// A complex type that specifies how CloudFront handles query strings and cookies. /// /// </summary> public ForwardedValues ForwardedValues { get { return this.forwardedValues; } set { this.forwardedValues = value; } } /// <summary> /// Sets the ForwardedValues property /// </summary> /// <param name="forwardedValues">The value to set for the ForwardedValues property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CacheBehavior WithForwardedValues(ForwardedValues forwardedValues) { this.forwardedValues = forwardedValues; return this; } // Check to see if ForwardedValues property is set internal bool IsSetForwardedValues() { return this.forwardedValues != null; } /// <summary> /// A complex type that specifies the AWS accounts, if any, that you want to allow to create signed URLs for private content. If you want to /// require signed URLs in requests for objects in the target origin that match the PathPattern for this cache behavior, specify true for /// Enabled, and specify the applicable values for Quantity and Items. For more information, go to Using a Signed URL to Serve Private Content /// in the Amazon CloudFront Developer Guide. If you don't want to require signed URLs in requests for objects that match PathPattern, specify /// false for Enabled and 0 for Quantity. Omit Items. To add, change, or remove one or more trusted signers, change Enabled to true (if it's /// currently false), change Quantity as applicable, and specify all of the trusted signers that you want to include in the updated /// distribution. /// /// </summary> public TrustedSigners TrustedSigners { get { return this.trustedSigners; } set { this.trustedSigners = value; } } /// <summary> /// Sets the TrustedSigners property /// </summary> /// <param name="trustedSigners">The value to set for the TrustedSigners property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CacheBehavior WithTrustedSigners(TrustedSigners trustedSigners) { this.trustedSigners = trustedSigners; return this; } // Check to see if TrustedSigners property is set internal bool IsSetTrustedSigners() { return this.trustedSigners != null; } /// <summary> /// Use this element to specify the protocol that users can use to access the files in the origin specified by TargetOriginId when a request /// matches the path pattern in PathPattern. If you want CloudFront to allow end users to use any available protocol, specify allow-all. If you /// want CloudFront to require HTTPS, specify https. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>allow-all, https-only</description> /// </item> /// </list> /// </para> /// </summary> public string ViewerProtocolPolicy { get { return this.viewerProtocolPolicy; } set { this.viewerProtocolPolicy = value; } } /// <summary> /// Sets the ViewerProtocolPolicy property /// </summary> /// <param name="viewerProtocolPolicy">The value to set for the ViewerProtocolPolicy property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CacheBehavior WithViewerProtocolPolicy(string viewerProtocolPolicy) { this.viewerProtocolPolicy = viewerProtocolPolicy; return this; } // Check to see if ViewerProtocolPolicy property is set internal bool IsSetViewerProtocolPolicy() { return this.viewerProtocolPolicy != null; } /// <summary> /// The minimum amount of time that you want objects to stay in CloudFront caches before CloudFront queries your origin to see whether the /// object has been updated.You can specify a value from 0 to 3,153,600,000 seconds (100 years). /// /// </summary> public long MinTTL { get { return this.minTTL ?? default(long); } set { this.minTTL = value; } } /// <summary> /// Sets the MinTTL property /// </summary> /// <param name="minTTL">The value to set for the MinTTL property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CacheBehavior WithMinTTL(long minTTL) { this.minTTL = minTTL; return this; } // Check to see if MinTTL property is set internal bool IsSetMinTTL() { return this.minTTL.HasValue; } } }
using System; using System.Collections.Generic; namespace System.Workflow.ComponentModel { [Flags] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public enum DependencyPropertyOptions : byte { Default = 1, ReadOnly = 2, Optional = 4, Metadata = 8, NonSerialized = 16, DelegateProperty = 32 } //overrides so you dont need to do inheritence public delegate object GetValueOverride(DependencyObject d); public delegate void SetValueOverride(DependencyObject d, object value); [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class PropertyMetadata { private Attribute[] attributes = null; private object defaultValue = null; private DependencyPropertyOptions options = DependencyPropertyOptions.Default; private bool propertySealed = false; private GetValueOverride getValueOverride = null; private SetValueOverride setValueOverride = null; private bool shouldAlwaysCallOverride = false; public PropertyMetadata() { } public PropertyMetadata(object defaultValue) : this(defaultValue, default(DependencyPropertyOptions)) { } public PropertyMetadata(DependencyPropertyOptions options) : this(null, options) { } public PropertyMetadata(object defaultValue, DependencyPropertyOptions options) : this(defaultValue, options, null, null, new Attribute[] { }) { } public PropertyMetadata(object defaultValue, params Attribute[] attributes) : this(defaultValue, default(DependencyPropertyOptions), null, null, attributes) { } public PropertyMetadata(object defaultValue, DependencyPropertyOptions options, params Attribute[] attributes) : this(defaultValue, options, null, null, attributes) { } public PropertyMetadata(DependencyPropertyOptions options, params Attribute[] attributes) : this(null, options, null, null, attributes) { } public PropertyMetadata(params Attribute[] attributes) : this(null, default(DependencyPropertyOptions), null, null, attributes) { } public PropertyMetadata(object defaultValue, DependencyPropertyOptions options, GetValueOverride getValueOverride, SetValueOverride setValueOverride) : this(defaultValue, options, getValueOverride, setValueOverride, new Attribute[] { }) { } public PropertyMetadata(object defaultValue, DependencyPropertyOptions options, GetValueOverride getValueOverride, SetValueOverride setValueOverride, params Attribute[] attributes) : this(defaultValue, options, getValueOverride, setValueOverride, false, attributes) { } internal PropertyMetadata(object defaultValue, DependencyPropertyOptions options, GetValueOverride getValueOverride, SetValueOverride setValueOverride, bool shouldAlwaysCallOverride, params Attribute[] attributes) { this.defaultValue = defaultValue; this.options = options; this.getValueOverride = getValueOverride; this.setValueOverride = setValueOverride; this.shouldAlwaysCallOverride = shouldAlwaysCallOverride; this.attributes = attributes; } public Attribute[] GetAttributes() { return GetAttributes(null); } public Attribute[] GetAttributes(Type attributeType) { List<Attribute> attributes = new List<Attribute>(); if (this.attributes != null) { foreach (Attribute attribute in this.attributes) { if (attribute == null) continue; if (attributeType == null || attribute.GetType() == attributeType) attributes.Add(attribute); } } return attributes.ToArray(); } public object DefaultValue { get { return this.defaultValue; } set { if (this.propertySealed) throw new InvalidOperationException(SR.GetString(SR.Error_SealedPropertyMetadata)); this.defaultValue = value; } } public DependencyPropertyOptions Options { get { return this.options; } set { if (this.propertySealed) throw new InvalidOperationException(SR.GetString(SR.Error_SealedPropertyMetadata)); this.options = value; } } public bool IsMetaProperty { get { return (this.options & DependencyPropertyOptions.Metadata) > 0; } } public bool IsNonSerialized { get { return (this.options & DependencyPropertyOptions.NonSerialized) > 0; } } public bool IsReadOnly { get { return (this.options & DependencyPropertyOptions.ReadOnly) > 0; } } public GetValueOverride GetValueOverride { get { return this.getValueOverride; } set { if (this.propertySealed) throw new InvalidOperationException(SR.GetString(SR.Error_SealedPropertyMetadata)); this.getValueOverride = value; } } public SetValueOverride SetValueOverride { get { return this.setValueOverride; } set { if (this.propertySealed) throw new InvalidOperationException(SR.GetString(SR.Error_SealedPropertyMetadata)); this.setValueOverride = value; } } protected virtual void OnApply(DependencyProperty dependencyProperty, Type targetType) { } protected bool IsSealed { get { return this.propertySealed; } } internal bool ShouldAlwaysCallOverride { get { return shouldAlwaysCallOverride; } } internal void Seal(DependencyProperty dependencyProperty, Type targetType) { OnApply(dependencyProperty, targetType); this.propertySealed = true; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; namespace System { public struct Decimal { [Pure][Reads(ReadsAttribute.Reads.Nothing)] public TypeCode GetTypeCode () { return default(TypeCode); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool operator >= (Decimal d1, Decimal d2) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool operator > (Decimal d1, Decimal d2) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool operator <= (Decimal d1, Decimal d2) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool operator < (Decimal d1, Decimal d2) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool operator != (Decimal d1, Decimal d2) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool operator == (Decimal d1, Decimal d2) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal operator % (Decimal d1, Decimal d2) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal operator / (Decimal d1, Decimal d2) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal operator * (Decimal d1, Decimal d2) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal operator - (Decimal d1, Decimal d2) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal operator + (Decimal d1, Decimal d2) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal operator -- (Decimal d) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal operator ++ (Decimal d) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal operator - (Decimal d) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal operator + (Decimal d) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator double (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator Single (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator UInt64 (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator Int64 (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator UInt32 (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator int (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator UInt16 (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator Int16 (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator Char (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator SByte (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator byte (Decimal value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator Decimal (double value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static explicit operator Decimal (Single value) { return default(explicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static implicit operator Decimal (UInt64 value) { return default(implicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static implicit operator Decimal (Int64 value) { return default(implicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static implicit operator Decimal (UInt32 value) { return default(implicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static implicit operator Decimal (int value) { return default(implicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static implicit operator Decimal (Char value) { return default(implicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static implicit operator Decimal (UInt16 value) { return default(implicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static implicit operator Decimal (Int16 value) { return default(implicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static implicit operator Decimal (SByte value) { return default(implicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static implicit operator Decimal (byte value) { return default(implicit); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Truncate (Decimal arg0) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public string ToString (IFormatProvider provider) { return default(string); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Single ToSingle (Decimal arg0) { return default(Single); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static UInt64 ToUInt64 (Decimal d) { return default(UInt64); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static UInt32 ToUInt32 (Decimal d) { return default(UInt32); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static UInt16 ToUInt16 (Decimal value) { return default(UInt16); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Int64 ToInt64 (Decimal d) { return default(Int64); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static int ToInt32 (Decimal d) { return default(int); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static double ToDouble (Decimal arg0) { return default(double); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Int16 ToInt16 (Decimal value) { return default(Int16); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static SByte ToSByte (Decimal value) { return default(SByte); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static byte ToByte (Decimal value) { return default(byte); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Subtract (Decimal arg0, Decimal arg1) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Round (Decimal arg0, int arg1) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Negate (Decimal d) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Multiply (Decimal arg0, Decimal arg1) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Remainder (Decimal arg0, Decimal arg1) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Int32[] GetBits (Decimal d) { return default(Int32[]); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Parse (string s, IFormatProvider provider) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Parse (string s, System.Globalization.NumberStyles style) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Parse (string s) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public string ToString (string format, IFormatProvider provider) { return default(string); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public string ToString (string format) { return default(string); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public string ToString () { return default(string); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Floor (Decimal arg0) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool Equals (Decimal d1, Decimal d2) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public int GetHashCode () { return default(int); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public bool Equals (object value) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Divide (Decimal arg0, Decimal arg1) { return default(Decimal); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public int CompareTo (object value) { return default(int); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static int Compare (Decimal arg0, Decimal arg1) { return default(int); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Decimal Add (Decimal arg0, Decimal arg1) { return default(Decimal); } public Decimal (int lo, int mid, int hi, bool isNegative, byte scale) { CodeContract.Requires(scale <= 28); return default(Decimal); } public Decimal (Int32[]! bits) { CodeContract.Requires(bits != null); CodeContract.Requires(bits.Length == 4); return default(Decimal); } public static Decimal FromOACurrency (Int64 cy) { return default(Decimal); } public static Int64 ToOACurrency (Decimal value) { return default(Int64); } public Decimal (double arg0) { return default(Decimal); } public Decimal (Single arg0) { return default(Decimal); } public Decimal (UInt64 value) { return default(Decimal); } public Decimal (Int64 value) { return default(Decimal); } public Decimal (UInt32 value) { return default(Decimal); } public Decimal (int value) { return default(Decimal); } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Cassandra.IntegrationTests.Linq.Structures; using Cassandra.IntegrationTests.Mapping.Structures; using Cassandra.IntegrationTests.SimulacronAPI; using Cassandra.IntegrationTests.SimulacronAPI.Models.Logs; using Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then; using Cassandra.IntegrationTests.TestBase; using Cassandra.Mapping; using Cassandra.Mapping.Attributes; using NUnit.Framework; #pragma warning disable 169 #pragma warning disable 618 #pragma warning disable 612 using Linq = Cassandra.Data.Linq; namespace Cassandra.IntegrationTests.Mapping.Tests { public class Attributes : SimulacronTest { private const string IgnoredStringAttribute = "ignoredstringattribute"; private Linq::Table<T> GetTable<T>() { return new Linq::Table<T>(Session, new MappingConfiguration()); } private IMapper GetMapper() { return new Mapper(Session, new MappingConfiguration()); } /// <summary> /// Validate that the mapping mechanism ignores the field marked with mapping attribute "Ignore" /// </summary> [Test] public void Attributes_Ignore_TableCreatedWithMappingAttributes() { var definition = new AttributeBasedTypeDefinition(typeof(PocoWithIgnoredAttributes)); var table = new Linq::Table<PocoWithIgnoredAttributes>(Session, new MappingConfiguration().Define(definition)); Assert.AreNotEqual(table.Name, table.Name.ToLower()); table.Create(); VerifyQuery( "CREATE TABLE PocoWithIgnoredAttributes " + "(SomeNonIgnoredDouble double, SomePartitionKey text, " + "PRIMARY KEY (SomePartitionKey))", 1); //var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); var mapper = new Mapper(Session, new MappingConfiguration()); var pocoToUpload = new PocoWithIgnoredAttributes { SomePartitionKey = Guid.NewGuid().ToString(), IgnoredStringAttribute = Guid.NewGuid().ToString(), }; mapper.Insert(pocoToUpload); VerifyBoundStatement( "INSERT INTO PocoWithIgnoredAttributes (SomeNonIgnoredDouble, SomePartitionKey) " + "VALUES (?, ?)", 1, pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey); var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where \"somepartitionkey\"='{pocoToUpload.SomePartitionKey}'"; // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { "somenonignoreddouble", "somepartitionkey" }, r => r.WithRow(pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey))); var records = mapper.Fetch<PocoWithIgnoredAttributes>(cqlSelect).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoToUpload.SomePartitionKey, records[0].SomePartitionKey); var defaultPoco = new PocoWithIgnoredAttributes(); Assert.AreNotEqual(defaultPoco.IgnoredStringAttribute, pocoToUpload.IgnoredStringAttribute); Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute); Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoToUpload.SomePartitionKey, rows[0].GetValue<string>("somepartitionkey")); Assert.AreEqual(pocoToUpload.SomeNonIgnoredDouble, rows[0].GetValue<double>("somenonignoreddouble")); // Verify there was no column created for the ignored column var e = Assert.Throws<ArgumentException>(() => rows[0].GetValue<string>(IgnoredStringAttribute)); var expectedErrMsg = "Column " + IgnoredStringAttribute + " not found"; Assert.AreEqual(expectedErrMsg, e.Message); } /// <summary> /// Validate that the mapping mechanism ignores the field marked with mapping attribute "Ignore" /// </summary> [Test] public void Attributes_Ignore() { var table = GetTable<PocoWithIgnoredAttributes>(); Assert.AreNotEqual(table.Name, table.Name.ToLower()); table.Create(); VerifyQuery( "CREATE TABLE PocoWithIgnoredAttributes " + "(SomeNonIgnoredDouble double, SomePartitionKey text, " + "PRIMARY KEY (SomePartitionKey))", 1); var mapper = GetMapper(); var pocoToUpload = new PocoWithIgnoredAttributes { SomePartitionKey = Guid.NewGuid().ToString(), IgnoredStringAttribute = Guid.NewGuid().ToString(), }; mapper.Insert(pocoToUpload); VerifyBoundStatement( "INSERT INTO PocoWithIgnoredAttributes (SomeNonIgnoredDouble, SomePartitionKey) " + "VALUES (?, ?)", 1, pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey); var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where \"{"somepartitionkey"}\"='{pocoToUpload.SomePartitionKey}'"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { "somenonignoreddouble", "somepartitionkey" }, r => r.WithRow(pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = mapper.Fetch<PocoWithIgnoredAttributes>(cqlSelect).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoToUpload.SomePartitionKey, records[0].SomePartitionKey); var defaultPoco = new PocoWithIgnoredAttributes(); Assert.AreNotEqual(defaultPoco.IgnoredStringAttribute, pocoToUpload.IgnoredStringAttribute); Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute); Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoToUpload.SomePartitionKey, rows[0].GetValue<string>("somepartitionkey")); Assert.AreEqual(pocoToUpload.SomeNonIgnoredDouble, rows[0].GetValue<double>("somenonignoreddouble")); // Verify there was no column created for the ignored column var e = Assert.Throws<ArgumentException>(() => rows[0].GetValue<string>(IgnoredStringAttribute)); var expectedErrMsg = "Column " + IgnoredStringAttribute + " not found"; Assert.AreEqual(expectedErrMsg, e.Message); } /// <summary> /// Validate that the mapping mechanism ignores the class variable marked as "Ignore" /// The fact that the request does not fail trying to find a non-existing custom named column proves that /// the request is not looking for the column for reads or writes. /// /// This also validates that attributes from Cassandra.Mapping and Cassandra.Data.Linq can be used successfully on the same object /// </summary> [Test] public void Attributes_Ignore_LinqAndMappingAttributes() { var config = new MappingConfiguration(); config.MapperFactory.PocoDataFactory.AddDefinitionDefault( typeof(PocoWithIgnrdAttr_LinqAndMapping), () => Linq::LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithIgnrdAttr_LinqAndMapping))); var table = new Linq::Table<PocoWithIgnrdAttr_LinqAndMapping>(Session, config); table.Create(); VerifyQuery( "CREATE TABLE \"pocowithignrdattr_linqandmapping\" " + "(\"ignoredstringattribute\" text, \"somenonignoreddouble\" double, " + "\"somepartitionkey\" text, PRIMARY KEY (\"somepartitionkey\"))", 1); var cqlClient = GetMapper(); var pocoToInsert = new PocoWithIgnrdAttr_LinqAndMapping { SomePartitionKey = Guid.NewGuid().ToString(), IgnoredStringAttribute = Guid.NewGuid().ToString(), }; cqlClient.Insert(pocoToInsert); VerifyBoundStatement( "INSERT INTO PocoWithIgnrdAttr_LinqAndMapping (SomeNonIgnoredDouble, SomePartitionKey) " + "VALUES (?, ?)", 1, pocoToInsert.SomeNonIgnoredDouble, pocoToInsert.SomePartitionKey); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var cqlSelect = "SELECT * from " + table.Name; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("somenonignoreddouble", DataType.Double), ("somepartitionkey", DataType.Text), ("ignoredstringattribute", DataType.Text) }, r => r.WithRow( pocoToInsert.SomeNonIgnoredDouble, pocoToInsert.SomePartitionKey, null))); var records = cqlClient.Fetch<PocoWithIgnrdAttr_LinqAndMapping>(cqlSelect).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoToInsert.SomePartitionKey, records[0].SomePartitionKey); var defaultPoco = new PocoWithIgnrdAttr_LinqAndMapping(); Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute); Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoToInsert.SomePartitionKey, rows[0].GetValue<string>("somepartitionkey")); Assert.AreEqual(pocoToInsert.SomeNonIgnoredDouble, rows[0].GetValue<double>("somenonignoreddouble")); Assert.AreEqual(null, rows[0].GetValue<string>(IgnoredStringAttribute)); } /// <summary> /// Verify that inserting a mapped object that totally omits the Cassandra.Mapping.Attributes.PartitionKey silently fails. /// However, using mapping and a different Poco that has the key, records can be inserted and fetched into the same table /// </summary> [Test] public void Attributes_InsertFailsWhenPartitionKeyAttributeOmitted_FixedWithMapping() { // Setup var tableName = typeof(PocoWithPartitionKeyOmitted).Name.ToLower(); var selectAllCql = "SELECT * from " + tableName; var stringList = new List<string> { "string1", "string2" }; // Instantiate CqlClient with mapping rule that resolves the missing key issue var cqlClientWithMappping = new Mapper(Session, new MappingConfiguration().Define(new PocoWithPartitionKeyIncludedMapping())); // insert new record var pocoWithCustomAttributesKeyIncluded = new PocoWithPartitionKeyIncluded(); pocoWithCustomAttributesKeyIncluded.SomeList = stringList; // make it not empty cqlClientWithMappping.Insert(pocoWithCustomAttributesKeyIncluded); VerifyBoundStatement( $"INSERT INTO {tableName} (SomeDouble, SomeList, somestring) " + "VALUES (?, ?, ?)", 1, pocoWithCustomAttributesKeyIncluded.SomeDouble, pocoWithCustomAttributesKeyIncluded.SomeList, pocoWithCustomAttributesKeyIncluded.SomeString); TestCluster.PrimeFluent( b => b.WhenQuery(selectAllCql) .ThenRowsSuccess( new[] { "somedouble", "somelist", "somestring" }, r => r.WithRow( pocoWithCustomAttributesKeyIncluded.SomeDouble, pocoWithCustomAttributesKeyIncluded.SomeList, pocoWithCustomAttributesKeyIncluded.SomeString))); var records1 = cqlClientWithMappping.Fetch<PocoWithPartitionKeyIncluded>(selectAllCql).ToList(); Assert.AreEqual(1, records1.Count); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeString, records1[0].SomeString); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeList, records1[0].SomeList); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeDouble, records1[0].SomeDouble); records1.Clear(); var rows = Session.Execute(selectAllCql).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeString, rows[0].GetValue<string>("somestring")); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeList, rows[0].GetValue<List<string>>("somelist")); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeDouble, rows[0].GetValue<double>("somedouble")); // try to Select new record using poco that does not contain partition key, validate that the mapping mechanism matches what it can var cqlClientNomapping = GetMapper(); var records2 = cqlClientNomapping.Fetch<PocoWithPartitionKeyOmitted>(selectAllCql).ToList(); Assert.AreEqual(1, records2.Count); records2.Clear(); // try again with the old CqlClient instance records1 = cqlClientWithMappping.Fetch<PocoWithPartitionKeyIncluded>(selectAllCql).ToList(); Assert.AreEqual(1, records1.Count); } /// <summary> /// Verify that inserting a mapped object without specifying Cassandra.Mapping.Attributes.PartitionKey does not fail /// This also validates that not all columns need to be included for the Poco insert / fetch to succeed /// </summary> [Test, TestCassandraVersion(2, 0)] public void Attributes_PartitionKeyNotLabeled() { var tableName = typeof(PocoWithOnlyPartitionKeyNotLabeled).Name; var cqlClient = GetMapper(); var pocoWithOnlyCustomAttributes = new PocoWithOnlyPartitionKeyNotLabeled(); cqlClient.Insert(pocoWithOnlyCustomAttributes); VerifyBoundStatement( $"INSERT INTO {tableName} (SomeString) " + "VALUES (?)", 1, pocoWithOnlyCustomAttributes.SomeString); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + tableName) .ThenRowsSuccess( new[] { ("somedouble", DataType.Double), ("somelist", DataType.List(DataType.Text)), ("somestring", DataType.Text) }, r => r.WithRow( null, null, pocoWithOnlyCustomAttributes.SomeString))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = cqlClient.Fetch<PocoWithOnlyPartitionKeyNotLabeled>("SELECT * from " + tableName).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoWithOnlyCustomAttributes.SomeString, records[0].SomeString); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute("SELECT * from " + tableName).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoWithOnlyCustomAttributes.SomeString, rows[0].GetValue<string>("somestring")); } /// <summary> /// Verify that inserting a mapped object without including PartitionKey succeeds when it is not the only field in the Poco class /// </summary> [Test, TestCassandraVersion(2, 0)] public void Attributes_PartitionKeyNotLabeled_AnotherNonLabelFieldIncluded() { var tableName = typeof(PocoWithPartitionKeyNotLabeledAndOtherField).Name; var cqlClient = GetMapper(); var pocoWithOnlyCustomAttributes = new PocoWithPartitionKeyNotLabeledAndOtherField(); cqlClient.Insert(pocoWithOnlyCustomAttributes); VerifyBoundStatement( $"INSERT INTO {tableName} (SomeOtherString, SomeString) " + "VALUES (?, ?)", 1, pocoWithOnlyCustomAttributes.SomeOtherString, pocoWithOnlyCustomAttributes.SomeString); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + tableName) .ThenRowsSuccess( new[] { ("somedouble", DataType.Double), ("somelist", DataType.List(DataType.Text)), ("somestring", DataType.Text), ("someotherstring", DataType.Text) }, r => r.WithRow( null, null, pocoWithOnlyCustomAttributes.SomeString, pocoWithOnlyCustomAttributes.SomeOtherString))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = cqlClient.Fetch<PocoWithPartitionKeyNotLabeledAndOtherField>("SELECT * from " + tableName).ToList(); Assert.AreEqual(1, records.Count); } /// <summary> /// Verify that inserting a mapped object, mislabeling the PartitionKey as a Clustering Key does not fail /// </summary> [Test] public void Attributes_MislabledClusteringKey() { var tableName = typeof(PocoMislabeledClusteringKey).Name; var cqlClient = GetMapper(); var pocoWithCustomAttributes = new PocoMislabeledClusteringKey(); cqlClient.Insert(pocoWithCustomAttributes); // TODO: Should this fail? VerifyBoundStatement( $"INSERT INTO {tableName} (SomeString) " + "VALUES (?)", 1, pocoWithCustomAttributes.SomeString); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + tableName) .ThenRowsSuccess( new[] { ("somestring", DataType.Varchar) }, r => r.WithRow(pocoWithCustomAttributes.SomeString))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = cqlClient.Fetch<PocoMislabeledClusteringKey>("SELECT * from " + tableName).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoWithCustomAttributes.SomeString, records[0].SomeString); } /// <summary> /// Successfully insert Poco object which have values that are part of a composite key /// </summary> [Test] public void Attributes_CompositeKey() { var tableName = typeof(PocoWithCompositeKey).Name; var definition = new AttributeBasedTypeDefinition(typeof(PocoWithCompositeKey)); var table = new Linq::Table<PocoWithCompositeKey>(Session, new MappingConfiguration().Define(definition)); table.Create(); VerifyQuery( $"CREATE TABLE {tableName} (ListOfGuids list<uuid>, SomePartitionKey1 text, SomePartitionKey2 text, " + "PRIMARY KEY ((SomePartitionKey1, SomePartitionKey2)))", 1); var listOfGuids = new List<Guid> { new Guid(), new Guid() }; var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); var pocoWithCustomAttributes = new PocoWithCompositeKey { ListOfGuids = listOfGuids, SomePartitionKey1 = Guid.NewGuid().ToString(), SomePartitionKey2 = Guid.NewGuid().ToString(), IgnoredString = Guid.NewGuid().ToString(), }; mapper.Insert(pocoWithCustomAttributes); VerifyBoundStatement( $"INSERT INTO {tableName} (ListOfGuids, SomePartitionKey1, SomePartitionKey2) VALUES (?, ?, ?)", 1, pocoWithCustomAttributes.ListOfGuids, pocoWithCustomAttributes.SomePartitionKey1, pocoWithCustomAttributes.SomePartitionKey2); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + tableName) .ThenRowsSuccess( new[] { ("listofguids", DataType.List(DataType.Uuid)), ("somepartitionkey1", DataType.Text), ("somepartitionkey2", DataType.Text) }, r => r.WithRow( pocoWithCustomAttributes.ListOfGuids, pocoWithCustomAttributes.SomePartitionKey1, pocoWithCustomAttributes.SomePartitionKey2))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = mapper.Fetch<PocoWithCompositeKey>("SELECT * from " + table.Name).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, records[0].SomePartitionKey1); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, records[0].SomePartitionKey2); Assert.AreEqual(pocoWithCustomAttributes.ListOfGuids, records[0].ListOfGuids); Assert.AreEqual(new PocoWithCompositeKey().IgnoredString, records[0].IgnoredString); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute("SELECT * from " + table.Name).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, rows[0].GetValue<string>("somepartitionkey1")); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, rows[0].GetValue<string>("somepartitionkey2")); Assert.AreEqual(pocoWithCustomAttributes.ListOfGuids, rows[0].GetValue<List<Guid>>("listofguids")); var ex = Assert.Throws<ArgumentException>(() => rows[0].GetValue<string>("ignoredstring")); Assert.AreEqual("Column ignoredstring not found", ex.Message); } /// <summary> /// Successfully insert Poco object which have values that are part of a composite key /// </summary> [Test] public void Attributes_MultipleClusteringKeys() { var config = new MappingConfiguration(); config.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(PocoWithClusteringKeys), () => Linq::LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithClusteringKeys))); var table = new Linq::Table<PocoWithClusteringKeys>(Session, config); table.Create(); VerifyQuery( "CREATE TABLE \"pocowithclusteringkeys\" (" + "\"guid1\" uuid, \"guid2\" uuid, \"somepartitionkey1\" text, \"somepartitionkey2\" text, " + "PRIMARY KEY ((\"somepartitionkey1\", \"somepartitionkey2\"), \"guid1\", \"guid2\"))", 1); var cqlClient = new Mapper(Session, config); var pocoWithCustomAttributes = new PocoWithClusteringKeys { SomePartitionKey1 = Guid.NewGuid().ToString(), SomePartitionKey2 = Guid.NewGuid().ToString(), Guid1 = Guid.NewGuid(), Guid2 = Guid.NewGuid(), }; cqlClient.Insert(pocoWithCustomAttributes); VerifyBoundStatement( "INSERT INTO \"pocowithclusteringkeys\" (" + "\"guid1\", \"guid2\", \"somepartitionkey1\", \"somepartitionkey2\") " + "VALUES (?, ?, ?, ?)", 1, pocoWithCustomAttributes.Guid1, pocoWithCustomAttributes.Guid2, pocoWithCustomAttributes.SomePartitionKey1, pocoWithCustomAttributes.SomePartitionKey2); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + table.Name) .ThenRowsSuccess( new[] { ("guid1", DataType.Uuid), ("guid2", DataType.Uuid), ("somepartitionkey1", DataType.Text), ("somepartitionkey2", DataType.Text) }, r => r.WithRow( pocoWithCustomAttributes.Guid1, pocoWithCustomAttributes.Guid2, pocoWithCustomAttributes.SomePartitionKey1, pocoWithCustomAttributes.SomePartitionKey2))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = cqlClient.Fetch<PocoWithClusteringKeys>("SELECT * from " + table.Name).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, records[0].SomePartitionKey1); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, records[0].SomePartitionKey2); Assert.AreEqual(pocoWithCustomAttributes.Guid1, records[0].Guid1); Assert.AreEqual(pocoWithCustomAttributes.Guid2, records[0].Guid2); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute("SELECT * from " + table.Name).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, rows[0].GetValue<string>("somepartitionkey1")); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, rows[0].GetValue<string>("somepartitionkey2")); Assert.AreEqual(pocoWithCustomAttributes.Guid1, rows[0].GetValue<Guid>("guid1")); Assert.AreEqual(pocoWithCustomAttributes.Guid2, rows[0].GetValue<Guid>("guid2")); } /// <summary> /// Expect a "missing partition key" failure upon create since there was no field specific to the class being created /// that was marked as partition key. /// This happens despite the matching partition key names since they reside in different classes. /// </summary> [Test] public void Attributes_Mapping_MisMatchedClassTypesButTheSamePartitionKeyName() { var mapping = new Map<SimplePocoWithPartitionKey>(); mapping.CaseSensitive(); mapping.PartitionKey(u => u.StringType); var table = new Linq::Table<ManyDataTypesPoco>(Session, new MappingConfiguration().Define(mapping)); // Validate expected Exception var ex = Assert.Throws<InvalidOperationException>(table.Create); StringAssert.Contains("No partition key defined", ex.Message); } /// <summary> /// The Partition key Attribute from the Poco class is used to create a table with a partition key /// </summary> [Test] public void Attributes_ClusteringKey_NoName() { var table = GetTable<EmptyClusteringColumnName>(); table.Create(); VerifyQuery( "CREATE TABLE \"test_map_empty_clust_column_name\" (\"cluster\" text, \"id\" int, \"value\" text, " + "PRIMARY KEY (\"id\", \"cluster\"))", 1); var definition = new AttributeBasedTypeDefinition(typeof(EmptyClusteringColumnName)); var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); var pocoToUpload = new EmptyClusteringColumnName { Id = 1, cluster = "c2", value = "v2" }; mapper.Insert(pocoToUpload); VerifyBoundStatement( "INSERT INTO test_map_empty_clust_column_name (cluster, id, value) VALUES (?, ?, ?)", 1, pocoToUpload.cluster, pocoToUpload.Id, pocoToUpload.value); var cqlSelect = $"SELECT * from {table.Name} where id={pocoToUpload.Id}"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("cluster", DataType.Text), ("id", DataType.Int), ("value", DataType.Text) }, r => r.WithRow(pocoToUpload.cluster, pocoToUpload.Id, pocoToUpload.value))); var instancesQueried = mapper.Fetch<EmptyClusteringColumnName>(cqlSelect).ToList(); Assert.AreEqual(1, instancesQueried.Count); Assert.AreEqual(pocoToUpload.Id, instancesQueried[0].Id); Assert.AreEqual(pocoToUpload.cluster, instancesQueried[0].cluster); Assert.AreEqual(pocoToUpload.value, instancesQueried[0].value); } /// <summary> /// The Partition key Attribute from the Poco class is used to create a table with a partition key /// </summary> [Test] public void Attributes_PartitionKey() { var table = GetTable<SimplePocoWithPartitionKey>(); Assert.AreNotEqual(table.Name, table.Name.ToLower()); table.Create(); VerifyQuery( "CREATE TABLE SimplePocoWithPartitionKey (StringTyp text, StringType text, StringTypeNotPartitionKey text, " + "PRIMARY KEY (StringType))", 1); var cqlClient = GetMapper(); var pocoToUpload = new SimplePocoWithPartitionKey(); cqlClient.Insert(pocoToUpload); VerifyBoundStatement( "INSERT INTO SimplePocoWithPartitionKey (StringTyp, StringType, StringTypeNotPartitionKey) VALUES (?, ?, ?)", 1, pocoToUpload.StringTyp, pocoToUpload.StringType, pocoToUpload.StringTypeNotPartitionKey); var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where \"{"stringtype"}\"='{pocoToUpload.StringType}'"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("StringTyp", DataType.Text), ("StringType", DataType.Text), ("StringTypeNotPartitionKey", DataType.Text) }, r => r.WithRow( pocoToUpload.StringTyp, pocoToUpload.StringType, pocoToUpload.StringTypeNotPartitionKey))); var instancesQueried = cqlClient.Fetch<SimplePocoWithPartitionKey>(cqlSelect).ToList(); Assert.AreEqual(1, instancesQueried.Count); Assert.AreEqual(pocoToUpload.StringType, instancesQueried[0].StringType); Assert.AreEqual(pocoToUpload.StringTyp, instancesQueried[0].StringTyp); Assert.AreEqual(pocoToUpload.StringTypeNotPartitionKey, instancesQueried[0].StringTypeNotPartitionKey); } /// <summary> /// Expect the mapping mechanism to recognize / use the Partition key Attribute from /// the Poco class it's derived from /// </summary> [Test, TestCassandraVersion(2, 0)] public void Attributes_SecondaryIndex() { var table = GetTable<SimplePocoWithSecondaryIndex>(); table.Create(); VerifyQuery( "CREATE TABLE SimplePocoWithSecondaryIndex (SomePartitionKey text, SomeSecondaryIndex int, " + "PRIMARY KEY (SomePartitionKey))", 1); VerifyQuery("CREATE INDEX ON SimplePocoWithSecondaryIndex (SomeSecondaryIndex)", 1); var cqlClient = GetMapper(); var expectedTotalRecords = 10; var defaultInstance = new SimplePocoWithSecondaryIndex(); var entities = new List<SimplePocoWithSecondaryIndex>(); for (var i = 0; i < expectedTotalRecords; i++) { var entity = new SimplePocoWithSecondaryIndex(i); entities.Add(entity); cqlClient.Insert(entity); } var logs = TestCluster.GetQueries(null, QueryType.Execute); foreach (var entity in entities) { VerifyStatement( logs, "INSERT INTO SimplePocoWithSecondaryIndex (SomePartitionKey, SomeSecondaryIndex) VALUES (?, ?)", 1, entity.SomePartitionKey, entity.SomeSecondaryIndex); } // Select using basic cql var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where {"somesecondaryindex"}={defaultInstance.SomeSecondaryIndex} order by {"somepartitionkey"} desc"; TestCluster.PrimeFluent( b => b.WhenQuery("SELECT SomePartitionKey, SomeSecondaryIndex FROM SimplePocoWithSecondaryIndex") .ThenRowsSuccess( new[] { ("somepartitionkey", DataType.Text), ("somesecondaryindex", DataType.Int) }, r => r.WithRows(entities.Select(entity => new object[] { entity.SomePartitionKey, entity.SomeSecondaryIndex }).ToArray()))); TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenServerError(ServerError.Invalid, "ORDER BY with 2ndary indexes is not supported.")); var instancesQueried = cqlClient.Fetch<SimplePocoWithSecondaryIndex>().ToList(); Assert.AreEqual(expectedTotalRecords, instancesQueried.Count); var ex = Assert.Throws<InvalidQueryException>(() => cqlClient.Fetch<SimplePocoWithSecondaryIndex>(cqlSelect)); Assert.AreEqual("ORDER BY with 2ndary indexes is not supported.", ex.Message); } /// <summary> /// Expect the mapping mechanism to recognize / use the Column Attribute from /// the Poco class it's derived from /// </summary> [Test] public void Attributes_Column_NoCustomLabel() { // Setup var expectedTotalRecords = 1; var definition = new AttributeBasedTypeDefinition(typeof(SimplePocoWithColumnAttribute)); var table = new Linq::Table<SimplePocoWithColumnAttribute>(Session, new MappingConfiguration().Define(definition)); Assert.AreNotEqual(table.Name, table.Name.ToLower()); table.Create(); VerifyQuery( "CREATE TABLE SimplePocoWithColumnAttribute (SomeColumn int, SomePartitionKey text, PRIMARY KEY (SomePartitionKey))", 1); var defaultInstance = new SimplePocoWithColumnAttribute(); var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); mapper.Insert(defaultInstance); VerifyBoundStatement( "INSERT INTO SimplePocoWithColumnAttribute (SomeColumn, SomePartitionKey) VALUES (?, ?)", 1, defaultInstance.SomeColumn, defaultInstance.SomePartitionKey); // Validate using mapped Fetch var cqlSelectAll = "select * from " + table.Name.ToLower(); TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelectAll) .ThenRowsSuccess( new[] { ("somecolumn", DataType.Int), ("somepartitionkey", DataType.Text) }, r => r.WithRow(defaultInstance.SomeColumn, defaultInstance.SomePartitionKey))); var instancesQueried = mapper.Fetch<SimplePocoWithColumnAttribute>(cqlSelectAll).ToList(); Assert.AreEqual(expectedTotalRecords, instancesQueried.Count); var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where {"somepartitionkey"}='{defaultInstance.SomePartitionKey}'"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("somecolumn", DataType.Int), ("somepartitionkey", DataType.Text) }, r => r.WithRow(defaultInstance.SomeColumn, defaultInstance.SomePartitionKey))); var actualObjectsInOrder = mapper.Fetch<SimplePocoWithColumnAttribute>(cqlSelect).ToList(); Assert.AreEqual(expectedTotalRecords, actualObjectsInOrder.Count); // Validate using straight cql to verify column names var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(expectedTotalRecords, rows.Count); Assert.AreEqual(defaultInstance.SomeColumn, rows[0].GetValue<int>("somecolumn")); } /// <summary> /// Expect the mapping mechanism to recognize / use the Column Attribute from /// the Poco class it's derived from, including the custom label option /// </summary> [Test, TestCassandraVersion(2, 0)] public void Attributes_Column_CustomLabels() { // Setup var expectedTotalRecords = 1; var definition = new AttributeBasedTypeDefinition(typeof(SimplePocoWithColumnLabel_CustomColumnName)); var table = new Linq::Table<SimplePocoWithColumnLabel_CustomColumnName>(Session, new MappingConfiguration().Define(definition)); Assert.AreEqual(typeof(SimplePocoWithColumnLabel_CustomColumnName).Name, table.Name); // Assert table name is case sensitive now Assert.AreNotEqual(typeof(SimplePocoWithColumnLabel_CustomColumnName).Name, typeof(SimplePocoWithColumnLabel_CustomColumnName).Name.ToLower()); // Assert table name is case senstive table.Create(); VerifyQuery( "CREATE TABLE SimplePocoWithColumnLabel_CustomColumnName (someCaseSensitivePartitionKey text, some_column_label_thats_different int, " + "PRIMARY KEY (someCaseSensitivePartitionKey))", 1); var defaultInstance = new SimplePocoWithColumnLabel_CustomColumnName(); var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); mapper.Insert(defaultInstance); VerifyBoundStatement( "INSERT INTO SimplePocoWithColumnLabel_CustomColumnName (someCaseSensitivePartitionKey, some_column_label_thats_different) " + "VALUES (?, ?)", 1, defaultInstance.SomePartitionKey, defaultInstance.SomeColumn); // Validate using mapped Fetch var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where {"someCaseSensitivePartitionKey"}='{defaultInstance.SomePartitionKey}'"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("some_column_label_thats_different", DataType.Int), ("someCaseSensitivePartitionKey", DataType.Text) }, r => r.WithRow(defaultInstance.SomeColumn, defaultInstance.SomePartitionKey))); var actualObjectsInOrder = mapper.Fetch<SimplePocoWithColumnLabel_CustomColumnName>(cqlSelect).ToList(); Assert.AreEqual(expectedTotalRecords, actualObjectsInOrder.Count); Assert.AreEqual(defaultInstance.SomeColumn, actualObjectsInOrder[0].SomeColumn); // Validate using straight cql to verify column names var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(expectedTotalRecords, rows.Count); Assert.AreEqual(defaultInstance.SomeColumn, rows[0].GetValue<int>("some_column_label_thats_different")); } ///////////////////////////////////////// /// Private test classes ///////////////////////////////////////// [Table("SimplePocoWithColumnLabel_CustomColumnName")] public class SimplePocoWithColumnLabel_CustomColumnName { [Column("someCaseSensitivePartitionKey")] [PartitionKey] public string SomePartitionKey = "defaultPartitionKeyVal"; [Column("some_column_label_thats_different")] public int SomeColumn = 191991919; } public class SimplePocoWithColumnAttribute { [PartitionKey] public string SomePartitionKey = "defaultPartitionKeyVal"; [Column] public int SomeColumn = 121212121; } public class SimplePocoWithSecondaryIndex { [PartitionKey] public string SomePartitionKey; [SecondaryIndex] public int SomeSecondaryIndex = 1; public SimplePocoWithSecondaryIndex() { } public SimplePocoWithSecondaryIndex(int i) { SomePartitionKey = "partitionKey_" + i; } } private class SimplePocoWithPartitionKey { public string StringTyp = "someStringValue"; [PartitionKey] public string StringType = "someStringValue"; public string StringTypeNotPartitionKey = "someStringValueNotPk"; } private class PocoWithIgnoredAttributes { [PartitionKey] public string SomePartitionKey = "somePartitionKeyDefaultValue"; public double SomeNonIgnoredDouble = 123456; [Cassandra.Mapping.Attributes.Ignore] public string IgnoredStringAttribute = "someIgnoredString"; } /// <summary> /// Test poco class that uses both Linq and Cassandra.Mapping attributes at the same time /// </summary> [Linq::Table("pocowithignrdattr_linqandmapping")] private class PocoWithIgnrdAttr_LinqAndMapping { [Linq::PartitionKey] [PartitionKey] [Linq::Column("somepartitionkey")] public string SomePartitionKey = "somePartitionKeyDefaultValue"; [Linq::Column("somenonignoreddouble")] public double SomeNonIgnoredDouble = 123456; [Cassandra.Mapping.Attributes.Ignore] [Linq::Column(Attributes.IgnoredStringAttribute)] public string IgnoredStringAttribute = "someIgnoredString"; } /// <summary> /// See PocoWithIgnoredAttributes for correctly implemented counterpart /// </summary> [Linq::Table("pocowithwrongfieldlabeledpk")] private class PocoWithWrongFieldLabeledPk { [Linq::PartitionKey] [Linq::Column("somepartitionkey")] public string SomePartitionKey = "somePartitionKeyDefaultValue"; [Linq::Column("somenonignoreddouble")] public double SomeNonIgnoredDouble = 123456; [PartitionKey] [Linq::Column("someotherstring")] public string SomeOtherString = "someOtherString"; } /// <summary> /// Class with Mapping.Attributes.Partition key ommitted /// </summary> private class PocoWithOnlyPartitionKeyNotLabeled { public string SomeString = "somestring_value"; } /// <summary> /// Class with Mapping.Attributes.Partition key ommitted, as well as another field that is not labeled /// </summary> private class PocoWithPartitionKeyNotLabeledAndOtherField { public string SomeString = "somestring_value"; public string SomeOtherString = "someotherstring_value"; } /// <summary> /// Class with Mapping.Attributes.Partition key ommitted /// </summary> private class PocoMislabeledClusteringKey { [ClusteringKey] public string SomeString = "someStringValue"; } /// <summary> /// Class with Mapping.Attributes.Partition key ommitted /// </summary> private class PocoWithPartitionKeyOmitted { public double SomeDouble = 123456; public List<string> SomeList = new List<string>(); } /// <summary> /// Class with Mapping.Attributes.Partition key included, which was missing from PocoWithPartitionKeyOmitted /// </summary> private class PocoWithPartitionKeyIncluded { [PartitionKey] public string SomeString = "somePartitionKeyDefaultValue"; public double SomeDouble = 123456; public List<string> SomeList = new List<string>(); } /// <summary> /// Class designed to fix the issue with PocoWithPartitionKeyOmitted, which is implied by the name /// </summary> private class PocoWithPartitionKeyIncludedMapping : Map<PocoWithPartitionKeyIncluded> { public PocoWithPartitionKeyIncludedMapping() { TableName(typeof(PocoWithPartitionKeyOmitted).Name.ToLower()); PartitionKey(u => u.SomeString); Column(u => u.SomeString, cm => cm.WithName("somestring")); } } [Linq::Table("pocowithcompositekey")] private class PocoWithCompositeKey { [Linq::PartitionKey(1)] [PartitionKey(1)] [Linq::Column("somepartitionkey1")] public string SomePartitionKey1 = "somepartitionkey1_val"; [Linq::PartitionKey(2)] [PartitionKey(2)] [Linq::Column("somepartitionkey2")] public string SomePartitionKey2 = "somepartitionkey2_val"; [Linq::Column("listofguids")] public List<Guid> ListOfGuids; [Cassandra.Mapping.Attributes.Ignore] [Linq::Column("ignoredstring")] public string IgnoredString = "someIgnoredString_val"; } [Linq::Table("pocowithclusteringkeys")] private class PocoWithClusteringKeys { [Linq::PartitionKey(1)] [PartitionKey(1)] [Linq::Column("somepartitionkey1")] public string SomePartitionKey1 = "somepartitionkey1_val"; [Linq::PartitionKey(2)] [PartitionKey(2)] [Linq::Column("somepartitionkey2")] public string SomePartitionKey2 = "somepartitionkey2_val"; [Linq::ClusteringKey(1)] [ClusteringKey(1)] [Linq::Column("guid1")] public Guid Guid1; [Linq::ClusteringKey(2)] [ClusteringKey(2)] [Linq::Column("guid2")] public Guid Guid2; } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// UserInformationList /// </summary> [DataContract] public partial class UserInformationList : IEquatable<UserInformationList>, IValidatableObject { public UserInformationList() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="UserInformationList" /> class. /// </summary> /// <param name="EndPosition">The last position in the result set. .</param> /// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param> /// <param name="PreviousUri">The postal code for the billing address..</param> /// <param name="ResultSetSize">The number of results returned in this response. .</param> /// <param name="StartPosition">Starting position of the current result set..</param> /// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param> /// <param name="Users">Users.</param> public UserInformationList(string EndPosition = default(string), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string), List<UserInformation> Users = default(List<UserInformation>)) { this.EndPosition = EndPosition; this.NextUri = NextUri; this.PreviousUri = PreviousUri; this.ResultSetSize = ResultSetSize; this.StartPosition = StartPosition; this.TotalSetSize = TotalSetSize; this.Users = Users; } /// <summary> /// The last position in the result set. /// </summary> /// <value>The last position in the result set. </value> [DataMember(Name="endPosition", EmitDefaultValue=false)] public string EndPosition { get; set; } /// <summary> /// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. /// </summary> /// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value> [DataMember(Name="nextUri", EmitDefaultValue=false)] public string NextUri { get; set; } /// <summary> /// The postal code for the billing address. /// </summary> /// <value>The postal code for the billing address.</value> [DataMember(Name="previousUri", EmitDefaultValue=false)] public string PreviousUri { get; set; } /// <summary> /// The number of results returned in this response. /// </summary> /// <value>The number of results returned in this response. </value> [DataMember(Name="resultSetSize", EmitDefaultValue=false)] public string ResultSetSize { get; set; } /// <summary> /// Starting position of the current result set. /// </summary> /// <value>Starting position of the current result set.</value> [DataMember(Name="startPosition", EmitDefaultValue=false)] public string StartPosition { get; set; } /// <summary> /// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response. /// </summary> /// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value> [DataMember(Name="totalSetSize", EmitDefaultValue=false)] public string TotalSetSize { get; set; } /// <summary> /// Gets or Sets Users /// </summary> [DataMember(Name="users", EmitDefaultValue=false)] public List<UserInformation> Users { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class UserInformationList {\n"); sb.Append(" EndPosition: ").Append(EndPosition).Append("\n"); sb.Append(" NextUri: ").Append(NextUri).Append("\n"); sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n"); sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n"); sb.Append(" StartPosition: ").Append(StartPosition).Append("\n"); sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n"); sb.Append(" Users: ").Append(Users).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as UserInformationList); } /// <summary> /// Returns true if UserInformationList instances are equal /// </summary> /// <param name="other">Instance of UserInformationList to be compared</param> /// <returns>Boolean</returns> public bool Equals(UserInformationList other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.EndPosition == other.EndPosition || this.EndPosition != null && this.EndPosition.Equals(other.EndPosition) ) && ( this.NextUri == other.NextUri || this.NextUri != null && this.NextUri.Equals(other.NextUri) ) && ( this.PreviousUri == other.PreviousUri || this.PreviousUri != null && this.PreviousUri.Equals(other.PreviousUri) ) && ( this.ResultSetSize == other.ResultSetSize || this.ResultSetSize != null && this.ResultSetSize.Equals(other.ResultSetSize) ) && ( this.StartPosition == other.StartPosition || this.StartPosition != null && this.StartPosition.Equals(other.StartPosition) ) && ( this.TotalSetSize == other.TotalSetSize || this.TotalSetSize != null && this.TotalSetSize.Equals(other.TotalSetSize) ) && ( this.Users == other.Users || this.Users != null && this.Users.SequenceEqual(other.Users) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.EndPosition != null) hash = hash * 59 + this.EndPosition.GetHashCode(); if (this.NextUri != null) hash = hash * 59 + this.NextUri.GetHashCode(); if (this.PreviousUri != null) hash = hash * 59 + this.PreviousUri.GetHashCode(); if (this.ResultSetSize != null) hash = hash * 59 + this.ResultSetSize.GetHashCode(); if (this.StartPosition != null) hash = hash * 59 + this.StartPosition.GetHashCode(); if (this.TotalSetSize != null) hash = hash * 59 + this.TotalSetSize.GetHashCode(); if (this.Users != null) hash = hash * 59 + this.Users.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
//! \file ImageTINK.cs //! \date Fri Jun 17 18:49:04 2016 //! \brief Tinker Bell encrypted image file. // // Copyright (C) 2016-2017 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.IO; using System.Windows.Media; using System.Windows.Media.Imaging; namespace GameRes.Formats.Cyberworks { public enum AImageHeader { Flags = 0, Field1 = 1, Field2 = 2, Height = 3, Width = 4, UnpackedSize = 5, AlphaSize = 6, BitsSize = 7, Ignored = Field1, } internal sealed class AImageReader : IImageDecoder { readonly ImageMetaData m_info = new ImageMetaData(); IBinaryStream m_input; byte[] m_output; AImageScheme m_scheme; ImageData m_image; int[] m_header; int m_type; public Stream Source { get { m_input.Position = 0; return m_input.AsStream; } } public ImageFormat SourceFormat { get { return null; } } public ImageMetaData Info { get { return m_info; } } public byte[] Baseline { get; set; } public int Type { get { return m_type; } } public ImageData Image { get { if (null == m_image) { Unpack(); int stride = (int)Info.Width * Info.BPP / 8; if (m_scheme.Flipped) m_image = ImageData.CreateFlipped (Info, GetPixelFormat(), null, Data, stride); else m_image = ImageData.Create (Info, GetPixelFormat(), null, Data, stride); } return m_image; } } public byte[] Data { get { return m_output; } } public AImageReader (IBinaryStream input, AImageScheme scheme, int type = 'a') { m_input = input; m_scheme = scheme; m_type = type; } internal int[] ReadHeader () { if (m_header != null) return m_header; int header_length = Math.Max (8, m_scheme.HeaderOrder.Length); m_header = new int[header_length]; for (int i = 0; i < m_scheme.HeaderOrder.Length; ++i) { int b = GetInt(); m_header[m_scheme.HeaderOrder[i]] = b; } Info.Width = (uint)m_header[4]; Info.Height = (uint)m_header[3]; return m_header; } /// <summary> /// Search archive <paramref name="arc"/> for baseline image. /// </summary> internal void ReadBaseline (BellArchive arc, Entry entry) { var header = ReadHeader(); if (!((header[0] & 1) == 1 && 'd' == this.Type || header[0] == 1 && 'a' == this.Type)) return; var scheme = arc.Scheme; var dir = (List<Entry>)arc.Dir; int i = dir.IndexOf (entry); while (--i >= 0 && "image" == dir[i].Type) { using (var input = arc.OpenEntry (dir[i])) { int type = input.ReadByte(); if ('d' == type) continue; if ('a' == type) { int id = input.ReadByte(); if (id != scheme.Value2) break; using (var bin = new BinaryStream (input, dir[i].Name)) using (var base_image = new AImageReader (bin, scheme)) { var base_header = base_image.ReadHeader(); if (1 == base_header[0]) continue; // check if image width/height are the same if (base_header[3] == header[3] && base_header[4] == header[4]) { base_image.Unpack(); Baseline = base_image.Data; } } } else if ('b' == type || 'c' == type) { var size_buf = new byte[4]; input.Read (size_buf, 0 , 4); var decoder = new PngBitmapDecoder (input, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); BitmapSource frame = decoder.Frames[0]; Info.Width = (uint)frame.PixelWidth; Info.Height = (uint)frame.PixelHeight; if (frame.Format.BitsPerPixel != 32) frame = new FormatConvertedBitmap (frame, PixelFormats.Bgra32, null, 0); int stride = frame.PixelWidth * 4; var pixels = new byte[stride * frame.PixelHeight]; frame.CopyPixels (pixels, stride, 0); Baseline = pixels; } break; } } } public void Unpack () { var header = ReadHeader(); if (0 == Info.Width || Info.Width >= 0x8000 || 0 == Info.Height || Info.Height >= 0x8000) throw new InvalidFormatException(); int flags = header[0]; int unpacked_size = header[5]; int bits_size = header[7]; if (unpacked_size <= 0) { if (0 == unpacked_size && 0 == header[6] && (1 == (flags & 1) && Baseline != null)) { UnpackV6NoAlpha (bits_size); return; } throw new InvalidFormatException(); } int data_offset = bits_size * 2; if (0 == flags) CopyV0 (unpacked_size); else if (2 == (flags & 6)) UnpackV2 (bits_size, data_offset); else if (6 == (flags & 6)) { if (0 == bits_size) CopyV6 (unpacked_size, header[6]); else if (1 == (flags & 1) && 'd' == m_type && Baseline != null) UnpackV6d (bits_size, bits_size + header[6]); else UnpackV6 (bits_size, data_offset, data_offset + header[6]); } else if (0 == bits_size) CopyV0 (unpacked_size); else UnpackV1 (bits_size, unpacked_size); } void CopyV0 (int data_size) { int plane_size = (int)Info.Width * (int)Info.Height; if (plane_size == data_size) { Info.BPP = 8; m_output = m_input.ReadBytes (data_size); } else if (3 * plane_size == data_size) { Info.BPP = 24; m_output = m_input.ReadBytes (data_size); } else if (4 * plane_size == data_size) { Info.BPP = 32; m_output = m_input.ReadBytes (data_size); } else { Info.BPP = 24; int dst_stride = (int)Info.Width * 3; int src_stride = (dst_stride + 3) & ~3; if (src_stride * (int)Info.Height != data_size) throw new InvalidFormatException(); m_output = new byte[dst_stride * (int)Info.Height]; var gap = new byte[src_stride-dst_stride]; int dst = 0; for (uint y = 0; y < Info.Height; ++y) { m_input.Read (m_output, dst, dst_stride); m_input.Read (gap, 0, gap.Length); dst += dst_stride; } } } void UnpackV1 (int alpha_size, int rgb_size) { var alpha_map = m_input.ReadBytes (alpha_size); if (alpha_map.Length != alpha_size) throw new InvalidFormatException(); int plane_size = (int)Info.Width * (int)Info.Height; if (Baseline != null) { Info.BPP = 24; m_output = Baseline; } else { Info.BPP = 32; m_output = new byte[plane_size * 4]; } int pixel_size = Info.BPP / 8; int bit = 1; int bit_src = 0; int dst = 0; for (int i = 0; i < plane_size; ++i) { byte alpha = 0; if ((bit & alpha_map[bit_src]) != 0) { m_input.Read (m_output, dst, 3); alpha = 0xFF; } if (4 == pixel_size) m_output[dst+3] = alpha; dst += pixel_size; if (0x80 == bit) { ++bit_src; bit = 1; } else bit <<= 1; } } void UnpackV2 (int offset1, int rgb_offset) { Info.BPP = 24; var rgb_map = m_input.ReadBytes (offset1); var alpha_map = m_input.ReadBytes (rgb_offset-offset1); int plane_size = (int)Info.Width * (int)Info.Height; m_output = new byte[plane_size * 3]; int bit = 1; int bit_src = 0; int dst = 0; for (int i = 0; i < plane_size; ++i) { if ((bit & alpha_map[bit_src]) == 0 && (bit & rgb_map[bit_src]) != 0) { m_input.Read (m_output, dst, 3); } dst += 3; if (0x80 == bit) { ++bit_src; bit = 1; } else bit <<= 1; } } void CopyV6 (int alpha_size, int rgb_size) { Info.BPP = 32; int plane_size = (int)Info.Width * (int)Info.Height; m_output = new byte[plane_size * 4]; int stride = ((int)Info.Width * 3 + 3) & ~3; var line = new byte[stride]; int dst = 3; for (uint y = 0; y < Info.Height; ++y) { m_input.Read (line, 0, stride); int src = 0; for (uint x = 0; x < Info.Width; ++x) { m_output[dst] = line[src]; dst += 4; src += 3; } } dst = 0; for (uint y = 0; y < Info.Height; ++y) { m_input.Read (line, 0, stride); int src = 0; for (uint x = 0; x < Info.Width; ++x) { m_output[dst ] = line[src++]; m_output[dst+1] = line[src++]; m_output[dst+2] = line[src++]; dst += 4; } } } void UnpackV6 (int offset1, int alpha_offset, int rgb_offset) { Info.BPP = 32; var rgb_map = m_input.ReadBytes (offset1); var alpha_map = m_input.ReadBytes (alpha_offset - offset1); var alpha = m_input.ReadBytes (rgb_offset - alpha_offset); int plane_size = (int)Info.Width * (int)Info.Height; m_output = new byte[plane_size * 4]; int bit = 1; int bit_src = 0; int alpha_src = 0; int dst = 0; for (int i = 0; i < plane_size; ++i) { bool has_alpha = (bit & alpha_map[bit_src]) != 0; if (has_alpha || (bit & rgb_map[bit_src]) != 0) { m_input.Read (m_output, dst, 3); if (has_alpha && alpha_src < alpha.Length) { m_output[dst+3] = alpha[alpha_src]; alpha_src += 3; } else m_output[dst+3] = 0xFF; } dst += 4; if (0x80 == bit) { ++bit_src; bit = 1; } else bit <<= 1; } } void UnpackV6d (int bits_size, int rgb_offset) { Info.BPP = 32; var rgb_map = m_input.ReadBytes (bits_size); var alpha = m_input.ReadBytes (rgb_offset - bits_size); int plane_size = Math.Min (Baseline.Length, bits_size*8); m_output = Baseline; int bit = 1; int bit_src = 0; int alpha_src = 0; int dst = 0; for (int i = 0; i < plane_size; ++i) { if ((bit & rgb_map[bit_src]) != 0) { m_input.Read (m_output, dst, 3); m_output[dst+3] = alpha[alpha_src++]; } dst += 4; bit <<= 1; if (0x100 == bit) { ++bit_src; bit = 1; } } } void UnpackV6NoAlpha (int bits_size) { var rgb_map = m_input.ReadBytes (bits_size); int plane_size = Math.Min (Baseline.Length, bits_size*8); m_output = Baseline; if (m_info.Width * m_info.Height * 3 == m_output.Length) Info.BPP = 24; else Info.BPP = 32; int bit = 1; int bit_src = 0; int dst = 0; int pixel_size = Info.BPP / 8; for (int i = 0; i < plane_size; ++i) { if ((bit & rgb_map[bit_src]) != 0) { m_input.Read (m_output, dst, 3); } dst += pixel_size; bit <<= 1; if (0x100 == bit) { ++bit_src; bit = 1; } } } int GetInt () { byte a = m_input.ReadUInt8(); if (a == m_scheme.Value3) a = 0; int d = 0; int c = 0; for (;;) { byte a1 = m_input.ReadUInt8(); if (a1 == m_scheme.Value2) break; if (a1 != m_scheme.Value1) { c = (a1 == m_scheme.Value3) ? 0 : a1; } else { ++d; } } return a + (c + d * m_scheme.Value1) * m_scheme.Value1; } PixelFormat GetPixelFormat () { switch (Info.BPP) { case 8: return PixelFormats.Gray8; case 24: return PixelFormats.Bgr24; case 32: return PixelFormats.Bgra32; default: throw new InvalidFormatException(); } } #region IDisposable Members bool _disposed = false; public void Dispose () { if (!_disposed) { m_input.Dispose(); _disposed = true; } } #endregion } }
using System; using HalconDotNet; namespace HDisplayControl.ViewROI { /// <summary> /// This class demonstrates one of the possible implementations for a /// (simple) rectangularly shaped ROI. To create this rectangle we use /// a center point (midR, midC), an orientation 'phi' and the half /// edge lengths 'length1' and 'length2', similar to the HALCON /// operator gen_rectangle2(). /// The class ROIRectangle2 inherits from the base class ROI and /// implements (besides other auxiliary methods) all virtual methods /// defined in ROI.cs. /// </summary> public class ROIRectangle2 : ROI { /// <summary>Half length of the rectangle side, perpendicular to phi</summary> private double length1; /// <summary>Half length of the rectangle side, in direction of phi</summary> private double length2; /// <summary>Row coordinate of midpoint of the rectangle</summary> private double midR; /// <summary>Column coordinate of midpoint of the rectangle</summary> private double midC; /// <summary>Orientation of rectangle defined in radians.</summary> private double phi; //auxiliary variables HTuple rowsInit; HTuple colsInit; HTuple rows; HTuple cols; HHomMat2D hom2D, tmp; /// <summary>Constructor</summary> public ROIRectangle2() { NumHandles = 6; // 4 corners + 1 midpoint + 1 rotationpoint activeHandleIdx = 4; } /// <summary>Creates a new ROI instance at the mouse position</summary> /// <param name="midX"> /// x (=column) coordinate for interactive ROI /// </param> /// <param name="midY"> /// y (=row) coordinate for interactive ROI /// </param> public override void createROI(double midX, double midY) { midR = midY; midC = midX; length1 = 100; length2 = 50; phi = 0.0; rowsInit = new HTuple(new double[] {-1.0, -1.0, 1.0, 1.0, 0.0, 0.0 }); colsInit = new HTuple(new double[] {-1.0, 1.0, 1.0, -1.0, 0.0, 0.6 }); //order ul , ur, lr, ll, mp, arrowMidpoint hom2D = new HHomMat2D(); tmp = new HHomMat2D(); updateHandlePos(); } /// <summary>Paints the ROI into the supplied window</summary> /// <param name="window">HALCON window</param> public override void draw(HalconDotNet.HWindow window) { window.DispRectangle2(midR, midC, -phi, length1, length2); for (int i =0; i < NumHandles; i++) window.DispRectangle2(rows[i].D, cols[i].D, -phi, 5, 5); window.DispArrow(midR, midC, midR + (Math.Sin(phi) * length1 * 1.2), midC + (Math.Cos(phi) * length1 * 1.2), 2.0); } /// <summary> /// Returns the distance of the ROI handle being /// closest to the image point(x,y) /// </summary> /// <param name="x">x (=column) coordinate</param> /// <param name="y">y (=row) coordinate</param> /// <returns> /// Distance of the closest ROI handle. /// </returns> public override double distToClosestHandle(double x, double y) { double max = 10000; double [] val = new double[NumHandles]; for (int i=0; i < NumHandles; i++) val[i] = HMisc.DistancePp(y, x, rows[i].D, cols[i].D); for (int i=0; i < NumHandles; i++) { if (val[i] < max) { max = val[i]; activeHandleIdx = i; } } return val[activeHandleIdx]; } /// <summary> /// Paints the active handle of the ROI object into the supplied window /// </summary> /// <param name="window">HALCON window</param> public override void displayActive(HalconDotNet.HWindow window) { window.DispRectangle2(rows[activeHandleIdx].D, cols[activeHandleIdx].D, -phi, 5, 5); if (activeHandleIdx == 5) window.DispArrow(midR, midC, midR + (Math.Sin(phi) * length1 * 1.2), midC + (Math.Cos(phi) * length1 * 1.2), 2.0); } /// <summary>Gets the HALCON region described by the ROI</summary> public override HRegion getRegion() { HRegion region = new HRegion(); region.GenRectangle2(midR, midC, -phi, length1, length2); return region; } /// <summary> /// Gets the model information described by /// the interactive ROI /// </summary> public override HTuple getModelData() { return new HTuple(new double[] { midR, midC, phi, length1, length2 }); } /// <summary> /// Recalculates the shape of the ROI instance. Translation is /// performed at the active handle of the ROI object /// for the image coordinate (x,y) /// </summary> /// <param name="newX">x mouse coordinate</param> /// <param name="newY">y mouse coordinate</param> public override void moveByHandle(double newX, double newY) { double vX, vY, x=0, y=0; switch (activeHandleIdx) { case 0: case 1: case 2: case 3: tmp = hom2D.HomMat2dInvert(); x = tmp.AffineTransPoint2d(newX, newY, out y); length2 = Math.Abs(y); length1 = Math.Abs(x); checkForRange(x, y); break; case 4: midC = newX; midR = newY; break; case 5: vY = newY - rows[4].D; vX = newX - cols[4].D; phi = Math.Atan2(vY, vX); break; } updateHandlePos(); }//end of method /// <summary> /// Auxiliary method to recalculate the contour points of /// the rectangle by transforming the initial row and /// column coordinates (rowsInit, colsInit) by the updated /// homography hom2D /// </summary> private void updateHandlePos() { hom2D.HomMat2dIdentity(); hom2D = hom2D.HomMat2dTranslate(midC, midR); hom2D = hom2D.HomMat2dRotateLocal(phi); tmp = hom2D.HomMat2dScaleLocal(length1, length2); cols = tmp.AffineTransPoint2d(colsInit, rowsInit, out rows); } /* This auxiliary method checks the half lengths * (length1, length2) using the coordinates (x,y) of the four * rectangle corners (handles 0 to 3) to avoid 'bending' of * the rectangular ROI at its midpoint, when it comes to a * 'collapse' of the rectangle for length1=length2=0. * */ private void checkForRange(double x, double y) { switch (activeHandleIdx) { case 0: if ((x < 0) && (y < 0)) return; if (x >= 0) length1 = 0.01; if (y >= 0) length2 = 0.01; break; case 1: if ((x > 0) && (y < 0)) return; if (x <= 0) length1 = 0.01; if (y >= 0) length2 = 0.01; break; case 2: if ((x > 0) && (y > 0)) return; if (x <= 0) length1 = 0.01; if (y <= 0) length2 = 0.01; break; case 3: if ((x < 0) && (y > 0)) return; if (x >= 0) length1 = 0.01; if (y <= 0) length2 = 0.01; break; default: break; } } }//end of class }//end of namespace
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: supply/packages/amendment_held_lodging_package.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Supply.Packages { /// <summary>Holder for reflection information generated from supply/packages/amendment_held_lodging_package.proto</summary> public static partial class AmendmentHeldLodgingPackageReflection { #region Descriptor /// <summary>File descriptor for supply/packages/amendment_held_lodging_package.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AmendmentHeldLodgingPackageReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjRzdXBwbHkvcGFja2FnZXMvYW1lbmRtZW50X2hlbGRfbG9kZ2luZ19wYWNr", "YWdlLnByb3RvEhtob2xtcy50eXBlcy5zdXBwbHkucGFja2FnZXMaH2dvb2ds", "ZS9wcm90b2J1Zi90aW1lc3RhbXAucHJvdG8aJXN1cHBseS9wYWNrYWdlcy9s", "b2RnaW5nX3BhY2thZ2UucHJvdG8aMXN1cHBseS9yZXNlcnZhdGlvbl9hbWVu", "ZG1lbnRfaG9sZF9pbmRpY2F0b3IucHJvdG8i2gEKG0FtZW5kbWVudEhlbGRM", "b2RnaW5nUGFja2FnZRJNCg5ob2xkX2luZGljYXRvchgBIAEoCzI1LmhvbG1z", "LnR5cGVzLnN1cHBseS5SZXNlcnZhdGlvbkFtZW5kbWVudEhvbGRJbmRpY2F0", "b3ISLgoKZXhwaXJlc19hdBgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1l", "c3RhbXASPAoHcGFja2FnZRgDIAEoCzIrLmhvbG1zLnR5cGVzLnN1cHBseS5w", "YWNrYWdlcy5Mb2RnaW5nUGFja2FnZUIvWg9zdXBwbHkvcGFja2FnZXOqAhtI", "T0xNUy5UeXBlcy5TdXBwbHkuUGFja2FnZXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::HOLMS.Types.Supply.Packages.LodgingPackageReflection.Descriptor, global::HOLMS.Types.Supply.ReservationAmendmentHoldIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.Packages.AmendmentHeldLodgingPackage), global::HOLMS.Types.Supply.Packages.AmendmentHeldLodgingPackage.Parser, new[]{ "HoldIndicator", "ExpiresAt", "Package" }, null, null, null) })); } #endregion } #region Messages public sealed partial class AmendmentHeldLodgingPackage : pb::IMessage<AmendmentHeldLodgingPackage> { private static readonly pb::MessageParser<AmendmentHeldLodgingPackage> _parser = new pb::MessageParser<AmendmentHeldLodgingPackage>(() => new AmendmentHeldLodgingPackage()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AmendmentHeldLodgingPackage> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.Packages.AmendmentHeldLodgingPackageReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AmendmentHeldLodgingPackage() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AmendmentHeldLodgingPackage(AmendmentHeldLodgingPackage other) : this() { HoldIndicator = other.holdIndicator_ != null ? other.HoldIndicator.Clone() : null; ExpiresAt = other.expiresAt_ != null ? other.ExpiresAt.Clone() : null; Package = other.package_ != null ? other.Package.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AmendmentHeldLodgingPackage Clone() { return new AmendmentHeldLodgingPackage(this); } /// <summary>Field number for the "hold_indicator" field.</summary> public const int HoldIndicatorFieldNumber = 1; private global::HOLMS.Types.Supply.ReservationAmendmentHoldIndicator holdIndicator_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.ReservationAmendmentHoldIndicator HoldIndicator { get { return holdIndicator_; } set { holdIndicator_ = value; } } /// <summary>Field number for the "expires_at" field.</summary> public const int ExpiresAtFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp expiresAt_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp ExpiresAt { get { return expiresAt_; } set { expiresAt_ = value; } } /// <summary>Field number for the "package" field.</summary> public const int PackageFieldNumber = 3; private global::HOLMS.Types.Supply.Packages.LodgingPackage package_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.Packages.LodgingPackage Package { get { return package_; } set { package_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AmendmentHeldLodgingPackage); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AmendmentHeldLodgingPackage other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(HoldIndicator, other.HoldIndicator)) return false; if (!object.Equals(ExpiresAt, other.ExpiresAt)) return false; if (!object.Equals(Package, other.Package)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (holdIndicator_ != null) hash ^= HoldIndicator.GetHashCode(); if (expiresAt_ != null) hash ^= ExpiresAt.GetHashCode(); if (package_ != null) hash ^= Package.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (holdIndicator_ != null) { output.WriteRawTag(10); output.WriteMessage(HoldIndicator); } if (expiresAt_ != null) { output.WriteRawTag(18); output.WriteMessage(ExpiresAt); } if (package_ != null) { output.WriteRawTag(26); output.WriteMessage(Package); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (holdIndicator_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(HoldIndicator); } if (expiresAt_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ExpiresAt); } if (package_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Package); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AmendmentHeldLodgingPackage other) { if (other == null) { return; } if (other.holdIndicator_ != null) { if (holdIndicator_ == null) { holdIndicator_ = new global::HOLMS.Types.Supply.ReservationAmendmentHoldIndicator(); } HoldIndicator.MergeFrom(other.HoldIndicator); } if (other.expiresAt_ != null) { if (expiresAt_ == null) { expiresAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } ExpiresAt.MergeFrom(other.ExpiresAt); } if (other.package_ != null) { if (package_ == null) { package_ = new global::HOLMS.Types.Supply.Packages.LodgingPackage(); } Package.MergeFrom(other.Package); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (holdIndicator_ == null) { holdIndicator_ = new global::HOLMS.Types.Supply.ReservationAmendmentHoldIndicator(); } input.ReadMessage(holdIndicator_); break; } case 18: { if (expiresAt_ == null) { expiresAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(expiresAt_); break; } case 26: { if (package_ == null) { package_ = new global::HOLMS.Types.Supply.Packages.LodgingPackage(); } input.ReadMessage(package_); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Stardust.Interstellar.Test.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); } } } }
#define MIKET_CHANGE using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System; using System.Collections; using System.Collections.Generic; /* The AssetBundle Manager provides a High-Level API for working with AssetBundles. The AssetBundle Manager will take care of loading AssetBundles and their associated Asset Dependencies. Initialize() Initializes the AssetBundle manifest object. LoadAssetAsync() Loads a given asset from a given AssetBundle and handles all the dependencies. LoadLevelAsync() Loads a given scene from a given AssetBundle and handles all the dependencies. LoadDependencies() Loads all the dependent AssetBundles for a given AssetBundle. BaseDownloadingURL Sets the base downloading url which is used for automatic downloading dependencies. SimulateAssetBundleInEditor Sets Simulation Mode in the Editor. Variants Sets the active variant. RemapVariantName() Resolves the correct AssetBundle according to the active variant. */ namespace AssetBundles { /// <summary> /// Loaded assetBundle contains the references count which can be used to /// unload dependent assetBundles automatically. /// </summary> public class LoadedAssetBundle { public AssetBundle m_AssetBundle; public int m_ReferencedCount; internal event Action unload; internal void OnUnload() { m_AssetBundle.Unload(false); if (unload != null) unload(); } public LoadedAssetBundle(AssetBundle assetBundle) { m_AssetBundle = assetBundle; m_ReferencedCount = 1; } } /// <summary> /// Class takes care of loading assetBundle and its dependencies /// automatically, loading variants automatically. /// </summary> public class AssetBundleManager : MonoBehaviour { public enum LogMode { All, JustErrors }; public enum LogType { Info, Warning, Error }; static LogMode m_LogMode = LogMode.All; static string m_BaseDownloadingURL = ""; static string[] m_ActiveVariants = { }; static AssetBundleManifest m_AssetBundleManifest = null; #if UNITY_EDITOR static int m_SimulateAssetBundleInEditor = -1; const string kSimulateAssetBundles = "SimulateAssetBundles"; #endif static Dictionary<string, LoadedAssetBundle> m_LoadedAssetBundles = new Dictionary<string, LoadedAssetBundle>(); static Dictionary<string, string> m_DownloadingErrors = new Dictionary<string, string>(); static List<string> m_DownloadingBundles = new List<string>(); static List<AssetBundleLoadOperation> m_InProgressOperations = new List<AssetBundleLoadOperation>(); static Dictionary<string, string[]> m_Dependencies = new Dictionary<string, string[]>(); public static LogMode logMode { get { return m_LogMode; } set { m_LogMode = value; } } /// <summary> /// The base downloading url which is used to generate the full /// downloading url with the assetBundle names. /// </summary> public static string BaseDownloadingURL { get { return m_BaseDownloadingURL; } set { m_BaseDownloadingURL = value; } } public delegate string OverrideBaseDownloadingURLDelegate(string bundleName); /// <summary> /// Implements per-bundle base downloading URL override. /// The subscribers must return null values for unknown bundle names; /// </summary> public static event OverrideBaseDownloadingURLDelegate overrideBaseDownloadingURL; /// <summary> /// Variants which is used to define the active variants. /// </summary> public static string[] ActiveVariants { get { return m_ActiveVariants; } set { m_ActiveVariants = value; } } /// <summary> /// AssetBundleManifest object which can be used to load the dependecies /// and check suitable assetBundle variants. /// </summary> public static AssetBundleManifest AssetBundleManifestObject { set { m_AssetBundleManifest = value; } } private static void Log(LogType logType, string text) { if (logType == LogType.Error) Debug.LogError("[AssetBundleManager] " + text); else if (m_LogMode == LogMode.All && logType == LogType.Warning) Debug.LogWarning("[AssetBundleManager] " + text); else if (m_LogMode == LogMode.All) Debug.Log("[AssetBundleManager] " + text); } #if UNITY_EDITOR /// <summary> /// Flag to indicate if we want to simulate assetBundles in Editor without building them actually. /// </summary> public static bool SimulateAssetBundleInEditor { get { if (m_SimulateAssetBundleInEditor == -1) m_SimulateAssetBundleInEditor = EditorPrefs.GetBool(kSimulateAssetBundles, true) ? 1 : 0; return m_SimulateAssetBundleInEditor != 0; } set { int newValue = value ? 1 : 0; if (newValue != m_SimulateAssetBundleInEditor) { m_SimulateAssetBundleInEditor = newValue; EditorPrefs.SetBool(kSimulateAssetBundles, value); } } } #endif #if !MIKET_CHANGE private static string GetStreamingAssetsPath() { if (Application.isEditor) return "file://" + System.Environment.CurrentDirectory.Replace("\\", "/"); // Use the build output folder directly. else if (Application.isWebPlayer) return System.IO.Path.GetDirectoryName(Application.absoluteURL).Replace("\\", "/") + "/StreamingAssets"; else if (Application.isMobilePlatform || Application.isConsolePlatform) return Application.streamingAssetsPath; else // For standalone player. return "file://" + Application.streamingAssetsPath; } #endif /// <summary> /// Sets base downloading URL to a directory relative to the streaming assets directory. /// Asset bundles are loaded from a local directory. /// </summary> public static void SetSourceAssetBundleDirectory(string relativePath) { #if MIKET_CHANGE throw new NotImplementedException(); #else BaseDownloadingURL = GetStreamingAssetsPath() + relativePath; #endif } /// <summary> /// Sets base downloading URL to a web URL. The directory pointed to by this URL /// on the web-server should have the same structure as the AssetBundles directory /// in the demo project root. /// </summary> /// <example>For example, AssetBundles/iOS/xyz-scene must map to /// absolutePath/iOS/xyz-scene. /// <example> public static void SetSourceAssetBundleURL(string absolutePath) { if (!absolutePath.EndsWith("/")) { absolutePath += "/"; } BaseDownloadingURL = absolutePath + Utility.GetPlatformName() + "/"; } /// <summary> /// Sets base downloading URL to a local development server URL. /// </summary> public static void SetDevelopmentAssetBundleServer() { #if UNITY_EDITOR // If we're in Editor simulation mode, we don't have to setup a download URL if (SimulateAssetBundleInEditor) return; #endif TextAsset urlFile = Resources.Load("AssetBundleServerURL") as TextAsset; string url = (urlFile != null) ? urlFile.text.Trim() : null; if (url == null || url.Length == 0) { Log(LogType.Error, "Development Server URL could not be found."); } else { AssetBundleManager.SetSourceAssetBundleURL(url); } } /// <summary> /// Retrieves an asset bundle that has previously been requested via LoadAssetBundle. /// Returns null if the asset bundle or one of its dependencies have not been downloaded yet. /// </summary> static public LoadedAssetBundle GetLoadedAssetBundle(string assetBundleName, out string error) { if (m_DownloadingErrors.TryGetValue(assetBundleName, out error)) return null; LoadedAssetBundle bundle = null; m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle); if (bundle == null) return null; // No dependencies are recorded, only the bundle itself is required. string[] dependencies = null; if (!m_Dependencies.TryGetValue(assetBundleName, out dependencies)) return bundle; // Make sure all dependencies are loaded foreach (var dependency in dependencies) { if (m_DownloadingErrors.TryGetValue(dependency, out error)) return null; // Wait all the dependent assetBundles being loaded. LoadedAssetBundle dependentBundle; m_LoadedAssetBundles.TryGetValue(dependency, out dependentBundle); if (dependentBundle == null) return null; } return bundle; } /// <summary> /// Returns true if certain asset bundle has been downloaded without checking /// whether the dependencies have been loaded. /// </summary> static public bool IsAssetBundleDownloaded(string assetBundleName) { return m_LoadedAssetBundles.ContainsKey(assetBundleName); } /// <summary> /// Initializes asset bundle namager and starts download of manifest asset bundle. /// Returns the manifest asset bundle downolad operation object. /// </summary> static public AssetBundleLoadManifestOperation Initialize() { return Initialize(Utility.GetPlatformName()); } /// <summary> /// Initializes asset bundle namager and starts download of manifest asset bundle. /// Returns the manifest asset bundle downolad operation object. /// </summary> static public AssetBundleLoadManifestOperation Initialize(string manifestAssetBundleName) { #if UNITY_EDITOR Log(LogType.Info, "Simulation Mode: " + (SimulateAssetBundleInEditor ? "Enabled" : "Disabled")); #endif var go = new GameObject("AssetBundleManager", typeof(AssetBundleManager)); DontDestroyOnLoad(go); #if UNITY_EDITOR // If we're in Editor simulation mode, we don't need the manifest assetBundle. if (SimulateAssetBundleInEditor) return null; #endif LoadAssetBundle(manifestAssetBundleName, true); var operation = new AssetBundleLoadManifestOperation(manifestAssetBundleName, "AssetBundleManifest", typeof(AssetBundleManifest)); m_InProgressOperations.Add(operation); return operation; } // Temporarily work around a il2cpp bug static protected void LoadAssetBundle(string assetBundleName) { LoadAssetBundle(assetBundleName, false); } // Starts the download of the asset bundle identified by the given name, and asset bundles // that this asset bundle depends on. static protected void LoadAssetBundle(string assetBundleName, bool isLoadingAssetBundleManifest) { Log(LogType.Info, "Loading Asset Bundle " + (isLoadingAssetBundleManifest ? "Manifest: " : ": ") + assetBundleName); #if UNITY_EDITOR // If we're in Editor simulation mode, we don't have to really load the assetBundle and its dependencies. if (SimulateAssetBundleInEditor) return; #endif if (!isLoadingAssetBundleManifest) { if (m_AssetBundleManifest == null) { Log(LogType.Error, "Please initialize AssetBundleManifest by calling AssetBundleManager.Initialize()"); return; } } // Check if the assetBundle has already been processed. bool isAlreadyProcessed = LoadAssetBundleInternal(assetBundleName, isLoadingAssetBundleManifest); // Load dependencies. if (!isAlreadyProcessed && !isLoadingAssetBundleManifest) LoadDependencies(assetBundleName); } // Returns base downloading URL for the given asset bundle. // This URL may be overridden on per-bundle basis via overrideBaseDownloadingURL event. protected static string GetAssetBundleBaseDownloadingURL(string bundleName) { if (overrideBaseDownloadingURL != null) { foreach (OverrideBaseDownloadingURLDelegate method in overrideBaseDownloadingURL.GetInvocationList()) { string res = method(bundleName); if (res != null) return res; } } return m_BaseDownloadingURL; } // Checks who is responsible for determination of the correct asset bundle variant // that should be loaded on this platform. // // On most platforms, this is done by the AssetBundleManager itself. However, on // certain platforms (iOS at the moment) it's possible that an external asset bundle // variant resolution mechanism is used. In these cases, we use base asset bundle // name (without the variant tag) as the bundle identifier. The platform-specific // code is responsible for correctly loading the bundle. static protected bool UsesExternalBundleVariantResolutionMechanism(string baseAssetBundleName) { #if ENABLE_IOS_APP_SLICING var url = GetAssetBundleBaseDownloadingURL(baseAssetBundleName); if (url.ToLower().StartsWith("res://") || url.ToLower().StartsWith("odr://")) return true; #endif return false; } // Remaps the asset bundle name to the best fitting asset bundle variant. static protected string RemapVariantName(string assetBundleName) { string[] bundlesWithVariant = m_AssetBundleManifest.GetAllAssetBundlesWithVariant(); // Get base bundle name string baseName = assetBundleName.Split('.')[0]; if (UsesExternalBundleVariantResolutionMechanism(baseName)) return baseName; int bestFit = int.MaxValue; int bestFitIndex = -1; // Loop all the assetBundles with variant to find the best fit variant assetBundle. for (int i = 0; i < bundlesWithVariant.Length; i++) { string[] curSplit = bundlesWithVariant[i].Split('.'); string curBaseName = curSplit[0]; string curVariant = curSplit[1]; if (curBaseName != baseName) continue; int found = System.Array.IndexOf(m_ActiveVariants, curVariant); // If there is no active variant found. We still want to use the first if (found == -1) found = int.MaxValue - 1; if (found < bestFit) { bestFit = found; bestFitIndex = i; } } if (bestFit == int.MaxValue - 1) { Log(LogType.Warning, "Ambigious asset bundle variant chosen because there was no matching active variant: " + bundlesWithVariant[bestFitIndex]); } if (bestFitIndex != -1) { return bundlesWithVariant[bestFitIndex]; } else { return assetBundleName; } } // Sets up download operation for the given asset bundle if it's not downloaded already. static protected bool LoadAssetBundleInternal(string assetBundleName, bool isLoadingAssetBundleManifest) { // Already loaded. LoadedAssetBundle bundle = null; m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle); if (bundle != null) { bundle.m_ReferencedCount++; return true; } // @TODO: Do we need to consider the referenced count of WWWs? // In the demo, we never have duplicate WWWs as we wait LoadAssetAsync()/LoadLevelAsync() to be finished before calling another LoadAssetAsync()/LoadLevelAsync(). // But in the real case, users can call LoadAssetAsync()/LoadLevelAsync() several times then wait them to be finished which might have duplicate WWWs. if (m_DownloadingBundles.Contains(assetBundleName)) return true; string bundleBaseDownloadingURL = GetAssetBundleBaseDownloadingURL(assetBundleName); if (bundleBaseDownloadingURL.ToLower().StartsWith("odr://")) { #if ENABLE_IOS_ON_DEMAND_RESOURCES Log(LogType.Info, "Requesting bundle " + assetBundleName + " through ODR"); m_InProgressOperations.Add(new AssetBundleDownloadFromODROperation(assetBundleName)); #else new ApplicationException("Can't load bundle " + assetBundleName + " through ODR: this Unity version or build target doesn't support it."); #endif } else if (bundleBaseDownloadingURL.ToLower().StartsWith("res://")) { #if ENABLE_IOS_APP_SLICING Log(LogType.Info, "Requesting bundle " + assetBundleName + " through asset catalog"); m_InProgressOperations.Add(new AssetBundleOpenFromAssetCatalogOperation(assetBundleName)); #else new ApplicationException("Can't load bundle " + assetBundleName + " through asset catalog: this Unity version or build target doesn't support it."); #endif } else { WWW download = null; if (!bundleBaseDownloadingURL.EndsWith("/")) { bundleBaseDownloadingURL += "/"; } string url = bundleBaseDownloadingURL + assetBundleName; // For manifest assetbundle, always download it as we don't have hash for it. if (isLoadingAssetBundleManifest) download = new WWW(url); else download = WWW.LoadFromCacheOrDownload(url, m_AssetBundleManifest.GetAssetBundleHash(assetBundleName), 0); m_InProgressOperations.Add(new AssetBundleDownloadFromWebOperation(assetBundleName, download)); } m_DownloadingBundles.Add(assetBundleName); return false; } // Where we get all the dependencies and load them all. static protected void LoadDependencies(string assetBundleName) { if (m_AssetBundleManifest == null) { Log(LogType.Error, "Please initialize AssetBundleManifest by calling AssetBundleManager.Initialize()"); return; } // Get dependecies from the AssetBundleManifest object.. string[] dependencies = m_AssetBundleManifest.GetAllDependencies(assetBundleName); if (dependencies.Length == 0) return; for (int i = 0; i < dependencies.Length; i++) dependencies[i] = RemapVariantName(dependencies[i]); // Record and load all dependencies. m_Dependencies.Add(assetBundleName, dependencies); for (int i = 0; i < dependencies.Length; i++) LoadAssetBundleInternal(dependencies[i], false); } /// <summary> /// Unloads assetbundle and its dependencies. /// </summary> static public void UnloadAssetBundle(string assetBundleName) { #if UNITY_EDITOR // If we're in Editor simulation mode, we don't have to load the manifest assetBundle. if (SimulateAssetBundleInEditor) return; #endif assetBundleName = RemapVariantName(assetBundleName); UnloadAssetBundleInternal(assetBundleName); UnloadDependencies(assetBundleName); } static protected void UnloadDependencies(string assetBundleName) { string[] dependencies = null; if (!m_Dependencies.TryGetValue(assetBundleName, out dependencies)) return; // Loop dependencies. foreach (var dependency in dependencies) { UnloadAssetBundleInternal(dependency); } m_Dependencies.Remove(assetBundleName); } static protected void UnloadAssetBundleInternal(string assetBundleName) { string error; LoadedAssetBundle bundle = GetLoadedAssetBundle(assetBundleName, out error); if (bundle == null) return; if (--bundle.m_ReferencedCount == 0) { bundle.OnUnload(); m_LoadedAssetBundles.Remove(assetBundleName); Log(LogType.Info, assetBundleName + " has been unloaded successfully"); } } void Update() { // Update all in progress operations for (int i = 0; i < m_InProgressOperations.Count;) { var operation = m_InProgressOperations[i]; if (operation.Update()) { i++; } else { m_InProgressOperations.RemoveAt(i); ProcessFinishedOperation(operation); } } } void ProcessFinishedOperation(AssetBundleLoadOperation operation) { AssetBundleDownloadOperation download = operation as AssetBundleDownloadOperation; if (download == null) return; if (download.error == null) m_LoadedAssetBundles.Add(download.assetBundleName, download.assetBundle); else { string msg = string.Format("Failed downloading bundle {0} from {1}: {2}", download.assetBundleName, download.GetSourceURL(), download.error); m_DownloadingErrors.Add(download.assetBundleName, msg); } m_DownloadingBundles.Remove(download.assetBundleName); } /// <summary> /// Starts a load operation for an asset from the given asset bundle. /// </summary> static public AssetBundleLoadAssetOperation LoadAssetAsync(string assetBundleName, string assetName, System.Type type) { Log(LogType.Info, "Loading " + assetName + " from " + assetBundleName + " bundle"); AssetBundleLoadAssetOperation operation = null; #if UNITY_EDITOR if (SimulateAssetBundleInEditor) { string[] assetPaths = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleName, assetName); if (assetPaths.Length == 0) { Log(LogType.Error, "There is no asset with name \"" + assetName + "\" in " + assetBundleName); return null; } // @TODO: Now we only get the main object from the first asset. Should consider type also. UnityEngine.Object target = AssetDatabase.LoadMainAssetAtPath(assetPaths[0]); operation = new AssetBundleLoadAssetOperationSimulation(target); } else #endif { assetBundleName = RemapVariantName(assetBundleName); LoadAssetBundle(assetBundleName); operation = new AssetBundleLoadAssetOperationFull(assetBundleName, assetName, type); m_InProgressOperations.Add(operation); } return operation; } /// <summary> /// Starts a load operation for a level from the given asset bundle. /// </summary> static public AssetBundleLoadOperation LoadLevelAsync(string assetBundleName, string levelName, bool isAdditive) { Log(LogType.Info, "Loading " + levelName + " from " + assetBundleName + " bundle"); AssetBundleLoadOperation operation = null; #if UNITY_EDITOR if (SimulateAssetBundleInEditor) { operation = new AssetBundleLoadLevelSimulationOperation(assetBundleName, levelName, isAdditive); } else #endif { assetBundleName = RemapVariantName(assetBundleName); LoadAssetBundle(assetBundleName); operation = new AssetBundleLoadLevelOperation(assetBundleName, levelName, isAdditive); m_InProgressOperations.Add(operation); } return operation; } } // End of AssetBundleManager. }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using gView.Framework; using gView.Framework.Carto.Rendering; using gView.Framework.Symbology; using gView.Framework.Geometry; using gView.Framework.Data; using gView.Framework.UI; using gView.Framework.IO; using gView.Framework.system; using System.Reflection; using gView.Framework.Carto.Rendering.UI; namespace gView.Framework.Carto.Rendering { public class RendererFunctions { static internal Random r = new Random(DateTime.Now.Millisecond); static internal Color RandomColor { get { return Color.FromArgb(r.Next(255), r.Next(255), r.Next(255)); } } static public ISymbol CreateStandardSymbol(geometryType type) { ISymbol symbol = null; switch (type) { case geometryType.Envelope: case geometryType.Polygon: symbol = new SimpleFillSymbol(); ((SimpleFillSymbol)symbol).OutlineSymbol = new SimpleLineSymbol(); ((SimpleFillSymbol)symbol).Color = RandomColor; ((SimpleLineSymbol)((SimpleFillSymbol)symbol).OutlineSymbol).Color = RandomColor; break; case geometryType.Polyline: symbol = new SimpleLineSymbol(); ((SimpleLineSymbol)symbol).Color = RandomColor; break; case geometryType.Multipoint: case geometryType.Point: symbol = new SimplePointSymbol(); ((SimplePointSymbol)symbol).Color = RandomColor; break; } return symbol; } static public ISymbol CreateStandardSelectionSymbol(geometryType type) { ISymbol symbol = null; switch (type) { case geometryType.Envelope: case geometryType.Polygon: symbol = new SimpleFillSymbol(); ((SimpleFillSymbol)symbol).Color = Color.Transparent; ((SimpleFillSymbol)symbol).OutlineSymbol = new SimpleLineSymbol(); ((SimpleLineSymbol)((SimpleFillSymbol)symbol).OutlineSymbol).Color = Color.Cyan; ((SimpleLineSymbol)((SimpleFillSymbol)symbol).OutlineSymbol).Width = 3; break; case geometryType.Polyline: symbol = new SimpleLineSymbol(); ((SimpleLineSymbol)symbol).Color = Color.Cyan; ((SimpleLineSymbol)symbol).Width = 3; break; case geometryType.Point: symbol = new SimplePointSymbol(); ((SimplePointSymbol)symbol).Color = Color.Cyan; ((SimplePointSymbol)symbol).Size = 5; break; } return symbol; } static public ISymbol CreateStandardHighlightSymbol(geometryType type) { ISymbol symbol = null; switch (type) { case geometryType.Envelope: case geometryType.Polygon: symbol = new SimpleFillSymbol(); ((SimpleFillSymbol)symbol).Color = Color.FromArgb(100, 255, 255, 0); ((SimpleFillSymbol)symbol).OutlineSymbol = new SimpleLineSymbol(); ((SimpleLineSymbol)((SimpleFillSymbol)symbol).OutlineSymbol).Color = Color.Yellow; ((SimpleLineSymbol)((SimpleFillSymbol)symbol).OutlineSymbol).Width = 5; break; case geometryType.Polyline: symbol = new SimpleLineSymbol(); ((SimpleLineSymbol)symbol).Color = Color.Yellow; ((SimpleLineSymbol)symbol).Width = 5; break; case geometryType.Point: symbol = new SimplePointSymbol(); ((SimplePointSymbol)symbol).Color = Color.Yellow; ((SimplePointSymbol)symbol).Size = 10; break; } return symbol; } } [gView.Framework.system.RegisterPlugIn("646386E4-D010-4c7d-98AA-8C1903A3D5E4")] public class SimpleRenderer : Cloner, IFeatureRenderer2, IPropertyPage, ILegendGroup, ISymbolCreator { public enum CartographicMethod { Simple = 0, SymbolOrder = 1 } private ISymbol _symbol; private SymbolRotation _symbolRotation; private bool _useRefScale = true, _rotate = false; private CartographicMethod _cartoMethod = CartographicMethod.Simple, _actualCartoMethod = CartographicMethod.Simple; private List<IFeature> _features = null; public SimpleRenderer() { _symbolRotation = new SymbolRotation(); } public void Dispose() { if (_symbol != null) _symbol.Release(); _symbol = null; } public ISymbol Symbol { get { return _symbol; } set { _symbol = value; _rotate = (_symbol is ISymbolRotation && _symbolRotation != null && _symbolRotation.RotationFieldName != ""); } } public ISymbol CreateStandardSymbol(geometryType type) { return RendererFunctions.CreateStandardSymbol(type); } public ISymbol CreateStandardSelectionSymbol(geometryType type) { return RendererFunctions.CreateStandardSelectionSymbol(type); } public ISymbol CreateStandardHighlightSymbol(geometryType type) { return RendererFunctions.CreateStandardHighlightSymbol(type); } public SymbolRotation SymbolRotation { get { return _symbolRotation; } set { if (value == null) _symbolRotation.RotationFieldName = ""; else _symbolRotation = value; _rotate = (_symbol is ISymbolRotation && _symbolRotation != null && _symbolRotation.RotationFieldName != ""); } } public CartographicMethod CartoMethod { get { return _cartoMethod; } set { _cartoMethod = value; } } #region IFeatureRenderer public bool CanRender(IFeatureLayer layer, IMap map) { if (layer == null) return false; if (layer.FeatureClass == null) return false; /* if (layer.FeatureClass.GeometryType == geometryType.Unknown || layer.FeatureClass.GeometryType == geometryType.Network) return false; * */ if (layer.LayerGeometryType == geometryType.Unknown || layer.LayerGeometryType == geometryType.Network) return false; return true; } public bool HasEffect(IFeatureLayer layer, IMap map) { return true; } public bool UseReferenceScale { get { return _useRefScale; } set { _useRefScale = value; } } public void PrepareQueryFilter(IFeatureLayer layer, IQueryFilter filter) { if (!(_symbol is ISymbolCollection) || ((ISymbolCollection)_symbol).Symbols.Count < 2) { _actualCartoMethod = CartographicMethod.Simple; } else { _actualCartoMethod = _cartoMethod; } if (_rotate && layer.FeatureClass.FindField(_symbolRotation.RotationFieldName) != null) filter.AddField(_symbolRotation.RotationFieldName); } /* public void Draw(IDisplay disp,IFeatureCursor fCursor,DrawPhase drawPhase,ICancelTracker cancelTracker) { if(_symbol==null) return; IFeature feature; try { while((feature=fCursor.NextFeature)!=null) { //_symbol.Draw(disp,feature.Shape); if(cancelTracker!=null) if(!cancelTracker.Continue) return; disp.Draw(_symbol,feature.Shape); } } catch(Exception ex) { string msg=ex.Message; } } * */ public void Draw(IDisplay disp, IFeature feature) { /* if (feature.Shape is IPolyline) { ISymbol symbol = RendererFunctions.CreateStandardSymbol(geometryType.Polygon); disp.Draw(symbol, ((ITopologicalOperation)feature.Shape).Buffer(30)); } if (feature.Shape is IPoint) { ISymbol symbol = RendererFunctions.CreateStandardSymbol(geometryType.Polygon); disp.Draw(symbol, ((ITopologicalOperation)feature.Shape).Buffer(30)); } if (feature.Shape is IPolygon) { IPolygon buffer = ((ITopologicalOperation)feature.Shape).Buffer(4.0); if (buffer != null) disp.Draw(_symbol, buffer); }*/ if (_actualCartoMethod == CartographicMethod.Simple) { if (_rotate) { object rot = feature[_symbolRotation.RotationFieldName]; if (rot != null && rot != DBNull.Value) { ((ISymbolRotation)_symbol).Rotation = (float)_symbolRotation.Convert2DEGAritmetic(Convert.ToDouble(rot)); } else { ((ISymbolRotation)_symbol).Rotation = 0; } } disp.Draw(_symbol, feature.Shape); } else if (_actualCartoMethod == CartographicMethod.SymbolOrder) { if (_features == null) _features = new List<IFeature>(); _features.Add(feature); } } public void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker) { if (cancelTracker == null) cancelTracker = new CancelTracker(); if (_actualCartoMethod == CartographicMethod.SymbolOrder && cancelTracker.Continue) { ISymbolCollection sColl = (ISymbolCollection)_symbol; foreach (ISymbolCollectionItem symbolItem in sColl.Symbols) { if (symbolItem.Visible == false || symbolItem.Symbol == null) continue; ISymbol symbol = symbolItem.Symbol; bool isRotatable = symbol is ISymbolRotation; int counter = 0; if (!cancelTracker.Continue) break; foreach (IFeature feature in _features) { if (_rotate && isRotatable) { object rot = feature[_symbolRotation.RotationFieldName]; if (rot != null && rot != DBNull.Value) { ((ISymbolRotation)symbol).Rotation = (float)_symbolRotation.Convert2DEGAritmetic(Convert.ToDouble(rot)); } else { ((ISymbolRotation)symbol).Rotation = 0; } } disp.Draw(symbol, feature.Shape); counter++; if (counter % 100 == 0 && !cancelTracker.Continue) break; } } } if (_features != null) _features.Clear(); _features = null; } public string Name { get { return "Single Symbol"; } } public string Category { get { return "Features"; } } #endregion #region IPropertyPage Member public object PropertyPageObject() { return this; } public object PropertyPage(object initObject) { if (initObject is IFeatureLayer) { if (((IFeatureLayer)initObject).FeatureClass == null) return null; if (_symbol == null) { _symbol = RendererFunctions.CreateStandardSymbol(((IFeatureLayer)initObject).LayerGeometryType/*((IFeatureLayer)initObject).FeatureClass.GeometryType*/); } string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Assembly uiAssembly = Assembly.LoadFrom(appPath + @"\gView.Carto.Rendering.UI.dll"); IPropertyPanel p = uiAssembly.CreateInstance("gView.Framework.Carto.Rendering.UI.PropertyForm_SimpleRenderer") as IPropertyPanel; if (p != null) { return p.PropertyPanel(this, (IFeatureLayer)initObject); } } return null; } #endregion #region IPersistable Member public string PersistID { get { return null; } } public void Load(IPersistStream stream) { _symbol = (ISymbol)stream.Load("Symbol"); _symbolRotation = (SymbolRotation)stream.Load("SymbolRotation", _symbolRotation, _symbolRotation); _rotate = ((_symbol is ISymbolRotation) && _symbolRotation != null && _symbolRotation.RotationFieldName != ""); _cartoMethod = (CartographicMethod)stream.Load("CartographicMethod", (int)CartographicMethod.Simple); } public void Save(IPersistStream stream) { stream.Save("Symbol", _symbol); if (_symbolRotation.RotationFieldName != "") { stream.Save("SymbolRotation", _symbolRotation); } stream.Save("CartographicMethod", (int)_cartoMethod); } #endregion #region ILegendGroup Members public int LegendItemCount { get { return (_symbol == null) ? 0 : 1; } } public ILegendItem LegendItem(int index) { if (index == 0) return _symbol; return null; } public void SetSymbol(ILegendItem item, ISymbol symbol) { if (_symbol == null) return; if (item == symbol) return; if (item == _symbol) { if (symbol is ILegendItem && _symbol is ILegendItem) { ((ILegendItem)symbol).LegendLabel = ((ILegendItem)_symbol).LegendLabel; } _symbol.Release(); _symbol = symbol; } } #endregion #region IClone2 public object Clone(IDisplay display) { SimpleRenderer renderer = new SimpleRenderer(); if (_symbol != null) renderer._symbol = (ISymbol)_symbol.Clone(_useRefScale ? display : null); renderer._symbolRotation = (SymbolRotation)_symbolRotation.Clone(); renderer._rotate = _rotate; renderer._cartoMethod = _cartoMethod; renderer._actualCartoMethod = _actualCartoMethod; return renderer; } public void Release() { Dispose(); } #endregion #region IRenderer Member public List<ISymbol> Symbols { get { return new List<ISymbol>(new ISymbol[] { _symbol }); } } public bool Combine(IRenderer renderer) { if (renderer is SimpleRenderer && renderer != this) { if (_symbol is ISymbolCollection) { ((ISymbolCollection)_symbol).AddSymbol( ((SimpleRenderer)renderer).Symbol); } else { ISymbolCollection symCol = PlugInManager.Create(new Guid("062AD1EA-A93C-4c3c-8690-830E65DC6D91")) as ISymbolCollection; symCol.AddSymbol(_symbol); symCol.AddSymbol(((SimpleRenderer)renderer).Symbol); _symbol = (ISymbol)symCol; } return true; } return false; } #endregion } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009 Oracle. All rights reserved. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class RecnoCursorTest { private string testFixtureName; private string testFixtureHome; private string testName; private string testHome; [TestFixtureSetUp] public void RunBeforeTests() { testFixtureName = "RecnoCursorTest"; testFixtureHome = "./TestOut/" + testFixtureName; } [Test] public void TestCursor() { testName = "TestCursor"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); GetCursorWithImplicitTxn(testHome, testName + ".db", false); } [Test] public void TestCursorWithConfig() { testName = "TestCursorWithConfig"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); GetCursorWithImplicitTxn(testHome, testName + ".db", true); } public void GetCursorWithImplicitTxn(string home, string dbFile, bool ifConfig) { DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseCDB = true; envConfig.UseMPool = true; DatabaseEnvironment env = DatabaseEnvironment.Open( home, envConfig); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; RecnoDatabase db = RecnoDatabase.Open(dbFile, dbConfig); RecnoCursor cursor; if (ifConfig == false) cursor = db.Cursor(); else cursor = db.Cursor(new CursorConfig()); cursor.Close(); db.Close(); env.Close(); } [Test] public void TestCursorInTxn() { testName = "TestCursorInTxn"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); GetCursorWithExplicitTxn(testHome, testName + ".db", false); } [Test] public void TestConfigedCursorInTxn() { testName = "TestConfigedCursorInTxn"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); GetCursorWithExplicitTxn(testHome, testName + ".db", true); } public void GetCursorWithExplicitTxn(string home, string dbFile, bool ifConfig) { DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseTxns = true; envConfig.UseMPool = true; DatabaseEnvironment env = DatabaseEnvironment.Open( home, envConfig); Transaction openTxn = env.BeginTransaction(); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; RecnoDatabase db = RecnoDatabase.Open(dbFile, dbConfig, openTxn); openTxn.Commit(); Transaction cursorTxn = env.BeginTransaction(); RecnoCursor cursor; if (ifConfig == false) cursor = db.Cursor(cursorTxn); else cursor = db.Cursor(new CursorConfig(), cursorTxn); cursor.Close(); cursorTxn.Commit(); db.Close(); env.Close(); } [Test] public void TestDuplicate() { KeyValuePair<DatabaseEntry, DatabaseEntry> pair; RecnoDatabase db; RecnoDatabaseConfig dbConfig; RecnoCursor cursor, dupCursor; string dbFileName; testName = "TestDuplicate"; testHome = testFixtureHome + "/" + testName; dbFileName = testHome + "/" + testName + ".db"; Configuration.ClearDir(testHome); dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; db = RecnoDatabase.Open(dbFileName, dbConfig); cursor = db.Cursor(); /* * Add a record(1, 1) by cursor and move * the cursor to the current record. */ AddOneByCursor(cursor); cursor.Refresh(); //Duplicate a new cursor to the same position. dupCursor = cursor.Duplicate(true); // Overwrite the record. dupCursor.Overwrite(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("newdata"))); // Confirm that the original data doesn't exist. pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry( BitConverter.GetBytes((int)1)), new DatabaseEntry( BitConverter.GetBytes((int)1))); Assert.IsFalse(dupCursor.Move(pair, true)); dupCursor.Close(); cursor.Close(); db.Close(); } [Test] public void TestInsertToLoc() { RecnoDatabase db; RecnoDatabaseConfig dbConfig; RecnoCursor cursor; DatabaseEntry data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; string dbFileName; testName = "TestInsertToLoc"; testHome = testFixtureHome + "/" + testName; dbFileName = testHome + "/" + testName + ".db"; Configuration.ClearDir(testHome); // Open database and cursor. dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Renumber = true; db = RecnoDatabase.Open(dbFileName, dbConfig); cursor = db.Cursor(); // Add record(1,1) into database. /* * Add a record(1, 1) by cursor and move * the cursor to the current record. */ AddOneByCursor(cursor); cursor.Refresh(); /* * Insert the new record(1,10) after the * record(1,1). */ data = new DatabaseEntry( BitConverter.GetBytes((int)10)); cursor.Insert(data, Cursor.InsertLocation.AFTER); /* * Move the cursor to the record(1,1) and * confirm that the next record is the one just inserted. */ pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry( BitConverter.GetBytes((int)1)), new DatabaseEntry( BitConverter.GetBytes((int)1))); Assert.IsTrue(cursor.Move(pair, true)); Assert.IsTrue(cursor.MoveNext()); Assert.AreEqual(BitConverter.GetBytes((int)10), cursor.Current.Value.Data); cursor.Close(); db.Close(); } public void AddOneByCursor(RecnoCursor cursor) { KeyValuePair<DatabaseEntry, DatabaseEntry> pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry( BitConverter.GetBytes((int)1)), new DatabaseEntry( BitConverter.GetBytes((int)1))); cursor.Add(pair); } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Utility; using MS.Internal.Documents; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Documents; using System.Windows.Media; namespace System.Windows.Controls.Primitives { /// <summary> /// BulletDecorator is used for decorating a generic content of type UIElement. /// Usually, the content is a text and the bullet is a glyph representing /// something similar to a checkbox or a radiobutton. /// Bullet property is used to decorate the content by aligning itself with the first line of the content text. /// </summary> public class BulletDecorator : Decorator { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Default BulletDecorator constructor /// </summary> /// <remarks> /// Automatic determination of current Dispatcher. /// Use alternative constructor that accepts a Dispatcher for best performance. /// </remarks> public BulletDecorator() : base() { } #endregion //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Properties /// <summary> /// DependencyProperty for <see cref="Background" /> property. /// </summary> public static readonly DependencyProperty BackgroundProperty = Panel.BackgroundProperty.AddOwner(typeof(BulletDecorator), new FrameworkPropertyMetadata( (Brush)null, FrameworkPropertyMetadataOptions.AffectsRender)); /// <summary> /// The Background property defines the brush used to fill the area within the BulletDecorator. /// </summary> public Brush Background { get { return (Brush)GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// Bullet property is the first visual element in BulletDecorator visual tree. /// It should be aligned to BulletDecorator.Child which is the second visual child. /// </summary> /// <value></value> public UIElement Bullet { get { return _bullet; } set { if (_bullet != value) { if (_bullet != null) { // notify the visual layer that the old bullet has been removed. RemoveVisualChild(_bullet); //need to remove old element from logical tree RemoveLogicalChild(_bullet); } _bullet = value; AddLogicalChild(value); // notify the visual layer about the new child. AddVisualChild(value); // If we decorator content exists we need to move it at the end of the visual tree UIElement child = Child; if (child != null) { RemoveVisualChild(child); AddVisualChild(child); } InvalidateMeasure(); } } } #endregion Properties //------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------- #region Protected Methods /// <summary> /// Returns enumerator to logical children. /// </summary> protected internal override IEnumerator LogicalChildren { get { if (_bullet == null) { return base.LogicalChildren; } if (Child == null) { return new SingleChildEnumerator(_bullet); } return new DoubleChildEnumerator(_bullet, Child); } } private class DoubleChildEnumerator : IEnumerator { internal DoubleChildEnumerator(object child1, object child2) { Debug.Assert(child1 != null, "First child should be non-null."); Debug.Assert(child2 != null, "Second child should be non-null."); _child1 = child1; _child2 = child2; } object IEnumerator.Current { get { switch (_index) { case 0: return _child1; case 1: return _child2; default: return null; } } } bool IEnumerator.MoveNext() { _index++; return _index < 2; } void IEnumerator.Reset() { _index = -1; } private int _index = -1; private object _child1; private object _child2; } /// <summary> /// Override from UIElement /// </summary> protected override void OnRender(DrawingContext dc) { // Draw background in rectangle inside border. Brush background = this.Background; if (background != null) { dc.DrawRectangle(background, null, new Rect(0, 0, RenderSize.Width, RenderSize.Height)); } } /// <summary> /// Returns the Visual children count. /// </summary> protected override int VisualChildrenCount { get { return (Child == null ? 0 : 1) + (_bullet == null ? 0 : 1); } } /// <summary> /// Returns the child at the specified index. /// </summary> protected override Visual GetVisualChild(int index) { if (index < 0 || index > VisualChildrenCount-1) { throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } if (index == 0 && _bullet != null) { return _bullet; } return Child; } /// <summary> /// Updates DesiredSize of the BulletDecorator. Called by parent UIElement. /// This is the first pass of layout. /// </summary> /// <param name="constraint">Constraint size is an "upper limit" that BulletDecorator should not exceed.</param> /// <returns>BulletDecorator' desired size.</returns> protected override Size MeasureOverride(Size constraint) { Size bulletSize = new Size(); Size contentSize = new Size(); UIElement bullet = Bullet; UIElement content = Child; // If we have bullet we should measure it first if (bullet != null) { bullet.Measure(constraint); bulletSize = bullet.DesiredSize; } // If we have second child (content) we should measure it if (content != null) { Size contentConstraint = constraint; contentConstraint.Width = Math.Max(0.0, contentConstraint.Width - bulletSize.Width); content.Measure(contentConstraint); contentSize = content.DesiredSize; } Size desiredSize = new Size(bulletSize.Width + contentSize.Width, Math.Max(bulletSize.Height, contentSize.Height)); return desiredSize; } /// <summary> /// BulletDecorator arranges its children - Bullet and Child. /// Bullet is aligned vertically with the center of the content's first line /// </summary> /// <param name="arrangeSize">Size that BulletDecorator will assume to position children.</param> protected override Size ArrangeOverride(Size arrangeSize) { UIElement bullet = Bullet; UIElement content = Child; double contentOffsetX = 0; double bulletOffsetY = 0; Size bulletSize = new Size(); // Arrange the bullet if exist if (bullet != null) { bullet.Arrange(new Rect(bullet.DesiredSize)); bulletSize = bullet.RenderSize; contentOffsetX = bulletSize.Width; } // Arrange the content if exist if (content != null) { // Helper arranges child and may substitute a child's explicit properties for its DesiredSize. // The actual size the child takes up is stored in its RenderSize. Size contentSize = arrangeSize; if (bullet != null) { contentSize.Width = Math.Max(content.DesiredSize.Width, arrangeSize.Width - bullet.DesiredSize.Width); contentSize.Height = Math.Max(content.DesiredSize.Height, arrangeSize.Height); } content.Arrange(new Rect(contentOffsetX, 0, contentSize.Width, contentSize.Height)); double centerY = GetFirstLineHeight(content) * 0.5d; bulletOffsetY += Math.Max(0d, centerY - bulletSize.Height * 0.5d); } // Re-Position the bullet if exist if (bullet != null && !DoubleUtil.IsZero(bulletOffsetY)) { bullet.Arrange(new Rect(0, bulletOffsetY, bullet.DesiredSize.Width, bullet.DesiredSize.Height)); } return arrangeSize; } #endregion Protected Methods //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods // This method calculates the height of the first line if the element is TextBlock or FlowDocumentScrollViewer // Otherwise returns the element height private double GetFirstLineHeight(UIElement element) { // We need to find TextBlock/FlowDocumentScrollViewer if it is nested inside ContentPresenter // Common scenario when used in styles is that BulletDecorator content is a ContentPresenter UIElement text = FindText(element); ReadOnlyCollection<LineResult> lr = null; if (text != null) { TextBlock textElement = ((TextBlock)text); if (textElement.IsLayoutDataValid) lr = textElement.GetLineResults(); } else { text = FindFlowDocumentScrollViewer(element); if (text != null) { TextDocumentView tdv = ((IServiceProvider)text).GetService(typeof(ITextView)) as TextDocumentView; if (tdv != null && tdv.IsValid) { ReadOnlyCollection<ColumnResult> cr = tdv.Columns; if (cr != null && cr.Count > 0) { ColumnResult columnResult = cr[0]; ReadOnlyCollection<ParagraphResult> pr = columnResult.Paragraphs; if (pr != null && pr.Count > 0) { ContainerParagraphResult cpr = pr[0] as ContainerParagraphResult; if (cpr != null) { TextParagraphResult textParagraphResult = cpr.Paragraphs[0] as TextParagraphResult; if (textParagraphResult != null) { lr = textParagraphResult.Lines; } } } } } } } if (lr != null && lr.Count > 0) { Point ancestorOffset = new Point(); text.TransformToAncestor(element).TryTransform(ancestorOffset, out ancestorOffset); return lr[0].LayoutBox.Height + ancestorOffset.Y * 2d; } return element.RenderSize.Height; } private TextBlock FindText(Visual root) { // Cases where the root is itself a TextBlock TextBlock text = root as TextBlock; if (text != null) return text; ContentPresenter cp = root as ContentPresenter; if (cp != null) { if (VisualTreeHelper.GetChildrenCount(cp) == 1) { DependencyObject child = VisualTreeHelper.GetChild(cp, 0); // Cases where the child is a TextBlock TextBlock textBlock = child as TextBlock; if (textBlock == null) { AccessText accessText = child as AccessText; if (accessText != null && VisualTreeHelper.GetChildrenCount(accessText) == 1) { // Cases where the child is an AccessText whose child is a TextBlock textBlock = VisualTreeHelper.GetChild(accessText, 0) as TextBlock; } } return textBlock; } } else { AccessText accessText = root as AccessText; if (accessText != null && VisualTreeHelper.GetChildrenCount(accessText) == 1) { // Cases where the root is an AccessText whose child is a TextBlock return VisualTreeHelper.GetChild(accessText, 0) as TextBlock; } } return null; } private FlowDocumentScrollViewer FindFlowDocumentScrollViewer(Visual root) { FlowDocumentScrollViewer text = root as FlowDocumentScrollViewer; if (text != null) return text; ContentPresenter cp = root as ContentPresenter; if (cp != null) { if(VisualTreeHelper.GetChildrenCount(cp) == 1) return VisualTreeHelper.GetChild(cp, 0) as FlowDocumentScrollViewer; } return null; } #endregion //------------------------------------------------------------------- // // Private Memebers // //------------------------------------------------------------------- #region Private Members UIElement _bullet = null; #endregion Private Members } }
using System; using System.Threading.Tasks; using Chill.Specs.TestSubjects; using FluentAssertions; using NSubstitute; using Xunit; namespace Chill.Specs { public class GivenSubjectSpecs : GivenSubject<TestSubject> { [Fact] public void When_the_subject_has_dependencies_it_should_inject_them_from_the_container() { UseThe(Substitute.For<ITestService>()); Subject.TestService.Should().NotBeNull(); } [Fact] public void When_configuring_mock_in_given_then_injected_mock_should_be_same() { ITestService testService = null; Given(() => { UseThe(Substitute.For<ITestService>()); testService = The<ITestService>(); }); Subject.TestService.Should().BeSameAs(testService); } [Fact] public void When_using_both_givens_and_whens_the_givens_are_executed_before_the_when() { string message = ""; Given(() => message += "given1"); Given(() => message += "given2"); When(() => message += "when"); message.Should().Be("given1given2when"); } [Fact] public void When_calling_the_when_in_deferred_mode_it_should_not_execute_it_until_the_action_is_evaluated() { string message = ""; Given(() => message += "given"); When(() => message += "when", deferredExecution: true); message.Should().Be("given"); WhenAction(); message.Should().Be("givenwhen"); } [Fact] public void When_configuring_the_test_to_use_deferred_mode_the_when_should_not_execute_until_it_is_requested() { DeferredExecution = true; string message = ""; Given(() => message += "given"); When(() => message += "when"); message.Should().Be("given"); WhenAction(); message.Should().Be("givenwhen"); } [Fact] public void When_setting_up_the_call_to_when_later_then_whenaction_is_not_called_automatically() { string message = ""; Given(() => message += "given"); WhenLater(() => message += "when"); message.Should().Be("given"); WhenAction(); message.Should().Be("givenwhen"); } [Fact] public void When_the_when_is_async_it_should_await_the_body() { SetThe<IAsyncService>().To(new AsyncService()); bool result = false; When(async () => result = await The<IAsyncService>().DoSomething()); result.Should().Be(true); } [Fact] public void When_calling_async_given_the_func_is_awaited() { SetThe<IAsyncService>().To(new AsyncService()); bool result = false; Given(async () => result = await The<IAsyncService>().DoSomething()); result.Should().Be(true); } private interface IAsyncService { Task<bool> DoSomething(); } private class AsyncService : IAsyncService { public async Task<bool> DoSomething() { await Task.Delay(100); return true; } } } public class GivenSubjectResultSpecs : GivenSubject<object, string> { [Fact] public void When_calling_when_deferred_then_whenaction_is_called_on_result() { string message = ""; Given(() => message += "given"); When(() => message += "when", deferredExecution: true); message.Should().Be("given"); Result.Should().Be("givenwhen"); } [Fact] public void When_calling_when_directly_then_whenaction_is_not_called_on_result() { string message = ""; Given(() => message += "given"); When(() => message += "when"); message.Should().Be("givenwhen"); Result.Should().Be("givenwhen"); } [Fact] public void When_calling_when_later_then_whenaction_is_called_on_result() { string message = ""; Given(() => message += "given"); WhenLater(() => message += "when"); message.Should().Be("given"); Result.Should().Be("givenwhen"); } } public class When_a_subject_is_build_using_a_custom_factory : GivenSubject<Disposable> { private readonly Disposable subject = new Disposable(); public When_a_subject_is_build_using_a_custom_factory() { Given(() => { WithSubject(_ => subject); }); When(() => { // NOTE: Force the subject to get created Subject.Foo(); }); } [Fact] public void Then_dispose_should_still_dispose_our_subject() { // NOTE: Because Dispose is called later, we just need this method to mark it as a test-case. } protected override void Dispose(bool disposing) { base.Dispose(disposing); subject.IsDisposed.Should().BeTrue("because even custom-built subjects should be disposed"); } } public class Disposable : IDisposable { public void Dispose() { IsDisposed = true; } public void Foo() { } public bool IsDisposed { get; set; } } public class TestSubject { private readonly ITestService testService; public TestSubject(ITestService testService) { this.testService = testService; } public bool DoSomething() { return testService.TryMe(); } public ITestService TestService { get { return testService; } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using UMA.AssetBundles; namespace UMA.CharacterSystem { [System.Serializable] public class DownloadingAssetsList { public List<DownloadingAssetItem> downloadingItems = new List<DownloadingAssetItem>(); public bool areDownloadedItemsReady = true; public bool DownloadingItemsContains(string itemToCheck) { bool res = false; if (downloadingItems.Find(item => item.requiredAssetName == itemToCheck) != null) { res = true; } return res; } public bool DownloadingItemsContains(List<string> itemsToCheck) { bool res = false; for (int i = 0; i < itemsToCheck.Count; i++) { if (downloadingItems.Find(item => item.requiredAssetName == itemsToCheck[i]) != null) { res = true; break; } } return res; } /// <summary> /// Generates a temporary item of type T. It then adds a new DownloadingAssetItem to downloadingItems that contains a refrence to this created temp asset and the name of the asset that it should be replaced by once the given assetbundle has completed downloading. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requiredAssetName"></param> /// <param name="requiredAssetNameHash"></param> /// <param name="containingBundle"></param> /// <param name="callback"></param> /// <returns></returns> public T AddDownloadItem<T>(string requiredAssetName, int? requiredAssetNameHash, string containingBundle, Delegate callback = null) where T : UnityEngine.Object { T thisTempAsset = null; if (downloadingItems.Find(item => item.requiredAssetName == requiredAssetName) == null) { if (requiredAssetNameHash == null) { requiredAssetNameHash = UMAUtils.StringToHash(requiredAssetName); } thisTempAsset = GetTempAsset<T>(); if (typeof(T) == typeof(RaceData)) { (thisTempAsset as RaceData).raceName = requiredAssetName; (thisTempAsset as RaceData).name = requiredAssetName; } else if (typeof(T) == typeof(SlotDataAsset)) { (thisTempAsset as SlotDataAsset).name = requiredAssetName; (thisTempAsset as SlotDataAsset).slotName = requiredAssetName; (thisTempAsset as SlotDataAsset).nameHash = (int)requiredAssetNameHash; } else if (typeof(T) == typeof(OverlayDataAsset)) { (thisTempAsset as OverlayDataAsset).name = requiredAssetName; (thisTempAsset as OverlayDataAsset).overlayName = requiredAssetName; (thisTempAsset as OverlayDataAsset).nameHash = (int)requiredAssetNameHash; } else if (typeof(T) == typeof(UMATextRecipe)) { //now that wardrobeRecipes have their own type, we can assume an UMATextRecipe is a full character recipe thisTempAsset.name = requiredAssetName; } else if (typeof(T) == typeof(UMAWardrobeRecipe)) { (thisTempAsset as UMAWardrobeRecipe).recipeType = "Wardrobe"; (thisTempAsset as UMAWardrobeRecipe).wardrobeSlot = AssetBundleManager.AssetBundleIndexObject.AssetWardrobeSlot(containingBundle, requiredAssetName); (thisTempAsset as UMAWardrobeRecipe).Hides = AssetBundleManager.AssetBundleIndexObject.AssetWardrobeHides(containingBundle, requiredAssetName); (thisTempAsset as UMAWardrobeRecipe).compatibleRaces = AssetBundleManager.AssetBundleIndexObject.AssetWardrobeCompatibleWith(containingBundle, requiredAssetName); thisTempAsset.name = requiredAssetName; } else if (typeof(T) == typeof(UMAWardrobeCollection)) { (thisTempAsset as UMAWardrobeCollection).recipeType = "WardrobeCollection"; (thisTempAsset as UMAWardrobeCollection).wardrobeSlot = AssetBundleManager.AssetBundleIndexObject.AssetWardrobeCollectionSlot(containingBundle, requiredAssetName); (thisTempAsset as UMAWardrobeCollection).compatibleRaces = AssetBundleManager.AssetBundleIndexObject.AssetWardrobeCollectionCompatibleWith(containingBundle, requiredAssetName); thisTempAsset.name = requiredAssetName; } else if (typeof(T) == typeof(RuntimeAnimatorController)) { (thisTempAsset as RuntimeAnimatorController).name = requiredAssetName; } else { thisTempAsset.name = requiredAssetName; } var thisDlItem = new DownloadingAssetItem(requiredAssetName, thisTempAsset, containingBundle, callback); downloadingItems.Add(thisDlItem); } else { DownloadingAssetItem dlItem = null; if (downloadingItems.Find(item => item.requiredAssetName == requiredAssetName) != null) dlItem = downloadingItems.Find(item => item.requiredAssetName == requiredAssetName); if (dlItem != null) { //Debug.LogWarning("DownloadingAssetsList already had entry for " + requiredAssetName + " as type " + dlItem.tempAsset.GetType().ToString() + " new request wanted it as type " + typeof(T) + " and its callback was " + dlItem.dynamicCallback[0].Method.Name); if (callback != null) if (!dlItem.dynamicCallback.Contains(callback)) dlItem.dynamicCallback.Add(callback); thisTempAsset = dlItem.tempAsset as T; } else { if (Debug.isDebugBuild) Debug.LogWarning("Could not get TempAsset for " + requiredAssetName); } } return thisTempAsset; } private T GetTempAsset<T>() where T : UnityEngine.Object { T thisTempAsset = null; //we only want the last bit after any assembly var thisTypeName = typeof(T).ToString().Replace(typeof(T).Namespace + ".", ""); //check RuntimeAnimatorController because these get called different things in the editor and in game if (typeof(T) == typeof(RuntimeAnimatorController)) thisTypeName = "RuntimeAnimatorController"; T thisPlaceholder = (T)Resources.Load<T>("PlaceholderAssets/" + thisTypeName + "Placeholder") as T; if (thisPlaceholder != null)//can we assume if an asset was found its a scriptableobject { thisTempAsset = ScriptableObject.Instantiate(thisPlaceholder) as T; } else { if (typeof(ScriptableObject).IsAssignableFrom(typeof(T))) { thisTempAsset = ScriptableObject.CreateInstance(typeof(T)) as T; } else { thisTempAsset = (T)Activator.CreateInstance(typeof(T)); } } return thisTempAsset; } /// <summary> /// Removes a list of downloadingAssetItems from the downloadingItems List. /// </summary> /// <param name="itemsToRemove"></param> public IEnumerator RemoveDownload(List<DownloadingAssetItem> itemsToRemove) { //Not used any more UMAs check the status of stuff they asked for themselves //Dictionary<UMAAvatarBase, List<string>> updatedUMAs = new Dictionary<UMAAvatarBase, List<string>>(); foreach (DownloadingAssetItem item in itemsToRemove) { item.isBeingRemoved = true; } foreach (DownloadingAssetItem item in itemsToRemove) { string error = ""; //we need to check everyitem in this batch belongs to an asset bundle that has actually been loaded LoadedAssetBundle loadedBundleTest = AssetBundleManager.GetLoadedAssetBundle(item.containingBundle, out error); AssetBundle loadedBundleABTest = loadedBundleTest.m_AssetBundle; if (loadedBundleABTest == null && (String.IsNullOrEmpty(error))) { while (loadedBundleTest.m_AssetBundle == null) { //could say we are unpacking here yield return null; } } if (!String.IsNullOrEmpty(error)) { if (Debug.isDebugBuild) Debug.LogError(error); yield break; } } //Now every item in the batch should be in a loaded bundle that is ready to use. foreach (DownloadingAssetItem item in itemsToRemove) { if (item != null) { string error = ""; var loadedBundle = AssetBundleManager.GetLoadedAssetBundle(item.containingBundle, out error); var loadedBundleAB = loadedBundle.m_AssetBundle; if (!String.IsNullOrEmpty(error)) { if (Debug.isDebugBuild) Debug.LogError(error); yield break; } var assetType = item.tempAsset.GetType(); //deal with RuntimeAnimatorController funkiness //the actual type of an instantiated clone of a RuntimeAnimatorController in the editor is UnityEditor.Animations.AnimatorController if (assetType.ToString().IndexOf("AnimatorController") > -1) assetType = typeof(RuntimeAnimatorController); var itemFilename = AssetBundleManager.AssetBundleIndexObject.GetFilenameFromAssetName(item.containingBundle, item.requiredAssetName, assetType.ToString()); if (assetType == typeof(RaceData)) { RaceData actualRace = loadedBundleAB.LoadAsset<RaceData>(itemFilename); UMAContextBase.Instance.AddRace(actualRace); } else if (assetType == typeof(SlotDataAsset)) { SlotDataAsset thisSlot = null; thisSlot = loadedBundleAB.LoadAsset<SlotDataAsset>(itemFilename); if (thisSlot != null) { UMAContextBase.Instance.AddSlotAsset(thisSlot); } else { if (Debug.isDebugBuild) Debug.LogWarning("[DynamicAssetLoader] could not add downloaded slot" + item.requiredAssetName); } } else if (assetType == typeof(OverlayDataAsset)) { OverlayDataAsset thisOverlay = null; thisOverlay = loadedBundleAB.LoadAsset<OverlayDataAsset>(itemFilename); if (thisOverlay != null) { UMAContextBase.Instance.AddOverlayAsset(thisOverlay); } else { if (Debug.isDebugBuild) Debug.LogWarning("[DynamicAssetLoader] could not add downloaded overlay" + item.requiredAssetName + " from assetbundle " + item.containingBundle); } } else if (assetType == typeof(UMATextRecipe)) { UMATextRecipe downloadedRecipe = loadedBundleAB.LoadAsset<UMATextRecipe>(itemFilename); UMAContextBase.Instance.AddRecipe(downloadedRecipe); } else if (assetType == typeof(UMAWardrobeRecipe)) { UMAWardrobeRecipe downloadedRecipe = loadedBundleAB.LoadAsset<UMAWardrobeRecipe>(itemFilename); UMAContextBase.Instance.AddRecipe(downloadedRecipe); } else if (item.dynamicCallback.Count > 0) { //get the asset as whatever the type of the tempAsset is //send this as an array to the dynamicCallback var downloadedAsset = loadedBundleAB.LoadAsset(itemFilename, assetType); var downloadedAssetArray = Array.CreateInstance(assetType, 1); downloadedAssetArray.SetValue(downloadedAsset, 0); for (int i = 0; i < item.dynamicCallback.Count; i++) { item.dynamicCallback[i].DynamicInvoke(downloadedAssetArray); } } if (!String.IsNullOrEmpty(error)) { if (Debug.isDebugBuild) Debug.LogError(error); } } downloadingItems.Remove(item); } if (downloadingItems.Count == 0) { areDownloadedItemsReady = true; //AssetBundleManager.UnloadAllAssetBundles();//we cant do this yet } //yield break; } /// <summary> /// Updates the list of downloadingItems, checks if any have finished downloading and if they have triggers the RemoveDownload method on them /// </summary> public void Update() { List<DownloadingAssetItem> finishedItems = new List<DownloadingAssetItem>(); if (downloadingItems.Count > 0) { areDownloadedItemsReady = false; List<string> finishedBundles = new List<string>(); foreach (DownloadingAssetItem dli in downloadingItems) { bool canProcessBatch = true; dli.UpdateProgress(); string error = ""; if (finishedBundles.Contains(dli.containingBundle)) { if (dli.flagForRemoval == false) { dli.flagForRemoval = true; } else { if (dli.isBeingRemoved) canProcessBatch = false; } } else if (AssetBundleManager.GetLoadedAssetBundle(dli.containingBundle, out error) != null) { finishedBundles.Add(dli.containingBundle); if (dli.flagForRemoval == false) { dli.flagForRemoval = true; } else { if (dli.isBeingRemoved) canProcessBatch = false; } } else { canProcessBatch = false; } if (canProcessBatch) { finishedItems.Add(dli); } } } //send the finished downloads to be processed if (finishedItems.Count > 0) { DynamicAssetLoader.Instance.StartCoroutine(RemoveDownload(finishedItems)); } } /// <summary> /// Returns the temporary asset that was generated when the DownloadingAssetItem for the given assetName was created /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assetName"></param> /// <returns></returns> public T Get<T>(string assetName) where T : UnityEngine.Object { T tempAsset = null; if (downloadingItems.Find(item => item.requiredAssetName == assetName) != null) { if (downloadingItems.Find(item => item.requiredAssetName == assetName).tempAsset.GetType() == typeof(T)) tempAsset = downloadingItems.Find(item => item.requiredAssetName == assetName) as T; } return tempAsset; } /// <summary> /// Returns the download progress of the asset bundle(s) required for the given asset to become available /// </summary> /// <param name="assetName"></param> /// <returns></returns> public float GetDownloadProgressOf(string assetName) { float progress = 0; DownloadingAssetItem item = null; item = downloadingItems.Find(aitem => aitem.requiredAssetName == assetName); if (item != null) { progress = item.Progress; } else { if (Debug.isDebugBuild) Debug.Log(assetName + " was not downloading"); } return progress; } } }
// // ServiceManager.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.IO; using System.Collections.Generic; using Mono.Addins; using Hyena; using Banshee.Base; using Banshee.MediaProfiles; using Banshee.Sources; using Banshee.Database; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Library; using Banshee.Hardware; namespace Banshee.ServiceStack { public static class ServiceManager { private static Dictionary<string, IService> services = new Dictionary<string, IService> (); private static Dictionary<string, IExtensionService> extension_services = new Dictionary<string, IExtensionService> (); private static Stack<IService> dispose_services = new Stack<IService> (); private static List<Type> service_types = new List<Type> (); private static ExtensionNodeList extension_nodes; private static bool is_initialized = false; private static readonly object self_mutex = new object (); public static event EventHandler StartupBegin; public static event EventHandler StartupFinished; public static event ServiceStartedHandler ServiceStarted; public static void Initialize () { Application.ClientStarted += OnClientStarted; } public static void InitializeAddins () { AddinManager.Initialize (ApplicationContext.CommandLine.Contains ("uninstalled") ? "." : Paths.ApplicationData); IProgressStatus monitor = ApplicationContext.CommandLine.Contains ("debug-addins") ? new ConsoleProgressStatus (true) : null; AddinManager.AddinLoadError += (o, a) => { try { AddinManager.Registry.DisableAddin (a.AddinId); } catch {} Log.Exception (a.Message, a.Exception); }; if (ApplicationContext.Debugging) { AddinManager.Registry.Rebuild (monitor); } else { AddinManager.Registry.Update (monitor); } } public static void RegisterAddinServices () { extension_nodes = AddinManager.GetExtensionNodes ("/Banshee/ServiceManager/Service"); } public static void RegisterDefaultServices () { RegisterService<DBusServiceManager> (); RegisterService<DBusCommandService> (); RegisterService<BansheeDbConnection> (); RegisterService<Banshee.Preferences.PreferenceService> (); // HACK: the next line shouldn't be here, it's needed to work around // a race in NDesk DBus. See bgo#627441. RegisterService<Banshee.Networking.Network> (); RegisterService<SourceManager> (); RegisterService<MediaProfileManager> (); RegisterService<PlayerEngineService> (); RegisterService<PlaybackControllerService> (); RegisterService<JobScheduler> (); RegisterService<Banshee.Hardware.HardwareManager> (); RegisterService<Banshee.Collection.Indexer.CollectionIndexerService> (); RegisterService<Banshee.Metadata.SaveTrackMetadataService> (); } public static void DefaultInitialize () { Initialize (); InitializeAddins (); RegisterDefaultServices (); RegisterAddinServices (); } private static void OnClientStarted (Client client) { DelayedInitialize (); } public static void Run() { lock (self_mutex) { OnStartupBegin (); uint cumulative_timer_id = Log.InformationTimerStart (); System.Net.ServicePointManager.DefaultConnectionLimit = 6; foreach (Type type in service_types) { RegisterService (type); } if (extension_nodes != null) { foreach (TypeExtensionNode node in extension_nodes) { StartExtension (node); } } if (AddinManager.IsInitialized) { AddinManager.AddExtensionNodeHandler ("/Banshee/ServiceManager/Service", OnExtensionChanged); } is_initialized = true; Log.InformationTimerPrint (cumulative_timer_id, "All services are started {0}"); OnStartupFinished (); } } private static IService RegisterService (Type type) { IService service = null; try { uint timer_id = Log.DebugTimerStart (); service = (IService)Activator.CreateInstance (type); RegisterService (service); Log.DebugTimerPrint (timer_id, String.Format ( "Core service started ({0}, {{0}})", service.ServiceName)); OnServiceStarted (service); if (service is IDisposable) { dispose_services.Push (service); } if (service is IInitializeService) { ((IInitializeService)service).Initialize (); } return service; } catch (Exception e) { if (service is IRequiredService) { Log.ErrorFormat ("Error initializing required service {0}", service == null ? type.ToString () : service.ServiceName, false); throw; } Log.Warning (String.Format ("Service `{0}' not started: {1}", type.FullName, e.InnerException != null ? e.InnerException.Message : e.Message)); Log.Exception (e.InnerException ?? e); } return null; } private static void StartExtension (TypeExtensionNode node) { if (extension_services.ContainsKey (node.Path)) { return; } IExtensionService service = null; try { uint timer_id = Log.DebugTimerStart (); service = (IExtensionService)node.CreateInstance (typeof (IExtensionService)); service.Initialize (); RegisterService (service); DelayedInitialize (service); Log.DebugTimerPrint (timer_id, String.Format ( "Extension service started ({0}, {{0}})", service.ServiceName)); OnServiceStarted (service); extension_services.Add (node.Path, service); dispose_services.Push (service); } catch (Exception e) { Log.Exception (e.InnerException ?? e); Log.Warning (String.Format ("Extension `{0}' not started: {1}", service == null ? node.Path : service.GetType ().FullName, e.Message)); } } private static void OnExtensionChanged (object o, ExtensionNodeEventArgs args) { lock (self_mutex) { TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode; if (args.Change == ExtensionChange.Add) { StartExtension (node); } else if (args.Change == ExtensionChange.Remove && extension_services.ContainsKey (node.Path)) { IExtensionService service = extension_services[node.Path]; extension_services.Remove (node.Path); Remove (service); ((IDisposable)service).Dispose (); Log.DebugFormat ("Extension service disposed ({0})", service.ServiceName); // Rebuild the dispose stack excluding the extension service IService [] tmp_services = new IService[dispose_services.Count - 1]; int count = tmp_services.Length; foreach (IService tmp_service in dispose_services) { if (tmp_service != service) { tmp_services[--count] = tmp_service; } } dispose_services = new Stack<IService> (tmp_services); } } } private static bool delayed_initialized, have_client; private static void DelayedInitialize () { lock (self_mutex) { if (!delayed_initialized) { have_client = true; var initialized = new HashSet <string> (); var to_initialize = services.Values.ToList (); foreach (IService service in to_initialize) { if (!initialized.Contains (service.ServiceName)) { DelayedInitialize (service); initialized.Add (service.ServiceName); } } delayed_initialized = true; } } } private static void DelayedInitialize (IService service) { try { if (have_client && service is IDelayedInitializeService) { Log.DebugFormat ("Delayed Initializating {0}", service); ((IDelayedInitializeService)service).DelayedInitialize (); } } catch (Exception e) { Log.Exception (e.InnerException ?? e); Log.Warning (String.Format ("Service `{0}' not initialized: {1}", service.GetType ().FullName, e.Message)); } } public static void Shutdown () { lock (self_mutex) { while (dispose_services.Count > 0) { IService service = dispose_services.Pop (); try { ((IDisposable)service).Dispose (); Log.DebugFormat ("Service disposed ({0})", service.ServiceName); } catch (Exception e) { Log.Exception (String.Format ("Service disposal ({0}) threw an exception", service.ServiceName), e); } } services.Clear (); } } public static void RegisterService (IService service) { lock (self_mutex) { Add (service); if(service is IDBusExportable) { DBusServiceManager.RegisterObject ((IDBusExportable)service); } } } public static void RegisterService<T> () where T : IService { lock (self_mutex) { if (is_initialized) { RegisterService (Activator.CreateInstance <T> ()); } else { service_types.Add (typeof (T)); } } } public static bool Contains (string serviceName) { lock (self_mutex) { return services.ContainsKey (serviceName); } } public static bool Contains<T> () where T : class, IService { return Contains (typeof (T).Name); } public static IService Get (string serviceName) { lock (self_mutex) { if (services.ContainsKey (serviceName)) { return services[serviceName]; } } return null; } public static T Get<T> () where T : class, IService { lock (self_mutex) { Type type = typeof (T); T service = Get (type.Name) as T; if (service == null && typeof(IRegisterOnDemandService).IsAssignableFrom (type)) { return RegisterService (type) as T; } return service; } } private static void Add (IService service) { services.Add (service.ServiceName, service); //because Get<T>() works this way: var type_name = service.GetType ().Name; if (type_name != service.ServiceName) { services.Add (type_name, service); } } private static void Remove (IService service) { services.Remove (service.ServiceName); //because Add () works this way: services.Remove (service.GetType ().Name); } private static void OnStartupBegin () { EventHandler handler = StartupBegin; if (handler != null) { handler (null, EventArgs.Empty); } } private static void OnStartupFinished () { EventHandler handler = StartupFinished; if (handler != null) { handler (null, EventArgs.Empty); } } private static void OnServiceStarted (IService service) { ServiceStartedHandler handler = ServiceStarted; if (handler != null) { handler (new ServiceStartedArgs (service)); } } public static int StartupServiceCount { get { return service_types.Count + (extension_nodes == null ? 0 : extension_nodes.Count) + 1; } } public static bool IsInitialized { get { return is_initialized; } } public static DBusServiceManager DBusServiceManager { get { return Get<DBusServiceManager> (); } } public static BansheeDbConnection DbConnection { get { return (BansheeDbConnection)Get ("DbConnection"); } } public static MediaProfileManager MediaProfileManager { get { return Get<MediaProfileManager> (); } } public static SourceManager SourceManager { get { return (SourceManager)Get ("SourceManager"); } } public static JobScheduler JobScheduler { get { return (JobScheduler)Get ("JobScheduler"); } } public static PlayerEngineService PlayerEngine { get { return (PlayerEngineService)Get ("PlayerEngine"); } } public static PlaybackControllerService PlaybackController { get { return (PlaybackControllerService)Get ("PlaybackController"); } } public static HardwareManager HardwareManager { get { return Get<HardwareManager> (); } } } }
using System; using System.Linq; using System.Threading.Tasks; using Xbehave.Test.Infrastructure; using Xunit; using Xunit.Abstractions; namespace Xbehave.Test { // In order to release allocated resources // As a developer // I want to execute teardowns after a scenario has run public class TeardownFeature : Feature { [Background] public void Background() => "Given no events have occurred" .x(() => typeof(TeardownFeature).ClearTestEvents()); [Scenario] public void ManyTeardownsInASingleStep(Type feature, ITestResultMessage[] results) { "Given a step with many teardowns" .x(() => feature = typeof(StepWithManyTeardowns)); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be one result" .x(() => Assert.Single(results)); "And there should be no failures" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); "Ann the teardowns should be executed in reverse order after the step" .x(() => Assert.Equal( new[] { "step1", "teardown3", "teardown2", "teardown1" }, typeof(TeardownFeature).GetTestEvents())); } [Scenario] public void TeardownsWhichThrowExceptionsWhenExecuted(Type feature, ITestResultMessage[] results) { "Given a step with three teardowns which throw exceptions when executed" .x(() => feature = typeof(StepWithThreeBadTeardowns)); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be two results" .x(() => Assert.Equal(2, results.Length)); "And the first result should be a pass" .x(() => Assert.IsAssignableFrom<ITestPassed>(results[0])); "And the second result should be a failure" .x(() => Assert.IsAssignableFrom<ITestFailed>(results[1])); "And the name of the teardown should end in '(Teardown)'" .x(() => Assert.EndsWith("(Teardown)", results[1].Test.DisplayName)); "And the teardowns should be executed in reverse order after the step" .x(() => Assert.Equal( new[] { "step1", "teardown3", "teardown2", "teardown1" }, typeof(TeardownFeature).GetTestEvents())); } [Scenario] public void ManyTeardownsInManySteps(Type feature, ITestResultMessage[] results) { "Given two steps with three teardowns each" .x(() => feature = typeof(TwoStepsWithThreeTeardownsEach)); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be two results" .x(() => Assert.Equal(2, results.Length)); "And there should be no failures" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result))); "And the teardowns should be executed in reverse order after the steps" .x(() => Assert.Equal( new[] { "step1", "step2", "teardown6", "teardown5", "teardown4", "teardown3", "teardown2", "teardown1" }, typeof(TeardownFeature).GetTestEvents())); } [Scenario] public void FailingSteps(Type feature, ITestResultMessage[] results) { "Given two steps with teardowns and a failing step" .x(() => feature = typeof(TwoStepsWithTeardownsAndAFailingStep)); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be one failure" .x(() => Assert.Single(results.OfType<ITestFailed>())); "And the teardowns should be executed after each step" .x(() => Assert.Equal( new[] { "step1", "step2", "step3", "teardown2", "teardown1" }, typeof(TeardownFeature).GetTestEvents())); } [Scenario] public void FailureToCompleteAStep(Type feature, ITestResultMessage[] results) { "Given a failing step with three teardowns" .x(() => feature = typeof(FailingStepWithThreeTeardowns)); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be one failure" .x(() => Assert.Single(results.OfType<ITestFailed>())); "And the teardowns should be executed in reverse order after the step" .x(() => Assert.Equal( new[] { "step1", "teardown3", "teardown2", "teardown1" }, typeof(TeardownFeature).GetTestEvents())); } [Scenario] public void NullTeardown() => "Given a null teardown" .x(() => { }) .Teardown((Action)null); [Scenario] public void AsyncTeardowns(Type feature, ITestResultMessage[] results) { "Given a step with an async teardown which throws" .x(() => feature = typeof(StepWithAnAsyncTeardownWhichThrows)); "When running the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be one failure" .x(() => Assert.Single(results.OfType<ITestFailed>())); } private static class StepWithManyTeardowns { [Scenario] public static void Scenario() => "Given something" .x(() => typeof(TeardownFeature).SaveTestEvent("step1")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown1")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown2")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown3")); } private static class StepWithThreeBadTeardowns { [Scenario] public static void Scenario() => "Given something" .x(() => typeof(TeardownFeature).SaveTestEvent("step1")) .Teardown(() => { typeof(TeardownFeature).SaveTestEvent("teardown1"); throw new InvalidOperationException(); }) .Teardown(() => { typeof(TeardownFeature).SaveTestEvent("teardown2"); throw new InvalidOperationException(); }) .Teardown(() => { typeof(TeardownFeature).SaveTestEvent("teardown3"); throw new InvalidOperationException(); }); } private static class TwoStepsWithThreeTeardownsEach { [Scenario] public static void Scenario() { "Given something" .x(() => typeof(TeardownFeature).SaveTestEvent("step1")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown1")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown2")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown3")); "And something else" .x(() => typeof(TeardownFeature).SaveTestEvent("step2")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown4")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown5")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown6")); } } private static class TwoStepsWithTeardownsAndAFailingStep { [Scenario] public static void Scenario() { "Given something" .x(() => typeof(TeardownFeature).SaveTestEvent("step1")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown1")); "When something" .x(() => typeof(TeardownFeature).SaveTestEvent("step2")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown2")); "Then something happens" .x(() => { typeof(TeardownFeature).SaveTestEvent("step3"); Assert.Equal(0, 1); }); } } private static class FailingStepWithThreeTeardowns { [Scenario] public static void Scenario() => "Given something" .x(() => { typeof(TeardownFeature).SaveTestEvent("step1"); throw new InvalidOperationException(); }) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown1")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown2")) .Teardown(() => typeof(TeardownFeature).SaveTestEvent("teardown3")); } private static class StepWithAnAsyncTeardownWhichThrows { [Scenario] public static void Scenario() => "Given something" .x(() => typeof(TeardownFeature).SaveTestEvent("step1")) .Teardown(async () => { await Task.Yield(); throw new Exception(); }); } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !WIN8METRO using System.Diagnostics; namespace SharpDX.Direct3D11 { public partial class EffectMatrixVariable { private const string MatrixInvalidSize = "Invalid Matrix size: Must be 64 bytes, 16 floats"; /// <summary> /// Set a floating-point matrix. /// </summary> /// <param name="matrix"> A pointer to the first element in the matrix. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::SetMatrix([In] float* pData)</unmanaged> public void SetMatrix<T>(T matrix) where T : struct { SetMatrix(ref matrix); } /// <summary> /// Get a matrix. /// </summary> /// <returns><para>A reference to the first element in a matrix.</para></returns> /// <remarks> /// Note??The DirectX SDK does not supply any compiled binaries for effects. You must use Effects 11 source to build your effects-type application. For more information about using Effects 11 source, see Differences Between Effects 10 and Effects 11. /// </remarks> /// <unmanaged>HRESULT ID3DX11EffectMatrixVariable::GetMatrix([Out] SHARPDX_MATRIX* pData)</unmanaged> public unsafe T GetMatrix<T>() where T : struct { T value; GetMatrix(out *(Matrix*)Interop.CastOut(out value)); return value; } /// <summary> /// Get a matrix. /// </summary> /// <returns><para>A reference to the first element in a matrix.</para></returns> /// <remarks> /// Note??The DirectX SDK does not supply any compiled binaries for effects. You must use Effects 11 source to build your effects-type application. For more information about using Effects 11 source, see Differences Between Effects 10 and Effects 11. /// </remarks> /// <unmanaged>HRESULT ID3DX11EffectMatrixVariable::GetMatrix([Out] SHARPDX_MATRIX* pData)</unmanaged> public Matrix GetMatrix() { Matrix value; GetMatrix(out value); return value; } /// <summary> /// Set a floating-point matrix. /// </summary> /// <param name="matrix"> A pointer to the first element in the matrix. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::SetMatrix([In] float* pData)</unmanaged> public unsafe void SetMatrix<T>(ref T matrix) where T : struct { #if !WIN8METRO Trace.Assert(Utilities.SizeOf<T>() <= 64, MatrixInvalidSize); #endif SetMatrix(ref *(Matrix*)Interop.Fixed(ref matrix)); } /// <summary> /// Set an array of floating-point matrices. /// </summary> /// <param name="matrixArray"> A pointer to the first matrix. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::SetMatrixArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public void SetMatrix<T>(T[] matrixArray) where T : struct { SetMatrix(matrixArray, 0); } /// <summary> /// Set an array of floating-point matrices. /// </summary> /// <param name="matrixArray"> A pointer to the first matrix. </param> /// <param name="offset"> The number of matrix elements to skip from the start of the array. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::SetMatrixArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public void SetMatrix<T>(T[] matrixArray, int offset) where T : struct { #if !WIN8METRO Trace.Assert(Utilities.SizeOf<T>() == 64, MatrixInvalidSize); #endif SetMatrixArray(Interop.CastArray<Matrix, T>(matrixArray), offset, matrixArray.Length); } /// <summary> /// Get an array of matrices. /// </summary> /// <param name="count"> The number of matrices in the returned array. </param> /// <returns>Returns an array of matrix. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::GetMatrixArray([Out, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public T[] GetMatrixArray<T>(int count) where T : struct { return GetMatrixArray<T>(0, count); } /// <summary> /// Get an array of matrices. /// </summary> /// <param name="offset"> The offset (in number of matrices) between the start of the array and the first matrix returned. </param> /// <param name="count"> The number of matrices in the returned array. </param> /// <returns>Returns an array of matrix. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::GetMatrixArray([Out, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public T[] GetMatrixArray<T>(int offset, int count) where T : struct { var temp = new T[count]; GetMatrixArray(Interop.CastArray<Matrix, T>(temp), offset, count); return temp; } /// <summary> /// Transpose and set a floating-point matrix. /// </summary> /// <remarks> /// Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa). /// </remarks> /// <param name="matrix"> A pointer to the first element of a matrix. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::SetMatrixTranspose([In] float* pData)</unmanaged> public void SetMatrixTranspose<T>(T matrix) where T : struct { SetMatrixTranspose(ref matrix); } /// <summary> /// Transpose and set a floating-point matrix. /// </summary> /// <remarks> /// Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa). /// </remarks> /// <param name="matrix"> A pointer to the first element of a matrix. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::SetMatrixTranspose([In] float* pData)</unmanaged> public unsafe void SetMatrixTranspose<T>(ref T matrix) where T : struct { #if !WIN8METRO Trace.Assert(Utilities.SizeOf<T>() <= 64, MatrixInvalidSize); #endif SetMatrixTranspose(ref *(Matrix*)Interop.Cast(ref matrix)); } /// <summary> /// Transpose and set an array of floating-point matrices. /// </summary> /// <remarks> /// Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa). /// </remarks> /// <param name="matrixArray"> A pointer to an array of matrices. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::SetMatrixTransposeArray([In] float* pData,[None] int Offset,[None] int Count)</unmanaged> public void SetMatrixTranspose<T>(T[] matrixArray) where T : struct { SetMatrixTranspose(matrixArray, 0); } /// <summary> /// Transpose and set an array of floating-point matrices. /// </summary> /// <remarks> /// Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa). /// </remarks> /// <param name="matrixArray"> A pointer to an array of matrices. </param> /// <param name="offset"> The offset (in number of matrices) between the start of the array and the first matrix to set. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::SetMatrixTransposeArray([In] float* pData,[None] int Offset,[None] int Count)</unmanaged> public void SetMatrixTranspose<T>(T[] matrixArray, int offset) where T : struct { SetMatrixTransposeArray(Interop.CastArray<Matrix, T>(matrixArray), offset, matrixArray.Length); } /// <summary> /// Transpose and get a floating-point matrix. /// </summary> /// <returns>The transposed matrix.</returns> /// <remarks> /// Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa).Note??The DirectX SDK does not supply any compiled binaries for effects. You must use Effects 11 source to build your effects-type application. For more information about using Effects 11 source, see Differences Between Effects 10 and Effects 11. /// </remarks> /// <unmanaged>HRESULT ID3DX11EffectMatrixVariable::GetMatrixTranspose([Out] SHARPDX_MATRIX* pData)</unmanaged> public unsafe T GetMatrixTranspose<T>() where T : struct { T value; GetMatrixTranspose(out *(Matrix*)Interop.CastOut(out value)); return value; } /// <summary> /// Transpose and get a floating-point matrix. /// </summary> /// <returns>The transposed matrix.</returns> /// <remarks> /// Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa).Note??The DirectX SDK does not supply any compiled binaries for effects. You must use Effects 11 source to build your effects-type application. For more information about using Effects 11 source, see Differences Between Effects 10 and Effects 11. /// </remarks> /// <unmanaged>HRESULT ID3DX11EffectMatrixVariable::GetMatrixTranspose([Out] SHARPDX_MATRIX* pData)</unmanaged> public Matrix GetMatrixTranspose() { Matrix value; GetMatrixTranspose(out value); return value; } /// <summary> /// Transpose and get an array of floating-point matrices. /// </summary> /// <remarks> /// Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa). /// </remarks> /// <param name="count"> The number of matrices in the array to get. </param> /// <returns>Returns an array of transposed <see cref="SharpDX.Matrix"/>. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::GetMatrixTransposeArray([Out, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public T[] GetMatrixTransposeArray<T>(int count) where T : struct { return GetMatrixTransposeArray<T>(0, count); } /// <summary> /// Transpose and get an array of floating-point matrices. /// </summary> /// <remarks> /// Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa). /// </remarks> /// <param name="offset"> The offset (in number of matrices) between the start of the array and the first matrix to get. </param> /// <param name="count"> The number of matrices in the array to get. </param> /// <returns>Returns an array of transposed <see cref="SharpDX.Matrix"/>. </returns> /// <unmanaged>HRESULT ID3D11EffectMatrixVariable::GetMatrixTransposeArray([Out, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public T[] GetMatrixTransposeArray<T>(int offset, int count) where T : struct { var temp = new T[count]; GetMatrixTransposeArray(Interop.CastArray<Matrix, T>(temp), offset, count); return temp; } } } #endif
// **************************************************************** // 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. // **************************************************************** using System; using System.Drawing; using System.Windows.Forms; using NUnit.Core; using NUnit.Util; namespace NUnit.UiKit { public class StatusBar : System.Windows.Forms.StatusBar, TestObserver { private StatusBarPanel statusPanel = new StatusBarPanel(); private StatusBarPanel testCountPanel = new StatusBarPanel(); private StatusBarPanel testsRunPanel = new StatusBarPanel(); private StatusBarPanel failuresPanel = new StatusBarPanel(); private StatusBarPanel timePanel = new StatusBarPanel(); private int testCount = 0; private int testsRun = 0; private int failures = 0; private int time = 0; private bool displayProgress = false; public bool DisplayTestProgress { get { return displayProgress; } set { displayProgress = value; } } public StatusBar() { Panels.Add( statusPanel ); Panels.Add( testCountPanel ); Panels.Add( testsRunPanel ); Panels.Add( failuresPanel ); Panels.Add( timePanel ); statusPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring; statusPanel.Text = "Status"; // Temporarily remove AutoSize due to Mono 1.2 rc problems // //testCountPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents; testCountPanel.MinWidth = 120; //testsRunPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents; testsRunPanel.MinWidth = 120; //failuresPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents; failuresPanel.MinWidth = 104; //timePanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents; timePanel.MinWidth = 120; ShowPanels = true; InitPanels(); } // Kluge to keep VS from generating code that sets the Panels for // the statusbar. Really, our status bar should be a user control // to avoid this and shouldn't allow the panels to be set except // according to specific protocols. [System.ComponentModel.DesignerSerializationVisibility( System.ComponentModel.DesignerSerializationVisibility.Hidden )] public new System.Windows.Forms.StatusBar.StatusBarPanelCollection Panels { get { return base.Panels; } } public override string Text { get { return statusPanel.Text; } set { statusPanel.Text = value; } } public void Initialize( int testCount ) { Initialize( testCount, testCount > 0 ? "Ready" : "" ); } public void Initialize( int testCount, string text ) { this.statusPanel.Text = text; this.testCount = testCount; this.testsRun = 0; this.failures = 0; this.time = 0; InitPanels(); } private void InitPanels() { DisplayTestCount(); this.testsRunPanel.Text = ""; this.failuresPanel.Text = ""; this.timePanel.Text = ""; } private void DisplayTestCount() { this.testCountPanel.Text = "Test Cases : " + testCount.ToString(); } private void DisplayTestsRun() { this.testsRunPanel.Text = "Tests Run : " + testsRun.ToString(); } private void DisplayFailures() { this.failuresPanel.Text = "Failures : " + failures.ToString(); } private void DisplayTime() { this.timePanel.Text = "Time : " + time.ToString(); } private void DisplayResult(TestResult result) { ResultSummarizer summarizer = new ResultSummarizer(result); int failureCount = summarizer.FailureCount; failuresPanel.Text = "Failures : " + failureCount.ToString(); testsRunPanel.Text = "Tests Run : " + summarizer.ResultCount.ToString(); timePanel.Text = "Time : " + summarizer.Time.ToString(); } public void OnTestLoaded( object sender, TestEventArgs e ) { Initialize( e.TestCount ); } public void OnTestReloaded( object sender, TestEventArgs e ) { Initialize( e.TestCount, "Reloaded" ); } public void OnTestUnloaded( object sender, TestEventArgs e ) { Initialize( 0, "Unloaded" ); } private void OnRunStarting( object sender, TestEventArgs e ) { Initialize( e.TestCount, "Running :" + e.Name ); DisplayTestCount(); DisplayFailures(); DisplayTime(); } private void OnRunFinished(object sender, TestEventArgs e ) { if ( e.Exception != null ) statusPanel.Text = "Failed"; else { statusPanel.Text = "Completed"; DisplayResult( e.Result ); } } public void OnTestStarting( object sender, TestEventArgs e ) { string fullText = "Running : " + e.TestName.FullName; string shortText = "Running : " + e.TestName.Name; Graphics g = Graphics.FromHwnd( Handle ); SizeF sizeNeeded = g.MeasureString( fullText, Font ); if ( statusPanel.Width >= (int)sizeNeeded.Width ) { statusPanel.Text = fullText; statusPanel.ToolTipText = ""; } else { sizeNeeded = g.MeasureString( shortText, Font ); statusPanel.Text = statusPanel.Width >= (int)sizeNeeded.Width ? shortText : e.TestName.Name; statusPanel.ToolTipText = e.TestName.FullName; } } private void OnTestFinished( object sender, TestEventArgs e ) { if ( DisplayTestProgress && e.Result.Executed ) { ++testsRun; DisplayTestsRun(); if ( e.Result.IsFailure ) { ++failures; DisplayFailures(); } } } #region TestObserver Members public void Subscribe(ITestEvents events) { events.TestLoaded += new TestEventHandler( OnTestLoaded ); events.TestReloaded += new TestEventHandler( OnTestReloaded ); events.TestUnloaded += new TestEventHandler( OnTestUnloaded ); events.TestStarting += new TestEventHandler( OnTestStarting ); events.TestFinished += new TestEventHandler( OnTestFinished ); events.RunStarting += new TestEventHandler( OnRunStarting ); events.RunFinished += new TestEventHandler( OnRunFinished ); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** Purpose: Create a Memorystream over an UnmanagedMemoryStream ** ===========================================================*/ using System; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { // Needed for backwards compatibility with V1.x usages of the // ResourceManager, where a MemoryStream is now returned as an // UnmanagedMemoryStream from ResourceReader. internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream { private UnmanagedMemoryStream _unmanagedStream; internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream) { _unmanagedStream = stream; } public override bool CanRead { [Pure] get { return _unmanagedStream.CanRead; } } public override bool CanSeek { [Pure] get { return _unmanagedStream.CanSeek; } } public override bool CanWrite { [Pure] get { return _unmanagedStream.CanWrite; } } protected override void Dispose(bool disposing) { try { if (disposing) _unmanagedStream.Close(); } finally { base.Dispose(disposing); } } public override void Flush() { _unmanagedStream.Flush(); } public override byte[] GetBuffer() { throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); } public override bool TryGetBuffer(out ArraySegment<byte> buffer) { buffer = default(ArraySegment<byte>); return false; } public override int Capacity { get { return (int)_unmanagedStream.Capacity; } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. set { throw new IOException(SR.IO_FixedCapacity); } } public override long Length { get { return _unmanagedStream.Length; } } public override long Position { get { return _unmanagedStream.Position; } set { _unmanagedStream.Position = value; } } public override int Read([In, Out] byte[] buffer, int offset, int count) { return _unmanagedStream.Read(buffer, offset, count); } public override int ReadByte() { return _unmanagedStream.ReadByte(); } public override long Seek(long offset, SeekOrigin loc) { return _unmanagedStream.Seek(offset, loc); } public unsafe override byte[] ToArray() { if (!_unmanagedStream._isOpen) __Error.StreamIsClosed(); if (!_unmanagedStream.CanRead) __Error.ReadNotSupported(); byte[] buffer = new byte[_unmanagedStream.Length]; Buffer.Memcpy(buffer, 0, _unmanagedStream.Pointer, 0, (int)_unmanagedStream.Length); return buffer; } public override void Write(byte[] buffer, int offset, int count) { _unmanagedStream.Write(buffer, offset, count); } public override void WriteByte(byte value) { _unmanagedStream.WriteByte(value); } // Writes this MemoryStream to another stream. public unsafe override void WriteTo(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); Contract.EndContractBlock(); if (!_unmanagedStream._isOpen) __Error.StreamIsClosed(); if (!CanRead) __Error.ReadNotSupported(); byte[] buffer = ToArray(); stream.Write(buffer, 0, buffer.Length); } public override void SetLength(Int64 value) { // This was probably meant to call _unmanagedStream.SetLength(value), but it was forgotten in V.4.0. // Now this results in a call to the base which touches the underlying array which is never actually used. // We cannot fix it due to compat now, but we should fix this at the next SxS release oportunity. base.SetLength(value); } public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { // The parameter checks must be in sync with the base version: if (destination == null) throw new ArgumentNullException(nameof(destination)); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (!CanRead && !CanWrite) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (!destination.CanRead && !destination.CanWrite) throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (!destination.CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); Contract.EndContractBlock(); return _unmanagedStream.CopyToAsync(destination, bufferSize, cancellationToken); } public override Task FlushAsync(CancellationToken cancellationToken) { return _unmanagedStream.FlushAsync(cancellationToken); } public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken); } public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken); } } // class UnmanagedMemoryStreamWrapper } // namespace
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Reflection; using System.Runtime; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Orleans.CodeGeneration; using Orleans.Core; using Orleans.GrainDirectory; using Orleans.Providers; using Orleans.Runtime.Configuration; using Orleans.Runtime.ConsistentRing; using Orleans.Runtime.Counters; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.MembershipService; using Orleans.Runtime.Messaging; using Orleans.Runtime.MultiClusterNetwork; using Orleans.Runtime.Placement; using Orleans.Runtime.Providers; using Orleans.Runtime.ReminderService; using Orleans.Runtime.Scheduler; using Orleans.Runtime.Services; using Orleans.Runtime.Startup; using Orleans.Runtime.Storage; using Orleans.Runtime.TestHooks; using Orleans.Serialization; using Orleans.Services; using Orleans.Storage; using Orleans.Streams; using Orleans.Timers; namespace Orleans.Runtime { /// <summary> /// Orleans silo. /// </summary> public class Silo { /// <summary> Standard name for Primary silo. </summary> public const string PrimarySiloName = "Primary"; /// <summary> Silo Types. </summary> public enum SiloType { /// <summary> No silo type specified. </summary> None = 0, /// <summary> Primary silo. </summary> Primary, /// <summary> Secondary silo. </summary> Secondary, } private readonly SiloInitializationParameters initializationParams; private readonly ISiloMessageCenter messageCenter; private readonly OrleansTaskScheduler scheduler; private readonly LocalGrainDirectory localGrainDirectory; private readonly ActivationDirectory activationDirectory; private readonly IncomingMessageAgent incomingAgent; private readonly IncomingMessageAgent incomingSystemAgent; private readonly IncomingMessageAgent incomingPingAgent; private readonly Logger logger; private readonly GrainTypeManager grainTypeManager; private TypeManager typeManager; private readonly ManualResetEvent siloTerminatedEvent; private readonly SiloStatisticsManager siloStatistics; private readonly MembershipFactory membershipFactory; private readonly InsideRuntimeClient runtimeClient; private readonly AssemblyProcessor assemblyProcessor; private StorageProviderManager storageProviderManager; private StatisticsProviderManager statisticsProviderManager; private BootstrapProviderManager bootstrapProviderManager; private IReminderService reminderService; private ProviderManagerSystemTarget providerManagerSystemTarget; private readonly IMembershipOracle membershipOracle; private IMultiClusterOracle multiClusterOracle; private Watchdog platformWatchdog; private readonly TimeSpan initTimeout; private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1); private readonly Catalog catalog; private readonly List<IHealthCheckParticipant> healthCheckParticipants = new List<IHealthCheckParticipant>(); private readonly object lockable = new object(); private readonly GrainFactory grainFactory; private readonly IGrainRuntime grainRuntime; private readonly List<IProvider> allSiloProviders = new List<IProvider>(); /// <summary> /// Gets the type of this /// </summary> public SiloType Type => this.initializationParams.Type; internal string Name => this.initializationParams.Name; internal ClusterConfiguration OrleansConfig => this.initializationParams.ClusterConfig; internal GlobalConfiguration GlobalConfig => this.initializationParams.GlobalConfig; internal NodeConfiguration LocalConfig => this.initializationParams.NodeConfig; internal OrleansTaskScheduler LocalScheduler { get { return scheduler; } } internal GrainTypeManager LocalGrainTypeManager { get { return grainTypeManager; } } internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } } internal ISiloStatusOracle LocalSiloStatusOracle { get { return membershipOracle; } } internal IMultiClusterOracle LocalMultiClusterOracle { get { return multiClusterOracle; } } internal IConsistentRingProvider RingProvider { get; private set; } internal IStorageProviderManager StorageProviderManager { get { return storageProviderManager; } } internal IProviderManager StatisticsProviderManager { get { return statisticsProviderManager; } } internal IStreamProviderManager StreamProviderManager { get { return grainRuntime.StreamProviderManager; } } internal IList<IBootstrapProvider> BootstrapProviders { get; private set; } internal ISiloPerformanceMetrics Metrics { get { return siloStatistics.MetricsTable; } } internal static Silo CurrentSilo { get; private set; } internal IReadOnlyCollection<IProvider> AllSiloProviders { get { return allSiloProviders.AsReadOnly(); } } internal ICatalog Catalog => catalog; internal IServiceProvider Services { get; } /// <summary> Get the id of the cluster this silo is part of. </summary> public string ClusterId { get { return GlobalConfig.HasMultiClusterNetwork ? GlobalConfig.ClusterId : null; } } /// <summary> SiloAddress for this silo. </summary> public SiloAddress SiloAddress => this.initializationParams.SiloAddress; /// <summary> /// Silo termination event used to signal shutdown of this silo. /// </summary> public WaitHandle SiloTerminatedEvent { get { return siloTerminatedEvent; } } // one event for all types of termination (shutdown, stop and fast kill). /// <summary> /// Test hook connection for white-box testing of silo. /// </summary> internal TestHooksSystemTarget testHook; /// <summary> /// Initializes a new instance of the <see cref="Silo"/> class. /// </summary> /// <param name="name">Name of this silo.</param> /// <param name="siloType">Type of this silo.</param> /// <param name="config">Silo config data to be used for this silo.</param> public Silo(string name, SiloType siloType, ClusterConfiguration config) : this(new SiloInitializationParameters(name, siloType, config)) { } /// <summary> /// Initializes a new instance of the <see cref="Silo"/> class. /// </summary> /// <param name="initializationParams"> /// The silo initialization parameters. /// </param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")] internal Silo(SiloInitializationParameters initializationParams) { string name = initializationParams.Name; ClusterConfiguration config = initializationParams.ClusterConfig; this.initializationParams = initializationParams; SystemStatus.Current = SystemStatus.Creating; CurrentSilo = this; var startTime = DateTime.UtcNow; siloTerminatedEvent = new ManualResetEvent(false); if (!LogManager.IsInitialized) LogManager.Initialize(LocalConfig); config.OnConfigChange("Defaults/Tracing", () => LogManager.Initialize(LocalConfig, true), false); MultiClusterRegistrationStrategy.Initialize(config.Globals); StatisticsCollector.Initialize(LocalConfig); SerializationManager.Initialize(GlobalConfig.SerializationProviders, this.GlobalConfig.FallbackSerializationProvider); initTimeout = GlobalConfig.MaxJoinAttemptTime; if (Debugger.IsAttached) { initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), GlobalConfig.MaxJoinAttemptTime); stopTimeout = initTimeout; } var localEndpoint = this.initializationParams.SiloAddress.Endpoint; LogManager.MyIPEndPoint = localEndpoint; logger = LogManager.GetLogger("Silo", LoggerType.Runtime); logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode)); if (!GCSettings.IsServerGC || !GCSettings.LatencyMode.Equals(GCLatencyMode.Batch)) { logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on or with GCLatencyMode.Batch enabled - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\"> and <configuration>-<runtime>-<gcConcurrent enabled=\"false\"/>"); logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines)."); } logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing {0} silo on host {1} MachineName {2} at {3}, gen {4} --------------", this.initializationParams.Type, LocalConfig.DNSHostName, Environment.MachineName, localEndpoint, this.initializationParams.SiloAddress.Generation); logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0} with the following configuration= " + Environment.NewLine + "{1}", name, config.ToString(name)); // Configure DI using Startup type this.Services = StartupBuilder.ConfigureStartup( this.LocalConfig.StartupTypeName, (services, usingCustomServiceProvider) => { // add system types // Note: you can replace IGrainFactory with your own implementation, but // we don't recommend it, in the aspect of performance and usability services.TryAddSingleton(sp => sp); services.TryAddSingleton(this); services.TryAddSingleton(initializationParams); services.TryAddSingleton<ILocalSiloDetails>(initializationParams); services.TryAddSingleton(initializationParams.ClusterConfig); services.TryAddSingleton(initializationParams.GlobalConfig); services.TryAddTransient(sp => initializationParams.NodeConfig); services.TryAddSingleton<ITimerRegistry, TimerRegistry>(); services.TryAddSingleton<IReminderRegistry, ReminderRegistry>(); services.TryAddSingleton<IStreamProviderManager, StreamProviderManager>(); services.TryAddSingleton<GrainRuntime>(); services.TryAddSingleton<IGrainRuntime, GrainRuntime>(); services.TryAddSingleton<OrleansTaskScheduler>(); services.TryAddSingleton<GrainFactory>(sp => sp.GetService<InsideRuntimeClient>().ConcreteGrainFactory); services.TryAddExisting<IGrainFactory, GrainFactory>(); services.TryAddExisting<IInternalGrainFactory, GrainFactory>(); services.TryAddSingleton<TypeMetadataCache>(); services.TryAddSingleton<AssemblyProcessor>(); services.TryAddSingleton<ActivationDirectory>(); services.TryAddSingleton<LocalGrainDirectory>(); services.TryAddExisting<ILocalGrainDirectory, LocalGrainDirectory>(); services.TryAddSingleton<SiloStatisticsManager>(); services.TryAddSingleton<ISiloPerformanceMetrics>(sp => sp.GetRequiredService<SiloStatisticsManager>().MetricsTable); services.TryAddSingleton<SiloAssemblyLoader>(); services.TryAddSingleton<GrainTypeManager>(); services.TryAddExisting<IMessagingConfiguration, GlobalConfiguration>(); services.TryAddSingleton<MessageCenter>(); services.TryAddExisting<IMessageCenter, MessageCenter>(); services.TryAddExisting<ISiloMessageCenter, MessageCenter>(); services.TryAddSingleton<Catalog>(); services.TryAddSingleton(sp => sp.GetRequiredService<Catalog>().Dispatcher); services.TryAddSingleton<InsideRuntimeClient>(); services.TryAddExisting<IRuntimeClient, InsideRuntimeClient>(); services.TryAddExisting<ISiloRuntimeClient, InsideRuntimeClient>(); services.TryAddSingleton<MembershipFactory>(); services.TryAddSingleton<MultiClusterOracleFactory>(); services.TryAddSingleton<DeploymentLoadPublisher>(); services.TryAddSingleton<IMembershipTable>( sp => sp.GetRequiredService<MembershipFactory>().GetMembershipTable(sp.GetRequiredService<GlobalConfiguration>())); services.TryAddSingleton<MembershipOracle>( sp => sp.GetRequiredService<MembershipFactory>() .CreateMembershipOracle(sp.GetRequiredService<Silo>(), sp.GetRequiredService<IMembershipTable>())); services.TryAddExisting<IMembershipOracle, MembershipOracle>(); services.TryAddExisting<ISiloStatusOracle, MembershipOracle>(); services.TryAddSingleton<Func<ISiloStatusOracle>>(sp => () => sp.GetRequiredService<ISiloStatusOracle>()); services.TryAddSingleton<MultiClusterOracleFactory>(); services.TryAddSingleton<LocalReminderServiceFactory>(); services.TryAddSingleton<ClientObserverRegistrar>(); services.TryAddSingleton<SiloProviderRuntime>(); services.TryAddExisting<IStreamProviderRuntime, SiloProviderRuntime>(); services.TryAddSingleton<ImplicitStreamSubscriberTable>(); // Placement services.TryAddSingleton<PlacementDirectorsManager>(); services.TryAddSingleton<IPlacementDirector<RandomPlacement>, RandomPlacementDirector>(); services.TryAddSingleton<IPlacementDirector<PreferLocalPlacement>, PreferLocalPlacementDirector>(); services.TryAddSingleton<IPlacementDirector<StatelessWorkerPlacement>, StatelessWorkerDirector>(); services.TryAddSingleton<IPlacementDirector<ActivationCountBasedPlacement>, ActivationCountPlacementDirector>(); services.TryAddSingleton<DefaultPlacementStrategy>(); services.TryAddSingleton<ClientObserversPlacementDirector>(); services.TryAddSingleton<Func<IGrainRuntime>>(sp => () => sp.GetRequiredService<IGrainRuntime>()); services.TryAddSingleton<GrainCreator>(); if (initializationParams.GlobalConfig.UseVirtualBucketsConsistentRing) { services.TryAddSingleton<IConsistentRingProvider>( sp => new VirtualBucketsRingProvider( this.initializationParams.SiloAddress, this.initializationParams.GlobalConfig.NumVirtualBucketsConsistentRing)); } else { services.TryAddSingleton<IConsistentRingProvider>( sp => new ConsistentRingProvider(this.initializationParams.SiloAddress)); } }); this.assemblyProcessor = this.Services.GetRequiredService<AssemblyProcessor>(); this.assemblyProcessor.Initialize(); BufferPool.InitGlobalBufferPool(GlobalConfig); UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnobservedExceptionHandler); AppDomain.CurrentDomain.UnhandledException += this.DomainUnobservedExceptionHandler; try { grainFactory = Services.GetRequiredService<GrainFactory>(); } catch (InvalidOperationException exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc); throw; } grainTypeManager = Services.GetRequiredService<GrainTypeManager>(); // Performance metrics siloStatistics = Services.GetRequiredService<SiloStatisticsManager>(); // The scheduler scheduler = Services.GetRequiredService<OrleansTaskScheduler>(); healthCheckParticipants.Add(scheduler); runtimeClient = Services.GetRequiredService<InsideRuntimeClient>(); // Initialize the message center messageCenter = Services.GetRequiredService<MessageCenter>(); messageCenter.RerouteHandler = runtimeClient.RerouteMessage; messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage; // GrainRuntime can be created only here, after messageCenter was created. grainRuntime = Services.GetRequiredService<IGrainRuntime>(); // Now the router/directory service // This has to come after the message center //; note that it then gets injected back into the message center.; localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>(); // Now the activation directory. activationDirectory = Services.GetRequiredService<ActivationDirectory>(); // Now the consistent ring provider RingProvider = Services.GetRequiredService<IConsistentRingProvider>(); // to preserve backwards compatibility, only use the service provider to inject grain dependencies if the user supplied his own // service provider, meaning that he is explicitly opting into it. catalog = Services.GetRequiredService<Catalog>(); siloStatistics.MetricsTable.Scheduler = scheduler; siloStatistics.MetricsTable.ActivationDirectory = activationDirectory; siloStatistics.MetricsTable.ActivationCollector = catalog.ActivationCollector; siloStatistics.MetricsTable.MessageCenter = messageCenter; // Now the incoming message agents incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, catalog.Dispatcher); incomingPingAgent = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, catalog.Dispatcher); incomingAgent = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, catalog.Dispatcher); membershipFactory = Services.GetRequiredService<MembershipFactory>(); membershipOracle = Services.GetRequiredService<IMembershipOracle>(); SystemStatus.Current = SystemStatus.Created; StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME, () => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs. logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode()); } private void CreateSystemTargets() { logger.Verbose("Creating System Targets for this silo."); logger.Verbose("Creating {0} System Target", "SiloControl"); var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services); RegisterSystemTarget(siloControl); logger.Verbose("Creating {0} System Target", "StreamProviderUpdateAgent"); RegisterSystemTarget( new StreamProviderManagerAgent(this, allSiloProviders, Services.GetRequiredService<IStreamProviderRuntime>())); logger.Verbose("Creating {0} System Target", "DeploymentLoadPublisher"); RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>()); logger.Verbose("Creating {0} System Target", "RemoteGrainDirectory + CacheValidator"); RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory); RegisterSystemTarget(LocalGrainDirectory.CacheValidator); logger.Verbose("Creating {0} System Target", "RemoteClusterGrainDirectory"); RegisterSystemTarget(LocalGrainDirectory.RemoteClusterGrainDirectory); logger.Verbose("Creating {0} System Target", "ClientObserverRegistrar + TypeManager"); this.RegisterSystemTarget(this.Services.GetRequiredService<ClientObserverRegistrar>()); var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>(); typeManager = new TypeManager(SiloAddress, this.grainTypeManager, membershipOracle, LocalScheduler, GlobalConfig.TypeMapRefreshInterval, implicitStreamSubscriberTable); this.RegisterSystemTarget(typeManager); logger.Verbose("Creating {0} System Target", "MembershipOracle"); if (this.membershipOracle is SystemTarget) { RegisterSystemTarget((SystemTarget)membershipOracle); } if (multiClusterOracle != null && multiClusterOracle is SystemTarget) { logger.Verbose("Creating {0} System Target", "MultiClusterOracle"); RegisterSystemTarget((SystemTarget)multiClusterOracle); } logger.Verbose("Finished creating System Targets for this silo."); } internal void InitializeTestHooksSystemTarget() { testHook = new TestHooksSystemTarget(this); RegisterSystemTarget(testHook); } private void InjectDependencies() { healthCheckParticipants.Add(membershipOracle); catalog.SiloStatusOracle = LocalSiloStatusOracle; localGrainDirectory.CatalogSiloStatusListener = catalog; LocalSiloStatusOracle.SubscribeToSiloStatusEvents(localGrainDirectory); messageCenter.SiloDeadOracle = LocalSiloStatusOracle.IsDeadSilo; // consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here LocalSiloStatusOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider); LocalSiloStatusOracle.SubscribeToSiloStatusEvents(typeManager); LocalSiloStatusOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>()); if (!GlobalConfig.ReminderServiceType.Equals(GlobalConfiguration.ReminderServiceProviderType.Disabled)) { // start the reminder service system target reminderService = Services.GetRequiredService<LocalReminderServiceFactory>() .CreateReminderService(this, grainFactory, initTimeout, this.runtimeClient); RegisterSystemTarget((SystemTarget) reminderService); } RegisterSystemTarget(catalog); scheduler.QueueAction(catalog.Start, catalog.SchedulingContext) .WaitWithThrow(initTimeout); // SystemTarget for provider init calls providerManagerSystemTarget = new ProviderManagerSystemTarget(this); RegisterSystemTarget(providerManagerSystemTarget); } private async Task CreateSystemGrains() { if (Type == SiloType.Primary) await membershipFactory.CreateMembershipTableProvider(catalog, this).WithTimeout(initTimeout); } /// <summary> Perform silo startup operations. </summary> public void Start() { try { DoStart(); } catch (Exception exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc); throw; } } private void DoStart() { lock (lockable) { if (!SystemStatus.Current.Equals(SystemStatus.Created)) throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", SystemStatus.Current)); SystemStatus.Current = SystemStatus.Starting; } logger.Info(ErrorCode.SiloStarting, "Silo Start()"); // Hook up to receive notification of process exit / Ctrl-C events AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; Console.CancelKeyPress += HandleProcessExit; ConfigureThreadPoolAndServicePointSettings(); // This has to start first so that the directory system target factory gets loaded before we start the router. grainTypeManager.Start(); runtimeClient.Start(); // The order of these 4 is pretty much arbitrary. scheduler.Start(); messageCenter.Start(); incomingPingAgent.Start(); incomingSystemAgent.Start(); incomingAgent.Start(); LocalGrainDirectory.Start(); // Set up an execution context for this thread so that the target creation steps can use asynch values. RuntimeContext.InitializeMainThread(); // Initialize the implicit stream subscribers table. var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>(); implicitStreamSubscriberTable.InitImplicitStreamSubscribers(this.grainTypeManager.GrainClassTypeData.Select(t => t.Value.Type).ToArray()); var siloProviderRuntime = Services.GetRequiredService<SiloProviderRuntime>(); runtimeClient.CurrentStreamProviderRuntime = siloProviderRuntime; statisticsProviderManager = new StatisticsProviderManager("Statistics", siloProviderRuntime); string statsProviderName = statisticsProviderManager.LoadProvider(GlobalConfig.ProviderConfigurations) .WaitForResultWithThrow(initTimeout); if (statsProviderName != null) LocalConfig.StatisticsProviderName = statsProviderName; allSiloProviders.AddRange(statisticsProviderManager.GetProviders()); // can call SetSiloMetricsTableDataManager only after MessageCenter is created (dependency on this.SiloAddress). siloStatistics.SetSiloStatsTableDataManager(this, LocalConfig).WaitWithThrow(initTimeout); siloStatistics.SetSiloMetricsTableDataManager(this, LocalConfig).WaitWithThrow(initTimeout); IMembershipTable membershipTable = Services.GetRequiredService<IMembershipTable>(); multiClusterOracle = Services.GetRequiredService<MultiClusterOracleFactory>().CreateGossipOracle(this).WaitForResultWithThrow(initTimeout); // This has to follow the above steps that start the runtime components CreateSystemTargets(); InjectDependencies(); // Validate the configuration. GlobalConfig.Application.ValidateConfiguration(logger); // ensure this runs in the grain context, wait for it to complete scheduler.QueueTask(CreateSystemGrains, catalog.SchedulingContext) .WaitWithThrow(initTimeout); if (logger.IsVerbose) { logger.Verbose("System grains created successfully."); } // Initialize storage providers once we have a basic silo runtime environment operating storageProviderManager = new StorageProviderManager(grainFactory, Services, siloProviderRuntime); scheduler.QueueTask( () => storageProviderManager.LoadStorageProviders(GlobalConfig.ProviderConfigurations), providerManagerSystemTarget.SchedulingContext) .WaitWithThrow(initTimeout); catalog.SetStorageManager(storageProviderManager); allSiloProviders.AddRange(storageProviderManager.GetProviders()); if (logger.IsVerbose) { logger.Verbose("Storage provider manager created successfully."); } // Load and init stream providers before silo becomes active var siloStreamProviderManager = (StreamProviderManager)grainRuntime.StreamProviderManager; scheduler.QueueTask( () => siloStreamProviderManager.LoadStreamProviders(GlobalConfig.ProviderConfigurations, siloProviderRuntime), providerManagerSystemTarget.SchedulingContext) .WaitWithThrow(initTimeout); runtimeClient.CurrentStreamProviderManager = siloStreamProviderManager; allSiloProviders.AddRange(siloStreamProviderManager.GetProviders()); if (logger.IsVerbose) { logger.Verbose("Stream provider manager created successfully."); } // Load and init grain services before silo becomes active. CreateGrainServices(GlobalConfig.GrainServiceConfigurations); ISchedulingContext statusOracleContext = ((SystemTarget)LocalSiloStatusOracle).SchedulingContext; bool waitForPrimaryToStart = GlobalConfig.PrimaryNodeIsRequired && Type != SiloType.Primary; if (waitForPrimaryToStart) // only in MembershipTableGrain case. { scheduler.QueueTask(() => membershipFactory.WaitForTableToInit(membershipTable), statusOracleContext) .WaitWithThrow(initTimeout); } scheduler.QueueTask(() => membershipTable.InitializeMembershipTable(GlobalConfig, true, LogManager.GetLogger(membershipTable.GetType().Name)), statusOracleContext) .WaitWithThrow(initTimeout); scheduler.QueueTask(() => LocalSiloStatusOracle.Start(), statusOracleContext) .WaitWithThrow(initTimeout); if (logger.IsVerbose) { logger.Verbose("Local silo status oracle created successfully."); } scheduler.QueueTask(LocalSiloStatusOracle.BecomeActive, statusOracleContext) .WaitWithThrow(initTimeout); if (logger.IsVerbose) { logger.Verbose("Local silo status oracle became active successfully."); } //if running in multi cluster scenario, start the MultiClusterNetwork Oracle if (GlobalConfig.HasMultiClusterNetwork) { logger.Info("Creating multicluster oracle with my ServiceId={0} and ClusterId={1}.", GlobalConfig.ServiceId, GlobalConfig.ClusterId); ISchedulingContext clusterStatusContext = ((SystemTarget) multiClusterOracle).SchedulingContext; scheduler.QueueTask(() => multiClusterOracle.Start(LocalSiloStatusOracle), clusterStatusContext) .WaitWithThrow(initTimeout); if (logger.IsVerbose) { logger.Verbose("multicluster oracle created successfully."); } } try { this.siloStatistics.Start(this.LocalConfig); if (this.logger.IsVerbose) { this.logger.Verbose("Silo statistics manager started successfully."); } // Finally, initialize the deployment load collector, for grains with load-based placement var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>(); this.scheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher.SchedulingContext) .WaitWithThrow(this.initTimeout); if (this.logger.IsVerbose) { this.logger.Verbose("Silo deployment load publisher started successfully."); } // Start background timer tick to watch for platform execution stalls, such as when GC kicks in this.platformWatchdog = new Watchdog(this.LocalConfig.StatisticsLogWriteInterval, this.healthCheckParticipants); this.platformWatchdog.Start(); if (this.logger.IsVerbose) { this.logger.Verbose("Silo platform watchdog started successfully."); } if (this.reminderService != null) { // so, we have the view of the membership in the consistentRingProvider. We can start the reminder service this.scheduler.QueueTask(this.reminderService.Start, ((SystemTarget)this.reminderService).SchedulingContext) .WaitWithThrow(this.initTimeout); if (this.logger.IsVerbose) { this.logger.Verbose("Reminder service started successfully."); } } this.bootstrapProviderManager = new BootstrapProviderManager(); this.scheduler.QueueTask( () => this.bootstrapProviderManager.LoadAppBootstrapProviders(siloProviderRuntime, this.GlobalConfig.ProviderConfigurations), this.providerManagerSystemTarget.SchedulingContext) .WaitWithThrow(this.initTimeout); this.BootstrapProviders = this.bootstrapProviderManager.GetProviders(); // Data hook for testing & diagnotics this.allSiloProviders.AddRange(this.BootstrapProviders); if (this.logger.IsVerbose) { this.logger.Verbose("App bootstrap calls done successfully."); } // Start stream providers after silo is active (so the pulling agents don't start sending messages before silo is active). // also after bootstrap provider started so bootstrap provider can initialize everything stream before events from this silo arrive. this.scheduler.QueueTask(siloStreamProviderManager.StartStreamProviders, this.providerManagerSystemTarget.SchedulingContext) .WaitWithThrow(this.initTimeout); if (this.logger.IsVerbose) { this.logger.Verbose("Stream providers started successfully."); } // Now that we're active, we can start the gateway var mc = this.messageCenter as MessageCenter; mc?.StartGateway(this.Services.GetRequiredService<ClientObserverRegistrar>()); if (this.logger.IsVerbose) { this.logger.Verbose("Message gateway service started successfully."); } SystemStatus.Current = SystemStatus.Running; } catch (Exception exc) { this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc)); this.FastKill(); // if failed after Membership became active, mark itself as dead in Membership abale. throw; } if (logger.IsVerbose) { logger.Verbose("Silo.Start complete: System status = {0}", SystemStatus.Current); } } private void CreateGrainServices(GrainServiceConfigurations grainServiceConfigurations) { foreach (var serviceConfig in grainServiceConfigurations.GrainServices) { // Construct the Grain Service var serviceType = System.Type.GetType(serviceConfig.Value.ServiceType); if (serviceType == null) { throw new Exception(String.Format("Cannot find Grain Service type {0} of Grain Service {1}", serviceConfig.Value.ServiceType, serviceConfig.Value.Name)); } var grainServiceInterfaceType = serviceType.GetInterfaces().FirstOrDefault(x => x.GetInterfaces().Contains(typeof(IGrainService))); if (grainServiceInterfaceType == null) { throw new Exception(String.Format("Cannot find an interface on {0} which implements IGrainService", serviceConfig.Value.ServiceType)); } var typeCode = GrainInterfaceUtils.GetGrainClassTypeCode(grainServiceInterfaceType); var grainId = (IGrainIdentity)GrainId.GetGrainServiceGrainId(0, typeCode); var grainService = (SystemTarget) ActivatorUtilities.CreateInstance(this.Services, serviceType, grainId, serviceConfig.Value); RegisterSystemTarget(grainService); } } /// <summary> /// Load and initialize newly added stream providers. Remove providers that are not on the list that's being passed in. /// </summary> public async Task UpdateStreamProviders(IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations) { IStreamProviderManagerAgent streamProviderUpdateAgent = runtimeClient.InternalGrainFactory.GetSystemTarget<IStreamProviderManagerAgent>(Constants.StreamProviderManagerAgentSystemTargetId, this.SiloAddress); await scheduler.QueueTask(() => streamProviderUpdateAgent.UpdateStreamProviders(streamProviderConfigurations), providerManagerSystemTarget.SchedulingContext) .WithTimeout(initTimeout); } private void ConfigureThreadPoolAndServicePointSettings() { #if !NETSTANDARD_TODO if (LocalConfig.MinDotNetThreadPoolSize > 0) { int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); if (LocalConfig.MinDotNetThreadPoolSize > workerThreads || LocalConfig.MinDotNetThreadPoolSize > completionPortThreads) { // if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value. int newWorkerThreads = Math.Max(LocalConfig.MinDotNetThreadPoolSize, workerThreads); int newCompletionPortThreads = Math.Max(LocalConfig.MinDotNetThreadPoolSize, completionPortThreads); bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads); if (ok) { logger.Info(ErrorCode.SiloConfiguredThreadPool, "Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } else { logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool, "Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } } } // Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage // http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx logger.Info(ErrorCode.SiloConfiguredServicePointManager, "Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.", LocalConfig.Expect100Continue, LocalConfig.DefaultConnectionLimit, LocalConfig.UseNagleAlgorithm); ServicePointManager.Expect100Continue = LocalConfig.Expect100Continue; ServicePointManager.DefaultConnectionLimit = LocalConfig.DefaultConnectionLimit; ServicePointManager.UseNagleAlgorithm = LocalConfig.UseNagleAlgorithm; #endif } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// Grains are not deactivated. /// </summary> public void Stop() { Terminate(false); } /// <summary> /// Gracefully stop the run time system and the application. /// All grains will be properly deactivated. /// All in-flight applications requests would be awaited and finished gracefully. /// </summary> public void Shutdown() { Terminate(true); } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// </summary> private void Terminate(bool gracefully) { string operation = gracefully ? "Shutdown()" : "Stop()"; bool stopAlreadyInProgress = false; lock (lockable) { if (SystemStatus.Current.Equals(SystemStatus.Stopping) || SystemStatus.Current.Equals(SystemStatus.ShuttingDown) || SystemStatus.Current.Equals(SystemStatus.Terminated)) { stopAlreadyInProgress = true; // Drop through to wait below } else if (!SystemStatus.Current.Equals(SystemStatus.Running)) { throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, SystemStatus.Current)); } else { if (gracefully) SystemStatus.Current = SystemStatus.ShuttingDown; else SystemStatus.Current = SystemStatus.Stopping; } } if (stopAlreadyInProgress) { logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish"); var pause = TimeSpan.FromSeconds(1); while (!SystemStatus.Current.Equals(SystemStatus.Terminated)) { logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause); Thread.Sleep(pause); } return; } try { try { if (gracefully) { logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()"); // 1: Write "ShutDown" state in the table + broadcast gossip msgs to re-read the table to everyone scheduler.QueueTask(LocalSiloStatusOracle.ShutDown, ((SystemTarget)LocalSiloStatusOracle).SchedulingContext) .WaitWithThrow(stopTimeout); } else { logger.Info(ErrorCode.SiloStopping, "Silo starting to Stop()"); // 1: Write "Stopping" state in the table + broadcast gossip msgs to re-read the table to everyone scheduler.QueueTask(LocalSiloStatusOracle.Stop, ((SystemTarget)LocalSiloStatusOracle).SchedulingContext) .WaitWithThrow(stopTimeout); } } catch (Exception exc) { logger.Error(ErrorCode.SiloFailedToStopMembership, String.Format("Failed to {0} LocalSiloStatusOracle. About to FastKill this silo.", operation), exc); return; // will go to finally } if (reminderService != null) { // 2: Stop reminder service scheduler.QueueTask(reminderService.Stop, ((SystemTarget) reminderService).SchedulingContext) .WaitWithThrow(stopTimeout); } if (gracefully) { // 3: Deactivate all grains SafeExecute(() => catalog.DeactivateAllActivations().WaitWithThrow(stopTimeout)); } // 3: Stop the gateway SafeExecute(messageCenter.StopAcceptingClientMessages); // 4: Start rejecting all silo to silo application messages SafeExecute(messageCenter.BlockApplicationMessages); // 5: Stop scheduling/executing application turns SafeExecute(scheduler.StopApplicationTurns); // 6: Directory: Speed up directory handoff // will be started automatically when directory receives SiloStatusChangeNotification(Stopping) // 7: SafeExecute(() => LocalGrainDirectory.StopPreparationCompletion.WaitWithThrow(stopTimeout)); // The order of closing providers might be importan: Stats, streams, boostrap, storage. // Stats first since no one depends on it. // Storage should definitely be last since other providers ma ybe using it, potentilay indirectly. // Streams and Bootstrap - the order is less clear. Seems like Bootstrap may indirecly depend on Streams, but not the other way around. // 8: SafeExecute(() => { scheduler.QueueTask(() => statisticsProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext) .WaitWithThrow(initTimeout); }); // 9: SafeExecute(() => { var siloStreamProviderManager = (StreamProviderManager)grainRuntime.StreamProviderManager; scheduler.QueueTask(() => siloStreamProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext) .WaitWithThrow(initTimeout); }); // 10: SafeExecute(() => { scheduler.QueueTask(() => bootstrapProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext) .WaitWithThrow(initTimeout); }); // 11: SafeExecute(() => { scheduler.QueueTask(() => storageProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext) .WaitWithThrow(initTimeout); }); } finally { // 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ... logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()"); FastKill(); } } /// <summary> /// Ungracefully stop the run time system and the application running on it. /// Applications requests would be abruptly terminated, and the internal system state quickly stopped with minimal cleanup. /// </summary> private void FastKill() { if (!GlobalConfig.LivenessType.Equals(GlobalConfiguration.LivenessProviderType.MembershipTableGrain)) { // do not execute KillMyself if using MembershipTableGrain, since it will fail, as we've already stopped app scheduler turns. SafeExecute(() => scheduler.QueueTask( LocalSiloStatusOracle.KillMyself, ((SystemTarget)LocalSiloStatusOracle).SchedulingContext) .WaitWithThrow(stopTimeout)); } // incoming messages SafeExecute(incomingSystemAgent.Stop); SafeExecute(incomingPingAgent.Stop); SafeExecute(incomingAgent.Stop); // timers SafeExecute(runtimeClient.Stop); if (platformWatchdog != null) SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up SafeExecute(scheduler.Stop); SafeExecute(scheduler.PrintStatistics); SafeExecute(activationDirectory.PrintActivationDirectory); SafeExecute(messageCenter.Stop); SafeExecute(siloStatistics.Stop); SafeExecute(GrainTypeManager.Stop); UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler(); SafeExecute(() => SystemStatus.Current = SystemStatus.Terminated); SafeExecute(LogManager.Close); SafeExecute(() => AppDomain.CurrentDomain.UnhandledException -= this.DomainUnobservedExceptionHandler); SafeExecute(() => this.assemblyProcessor?.Dispose()); // Setting the event should be the last thing we do. // Do nothijng after that! siloTerminatedEvent.Set(); } private void SafeExecute(Action action) { Utils.SafeExecute(action, logger, "Silo.Stop"); } private void HandleProcessExit(object sender, EventArgs e) { // NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting"); LogManager.Flush(); try { lock (lockable) { if (!SystemStatus.Current.Equals(SystemStatus.Running)) return; SystemStatus.Current = SystemStatus.Stopping; } logger.Info(ErrorCode.SiloStopping, "Silo.HandleProcessExit() - starting to FastKill()"); FastKill(); } finally { LogManager.Close(); } } private void UnobservedExceptionHandler(ISchedulingContext context, Exception exception) { var schedulingContext = context as SchedulingContext; if (schedulingContext == null) { if (context == null) logger.Error(ErrorCode.Runtime_Error_100102, "Silo caught an UnobservedException with context==null.", exception); else logger.Error(ErrorCode.Runtime_Error_100103, String.Format("Silo caught an UnobservedException with context of type different than OrleansContext. The type of the context is {0}. The context is {1}", context.GetType(), context), exception); } else { logger.Error(ErrorCode.Runtime_Error_100104, String.Format("Silo caught an UnobservedException thrown by {0}.", schedulingContext.Activation), exception); } } private void DomainUnobservedExceptionHandler(object context, UnhandledExceptionEventArgs args) { var exception = (Exception)args.ExceptionObject; if (context is ISchedulingContext) UnobservedExceptionHandler(context as ISchedulingContext, exception); else logger.Error(ErrorCode.Runtime_Error_100324, String.Format("Called DomainUnobservedExceptionHandler with context {0}.", context), exception); } internal void RegisterSystemTarget(SystemTarget target) { scheduler.RegisterWorkContext(target.SchedulingContext); activationDirectory.RecordNewSystemTarget(target); } internal void UnregisterSystemTarget(SystemTarget target) { activationDirectory.RemoveSystemTarget(target); scheduler.UnregisterWorkContext(target.SchedulingContext); } /// <summary> Return dump of diagnostic data from this silo. </summary> /// <param name="all"></param> /// <returns>Debug data for this silo.</returns> public string GetDebugDump(bool all = true) { var sb = new StringBuilder(); foreach (var systemTarget in activationDirectory.AllSystemTargets()) sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine(); var enumerator = activationDirectory.GetEnumerator(); while(enumerator.MoveNext()) { Utils.SafeExecute(() => { var activationData = enumerator.Current.Value; var workItemGroup = scheduler.GetWorkItemGroup(new SchedulingContext(activationData)); if (workItemGroup == null) { sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.", activationData.Grain, activationData.ActivationId); sb.AppendLine(); return; } if (all || activationData.State.Equals(ActivationState.Valid)) { sb.AppendLine(workItemGroup.DumpStatus()); sb.AppendLine(activationData.DumpStatus()); } }); } logger.Info(ErrorCode.SiloDebugDump, sb.ToString()); return sb.ToString(); } /// <summary> Object.ToString override -- summary info for this silo. </summary> public override string ToString() { return localGrainDirectory.ToString(); } } // A dummy system target to use for scheduling context for provider Init calls, to allow them to make grain calls internal class ProviderManagerSystemTarget : SystemTarget { public ProviderManagerSystemTarget(Silo currentSilo) : base(Constants.ProviderManagerSystemTargetId, currentSilo.SiloAddress) { } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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; namespace MindTouch.Dream { /// <summary> /// Provides a <see cref="XUri"/> map for matching child uri's of an input Uri. /// </summary> /// <remarks> /// This map is a counterpart to <see cref="XUriMap{T}"/>, which matches the closest parent uri, instead of the children. /// Parent/Child relationships are determined by scheme/hostpot/path similarity. /// </remarks> /// <typeparam name="T">Type of object that is associated with each <see cref="XUri"/> entry</typeparam> public class XUriChildMap<T> { //--- Types --- private class Entry { //--- Fields --- public readonly Dictionary<string, Entry> Children = new Dictionary<string, Entry>(StringComparer.OrdinalIgnoreCase); public readonly List<T> Exact = new List<T>(); public readonly List<T> Wildcard = new List<T>(); //--- Methods --- public void Clear() { Children.Clear(); Exact.Clear(); Wildcard.Clear(); } } //--- Fields --- private readonly Entry _root = new Entry(); private readonly bool _ignoreScheme; //--- Constructors --- /// <summary> /// Create a scheme-sensitive map. /// </summary> public XUriChildMap() : this(false) { } /// <summary> /// Create a map. /// </summary> /// <param name="ignoreScheme"><see langword="True"/> if this map ignores scheme differences in matches.</param> public XUriChildMap(bool ignoreScheme) { _ignoreScheme = ignoreScheme; } //--- Properties --- /// <summary> /// <see langword="True"/> if this map ignores scheme differences in matches. /// </summary> public bool IgnoresScheme { get { return _ignoreScheme; } } //--- Methods --- /// <summary> /// Add a uri to the map. /// </summary> /// <param name="uri">Uri to add.</param> /// <param name="registrant">The reference object for the uri.</param> public void Add(XUri uri, T registrant) { string scheme = _ignoreScheme ? "any" : uri.Scheme; string hostport = uri.HostPort; Entry current = _root; Entry next; bool wildcard = false; if(uri.LastSegment == "*") { uri = uri.WithoutLastSegment(); wildcard = true; } // add scheme if(!current.Children.TryGetValue(scheme, out next)) { next = new Entry(); current.Children.Add(scheme, next); } current = next; // add Hostport if(!current.Children.TryGetValue(hostport, out next)) { next = new Entry(); current.Children.Add(hostport, next); } current = next; // add rest of Uri for(int i = 0; i < uri.Segments.Length; i++) { if(!current.Children.TryGetValue(uri.Segments[i], out next)) { next = new Entry(); current.Children.Add(uri.Segments[i], next); } current = next; } if(wildcard) { current.Wildcard.Add(registrant); } else { current.Exact.Add(registrant); } } /// <summary> /// Add a range of uri's for a single reference object /// </summary> /// <param name="uris">Uris to add.</param> /// <param name="registrant">The reference object for the uri.</param> public void AddRange(IEnumerable<XUri> uris, T registrant) { foreach(XUri uri in uris) { Add(uri, registrant); } } /// <summary> /// Get all matching reference objects for uri. /// </summary> /// <param name="uri">Uri to find child uri's for.</param> /// <returns>Collection of reference objects.</returns> public ICollection<T> GetMatches(XUri uri) { return GetMatches(uri, null); } /// <summary> /// Get all matching reference objects for uri that are also in the filter list. /// </summary> /// <param name="uri">Uri to find child uri's for.</param> /// <param name="filter">Collection of matchable reference objects.</param> /// <returns>Filtered collection of reference objects.</returns> public ICollection<T> GetMatches(XUri uri, ICollection<T> filter) { string scheme = _ignoreScheme ? "any" : uri.Scheme; string hostport = uri.HostPort; Entry current = _root; Entry next; List<T> matches = new List<T>(); // check scheme if(!current.Children.TryGetValue(scheme, out next)) { return matches; } current = next; // check hostport if(current.Children.TryGetValue(hostport, out next)) { GetMatches(uri, next, matches, filter); } if(current.Children.TryGetValue("*", out next)) { GetMatches(uri, next, matches, filter); } return matches; } private void GetMatches(XUri uri, Entry current, List<T> matches, ICollection<T> filter) { Entry next; matches.AddRange(FilterMatches(current.Wildcard, filter)); for(int i = 0; i < uri.Segments.Length; i++) { if(!current.Children.TryGetValue(uri.Segments[i], out next)) { break; } current = next; // grab all wildcard matches as we descend matches.AddRange(FilterMatches(current.Wildcard, filter)); // if we're on the last segment, grab the exact matches if(i == uri.Segments.Length - 1) { matches.AddRange(FilterMatches(current.Exact, filter)); } } } private IEnumerable<T> FilterMatches(IEnumerable<T> matches, ICollection<T> filter) { if(filter == null) { return matches; } List<T> filtered = new List<T>(); foreach(T match in matches) { if(filter.Contains(match)) { filtered.Add(match); } } return filtered; } /// <summary> /// Clear the map. /// </summary> public void Clear() { _root.Clear(); } } }
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 Web.API.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Using directives #define USE_TRACING using System; using System.Xml; using System.IO; #endregion ////////////////////////////////////////////////////////////////////// // Contains AtomCategory, an object to represent an atom:category // element. // // atomCategory = element atom:category { // atomCommonAttributes, // attribute term { text }, // attribute scheme { atomUri }?, // attribute label { text }?, // empty // } // ////////////////////////////////////////////////////////////////////// namespace Google.GData.Client { ////////////////////////////////////////////////////////////////////// /// <summary> /// Category elements contain information about a category to which an Atom feed or entry is associated. /// atomCategory = element atom:category { /// atomCommonAttributes, /// attribute term { text }, /// attribute scheme { atomUri }?, /// attribute label { text }?, /// empty /// } /// </summary> ////////////////////////////////////////////////////////////////////// public class AtomCategory : AtomBase, IEquatable<AtomCategory> { /// <summary>holds the term</summary> private string term; /// <summary>holds the scheme as an Uri</summary> private AtomUri scheme; /// <summary>holds the category label</summary> private string label; ////////////////////////////////////////////////////////////////////// /// <summary>empty Category constructor</summary> ////////////////////////////////////////////////////////////////////// public AtomCategory() { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Category constructor</summary> /// <param name="term">the term of the category</param> ////////////////////////////////////////////////////////////////////// public AtomCategory(string term) { this.Term = term; this.Scheme = null; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Category constructor</summary> /// <param name="term">the term of the category</param> /// <param name="scheme">the scheme of the category</param> ////////////////////////////////////////////////////////////////////// public AtomCategory(string term, AtomUri scheme) { this.Term = term; this.Scheme = scheme; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Category constructor</summary> /// <param name="term">the term of the category</param> /// <param name="scheme">the scheme of the category</param> /// <param name="label"> the label for the category</param> ////////////////////////////////////////////////////////////////////// public AtomCategory(string term, AtomUri scheme, string label) { this.Term = term; this.Scheme = scheme; this.label = label; } ///////////////////////////////////////////////////////////////////////////// #region overloaded for persistence ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public override string XmlName { get { return AtomParserNameTable.XmlCategoryElement; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>overridden to save attributes for this(XmlWriter writer)</summary> /// <param name="writer">the xmlwriter to save into </param> ////////////////////////////////////////////////////////////////////// protected override void SaveXmlAttributes(XmlWriter writer) { WriteEncodedAttributeString(writer, AtomParserNameTable.XmlAttributeTerm, this.Term); WriteEncodedAttributeString(writer, AtomParserNameTable.XmlAttributeScheme, this.Scheme); WriteEncodedAttributeString(writer, AtomParserNameTable.XmlAttributeLabel, this.Label); // call base later as base takes care of writing out extension elements that might close the attribute list base.SaveXmlAttributes(writer); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>figures out if this object should be persisted</summary> /// <returns> true, if it's worth saving</returns> ////////////////////////////////////////////////////////////////////// public override bool ShouldBePersisted() { if (base.ShouldBePersisted() == false) { return Utilities.IsPersistable(this.term) || Utilities.IsPersistable(this.label) || Utilities.IsPersistable(this.scheme); } return true; } ///////////////////////////////////////////////////////////////////////////// #endregion ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string Term</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Term { get {return this.term;} set {this.Dirty = true; this.term = value;} } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string Label</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Label { get {return this.label;} set {this.Dirty = true; this.label = value;} } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public Uri Scheme</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public AtomUri Scheme { get {return this.scheme;} set {this.Dirty = true; this.scheme = value;} } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>creates a string rep of a category useful for a query URI</summary> /// <returns>the category as a string for a query </returns> ////////////////////////////////////////////////////////////////////// public string UriString { get { String result = String.Empty; if (this.scheme != null) { result = "{" + this.Scheme + "}"; } if (Utilities.IsPersistable(this.Term)) { result += this.Term; return result; } return null; } } ///////////////////////////////////////////////////////////////////////////// #region added by Noam Gal (ATGardner gmail.com) public bool Equals(AtomCategory other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return Equals(other.term, this.term) && (other.scheme == null || this.scheme == null || Equals(other.scheme, this.scheme)); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != typeof(AtomCategory)) { return false; } return Equals((AtomCategory)obj); } public override int GetHashCode() { unchecked { return ((this.term != null ? this.term.GetHashCode() : 0) * 397) ^ (this.scheme != null ? this.scheme.GetHashCode() : 0); } } #endregion } ///////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////
using System; /// <summary> /// Extends all array base classes with iteration function ForEach /// </summary> /// <remarks> /// This file as intentionally no namespace as the extensions methods will be loaded GLOBALLY /// </remarks> public static class ArrayExtensions { /// <summary> /// Iterate over the elements /// </summary> /// <typeparam name="T">Type of the array items</typeparam> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item</param> public static void ForEach<T>(this T[] array, Action<T> func) where T : class { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i]); } /// <summary> /// Iterate over the elements including the index /// </summary> /// <typeparam name="T">Type of the array items</typeparam> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item with its index</param> public static void ForEach<T>(this T[] array, Action<T, int> func) where T : class { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i], i); } /// <summary> /// Iterate over the elements /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item</param> public static void ForEach(this int[] array, Action<int> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i]); } /// <summary> /// Iterate over the elements including the index /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item with its index</param> public static void ForEach(this int[] array, Action<int, int> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i], i); } /// <summary> /// Iterate over the elements /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item</param> public static void ForEach(this long[] array, Action<long> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i]); } /// <summary> /// Iterate over the elements including the index /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item with its index</param> public static void ForEach(this long[] array, Action<long, int> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i], i); } /// <summary> /// Iterate over the elements /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item</param> public static void ForEach(this float[] array, Action<float> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i]); } /// <summary> /// Iterate over the elements including the index /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item with its index</param> public static void ForEach(this float[] array, Action<float, int> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i], i); } /// <summary> /// Iterate over the elements /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item</param> public static void ForEach(this bool[] array, Action<bool> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i]); } /// <summary> /// Iterate over the elements including the index /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item with its index</param> public static void ForEach(this bool[] array, Action<bool, int> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i], i); } /// <summary> /// Iterate over the elements /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item</param> public static void ForEach(this double[] array, Action<double> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i]); } /// <summary> /// Iterate over the elements including the index /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item with its index</param> public static void ForEach(this double[] array, Action<double, int> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i], i); } /// <summary> /// Iterate over the elements /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item</param> public static void ForEach(this char[] array, Action<char> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i]); } /// <summary> /// Iterate over the elements including the index /// </summary> /// <param name="array">to be iterated</param> /// <param name="func">to be called per item with its index</param> public static void ForEach(this char[] array, Action<char, int> func) { for(int i = 0, imax = array.Length; i < imax; i++) func(array[i], i); } /// <summary> /// Returns a new array by converting each member using the converter /// </summary> /// <returns>The all.</returns> /// <param name="array">Array.</param> /// <param name="func">Func.</param> /// <typeparam name="T">The type of the array</typeparam> /// <typeparam name="TOutput">The converter's result</typeparam> public static TOutput[] ConvertAll<T,TOutput>(this T[] array, Func<T, TOutput> func) where T : class { TOutput[] o = new TOutput[array.Length]; for(int i = 0, imax = array.Length; i < imax; i++) o[i] = func(array[i]); return o; } /// <summary> /// Returns a new array by converting each member using the converter /// </summary> /// <typeparam name="TOutput">of converter's result</typeparam> /// <param name="array">to be converted</param> /// <param name="func">to convert each member</param> /// <returns>a converted array</returns> public static TOutput[] ConvertAll<TOutput>(this int[] array, Func<int, TOutput> func) { TOutput[] o = new TOutput[array.Length]; for(int i = 0, imax = array.Length; i < imax; i++) o[i] = func(array[i]); return o; } /// <summary> /// Returns a new array by converting each member using the converter /// </summary> /// <typeparam name="TOutput">of converter's result</typeparam> /// <param name="array">to be converted</param> /// <param name="func">to convert each member</param> /// <returns>a converted array</returns> public static TOutput[] ConvertAll<TOutput>(this long[] array, Func<long, TOutput> func) { TOutput[] o = new TOutput[array.Length]; for(int i = 0, imax = array.Length; i < imax; i++) o[i] = func(array[i]); return o; } /// <summary> /// Returns a new array by converting each member using the converter /// </summary> /// <typeparam name="TOutput">of converter's result</typeparam> /// <param name="array">to be converted</param> /// <param name="func">to convert each member</param> /// <returns>a converted array</returns> public static TOutput[] ConvertAll<TOutput>(this float[] array, Func<float, TOutput> func) { TOutput[] o = new TOutput[array.Length]; for(int i = 0, imax = array.Length; i < imax; i++) o[i] = func(array[i]); return o; } /// <summary> /// Returns a new array by converting each member using the converter /// </summary> /// <typeparam name="TOutput">of converter's result</typeparam> /// <param name="array">to be converted</param> /// <param name="func">to convert each member</param> /// <returns>a converted array</returns> public static TOutput[] ConvertAll<TOutput>(this double[] array, Func<double, TOutput> func) { TOutput[] o = new TOutput[array.Length]; for(int i = 0, imax = array.Length; i < imax; i++) o[i] = func(array[i]); return o; } /// <summary> /// Returns a new array by converting each member using the converter /// </summary> /// <typeparam name="TOutput">of converter's result</typeparam> /// <param name="array">to be converted</param> /// <param name="func">to convert each member</param> /// <returns>a converted array</returns> public static TOutput[] ConvertAll<TOutput>(this bool[] array, Func<bool, TOutput> func) { TOutput[] o = new TOutput[array.Length]; for(int i = 0, imax = array.Length; i < imax; i++) o[i] = func(array[i]); return o; } /// <summary> /// Returns a new array by converting each member using the converter /// </summary> /// <typeparam name="TOutput">of converter's result</typeparam> /// <param name="array">to be converted</param> /// <param name="func">to convert each member</param> /// <returns>a converted array</returns> public static TOutput[] ConvertAll<TOutput>(this char[] array, Func<char, TOutput> func) { TOutput[] o = new TOutput[array.Length]; for(int i = 0, imax = array.Length; i < imax; i++) o[i] = func(array[i]); return o; } }
#region BSD License /* Copyright (c) 2011, Clarius Consulting 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 Clarius Consulting 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 namespace TracerHub.Diagnostics { using System; using System.Diagnostics; /// <summary> /// Provides usability overloads for tracing to a <see cref="ITracer"/>. /// </summary> /// <nuget id="Tracer.Interfaces" /> static partial class ITracerExtensions { #region Critical overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Critical"/> with the given message; /// </summary> public static void Critical(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Critical, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Critical"/> with the given format string and arguments. /// </summary> public static void Critical(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Critical, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Critical"/> with the given exception and message. /// </summary> public static void Critical(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Critical, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Critical"/> with the given exception, format string and arguments. /// </summary> public static void Critical(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Critical, exception, format, args); } #endregion #region Error overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Error"/> with the given message; /// </summary> public static void Error(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Error, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Error"/> with the given format string and arguments. /// </summary> public static void Error(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Error, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Error"/> with the given exception and message. /// </summary> public static void Error(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Error, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Error"/> with the given exception, format string and arguments. /// </summary> public static void Error(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Error, exception, format, args); } #endregion #region Warn overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Warning"/> with the given message; /// </summary> public static void Warn(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Warning, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Warning"/> with the given format string and arguments. /// </summary> public static void Warn(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Warning, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Warning"/> with the given exception and message. /// </summary> public static void Warn(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Warning, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Warning"/> with the given exception, format string and arguments. /// </summary> public static void Warn(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Warning, exception, format, args); } #endregion #region Info overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Information"/> with the given message; /// </summary> public static void Info(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Information, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Information"/> with the given format string and arguments. /// </summary> public static void Info(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Information, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Information"/> with the given exception and message. /// </summary> public static void Info(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Information, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Information"/> with the given exception, format string and arguments. /// </summary> public static void Info(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Information, exception, format, args); } #endregion #region Verbose overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Verbose"/> with the given message; /// </summary> public static void Verbose(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Verbose, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Verbose"/> with the given format string and arguments. /// </summary> public static void Verbose(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Verbose, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Verbose"/> with the given exception and message. /// </summary> public static void Verbose(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Verbose, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Verbose"/> with the given exception, format string and arguments. /// </summary> public static void Verbose(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Verbose, exception, format, args); } #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.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; #if ENABLE_WINRT using Internal.Runtime.Augments; #endif namespace System.Globalization { internal partial class CultureData { private const uint LOCALE_NOUSEROVERRIDE = 0x80000000; private const uint LOCALE_RETURN_NUMBER = 0x20000000; private const uint LOCALE_SISO3166CTRYNAME = 0x0000005A; private const uint TIME_NOSECONDS = 0x00000002; /// <summary> /// Check with the OS to see if this is a valid culture. /// If so we populate a limited number of fields. If its not valid we return false. /// /// The fields we populate: /// /// sWindowsName -- The name that windows thinks this culture is, ie: /// en-US if you pass in en-US /// de-DE_phoneb if you pass in de-DE_phoneb /// fj-FJ if you pass in fj (neutral, on a pre-Windows 7 machine) /// fj if you pass in fj (neutral, post-Windows 7 machine) /// /// sRealName -- The name you used to construct the culture, in pretty form /// en-US if you pass in EN-us /// en if you pass in en /// de-DE_phoneb if you pass in de-DE_phoneb /// /// sSpecificCulture -- The specific culture for this culture /// en-US for en-US /// en-US for en /// de-DE_phoneb for alt sort /// fj-FJ for fj (neutral) /// /// sName -- The IETF name of this culture (ie: no sort info, could be neutral) /// en-US if you pass in en-US /// en if you pass in en /// de-DE if you pass in de-DE_phoneb /// /// bNeutral -- TRUE if it is a neutral locale /// /// For a neutral we just populate the neutral name, but we leave the windows name pointing to the /// windows locale that's going to provide data for us. /// </summary> private unsafe bool InitCultureData() { const int LOCALE_NAME_MAX_LENGTH = 85; const uint LOCALE_ILANGUAGE = 0x00000001; const uint LOCALE_INEUTRAL = 0x00000071; const uint LOCALE_SNAME = 0x0000005c; int result; string realNameBuffer = _sRealName; char* pBuffer = stackalloc char[LOCALE_NAME_MAX_LENGTH]; result = GetLocaleInfoEx(realNameBuffer, LOCALE_SNAME, pBuffer, LOCALE_NAME_MAX_LENGTH); // Did it fail? if (result == 0) { return false; } // It worked, note that the name is the locale name, so use that (even for neutrals) // We need to clean up our "real" name, which should look like the windows name right now // so overwrite the input with the cleaned up name _sRealName = new String(pBuffer, 0, result - 1); realNameBuffer = _sRealName; // Check for neutrality, don't expect to fail // (buffer has our name in it, so we don't have to do the gc. stuff) result = GetLocaleInfoEx(realNameBuffer, LOCALE_INEUTRAL | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char)); if (result == 0) { return false; } // Remember our neutrality _bNeutral = *((uint*)pBuffer) != 0; // Note: Parents will be set dynamically // Start by assuming the windows name'll be the same as the specific name since windows knows // about specifics on all versions. Only for downlevel Neutral locales does this have to change. _sWindowsName = realNameBuffer; // Neutrals and non-neutrals are slightly different if (_bNeutral) { // Neutral Locale // IETF name looks like neutral name _sName = realNameBuffer; // Specific locale name is whatever ResolveLocaleName (win7+) returns. // (Buffer has our name in it, and we can recycle that because windows resolves it before writing to the buffer) result = Interop.Kernel32.ResolveLocaleName(realNameBuffer, pBuffer, LOCALE_NAME_MAX_LENGTH); // 0 is failure, 1 is invariant (""), which we expect if (result < 1) { return false; } // We found a locale name, so use it. // In vista this should look like a sort name (de-DE_phoneb) or a specific culture (en-US) and be in the "pretty" form _sSpecificCulture = new String(pBuffer, 0, result - 1); } else { // Specific Locale // Specific culture's the same as the locale name since we know its not neutral // On mac we'll use this as well, even for neutrals. There's no obvious specific // culture to use and this isn't exposed, but behaviorally this is correct on mac. // Note that specifics include the sort name (de-DE_phoneb) _sSpecificCulture = realNameBuffer; _sName = realNameBuffer; // We need the IETF name (sname) // If we aren't an alt sort locale then this is the same as the windows name. // If we are an alt sort locale then this is the same as the part before the _ in the windows name // This is for like de-DE_phoneb and es-ES_tradnl that hsouldn't have the _ part result = GetLocaleInfoEx(realNameBuffer, LOCALE_ILANGUAGE | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char)); if (result == 0) { return false; } _iLanguage = *((int*)pBuffer); if (!IsCustomCultureId(_iLanguage)) { // not custom locale int index = realNameBuffer.IndexOf('_'); if (index > 0 && index < realNameBuffer.Length) { _sName = realNameBuffer.Substring(0, index); } } } // It succeeded. return true; } // Wrappers around the GetLocaleInfoEx APIs which handle marshalling the returned // data as either and Int or String. internal static unsafe String GetLocaleInfoEx(String localeName, uint field) { // REVIEW: Determine the maximum size for the buffer const int BUFFER_SIZE = 530; char* pBuffer = stackalloc char[BUFFER_SIZE]; int resultCode = GetLocaleInfoEx(localeName, field, pBuffer, BUFFER_SIZE); if (resultCode > 0) { return new String(pBuffer); } return null; } internal static unsafe int GetLocaleInfoExInt(String localeName, uint field) { const uint LOCALE_RETURN_NUMBER = 0x20000000; field |= LOCALE_RETURN_NUMBER; int value = 0; GetLocaleInfoEx(localeName, field, (char*)&value, sizeof(int)); return value; } internal static unsafe int GetLocaleInfoEx(string lpLocaleName, uint lcType, void* lpLCData, int cchData) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, lpLCData, cchData); } private string GetLocaleInfo(LocaleStringData type) { Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already"); return GetLocaleInfo(_sWindowsName, type); } // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the // "windows" name, which can be specific for downlevel (< windows 7) os's. private string GetLocaleInfo(string localeName, LocaleStringData type) { uint lctype = (uint)type; return GetLocaleInfoFromLCType(localeName, lctype, UseUserOverride); } private int GetLocaleInfo(LocaleNumberData type) { uint lctype = (uint)type; // Fix lctype if we don't want overrides if (!UseUserOverride) { lctype |= LOCALE_NOUSEROVERRIDE; } // Ask OS for data, note that we presume it returns success, so we have to know that // sWindowsName is valid before calling. Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); return GetLocaleInfoExInt(_sWindowsName, lctype); } private int[] GetLocaleInfo(LocaleGroupingData type) { return ConvertWin32GroupString(GetLocaleInfoFromLCType(_sWindowsName, (uint)type, UseUserOverride)); } private string GetTimeFormatString() { const uint LOCALE_STIMEFORMAT = 0x00001003; return ReescapeWin32String(GetLocaleInfoFromLCType(_sWindowsName, LOCALE_STIMEFORMAT, UseUserOverride)); } private int GetFirstDayOfWeek() { Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C; int result = GetLocaleInfoExInt(_sWindowsName, LOCALE_IFIRSTDAYOFWEEK | (!UseUserOverride ? LOCALE_NOUSEROVERRIDE : 0)); // Win32 and .NET disagree on the numbering for days of the week, so we have to convert. return ConvertFirstDayOfWeekMonToSun(result); } private String[] GetTimeFormats() { // Note that this gets overrides for us all the time Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride)); return result; } private String[] GetShortTimeFormats() { // Note that this gets overrides for us all the time Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, TIME_NOSECONDS, UseUserOverride)); return result; } // Enumerate all system cultures and then try to find out which culture has // region name match the requested region name private static CultureData GetCultureDataFromRegionName(String regionName) { Debug.Assert(regionName != null); const uint LOCALE_SUPPLEMENTAL = 0x00000002; const uint LOCALE_SPECIFICDATA = 0x00000020; EnumLocaleData context = new EnumLocaleData(); context.cultureName = null; context.regionName = regionName; unsafe { Interop.Kernel32.EnumSystemLocalesEx(EnumSystemLocalesProc, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, Unsafe.AsPointer(ref context), IntPtr.Zero); } if (context.cultureName != null) { // we got a matched culture return GetCultureData(context.cultureName, true); } return null; } private string GetLanguageDisplayName(string cultureName) { #if ENABLE_WINRT return WinRTInterop.Callbacks.GetLanguageDisplayName(cultureName); #else // Usually the UI culture shouldn't be different than what we got from WinRT except // if DefaultThreadCurrentUICulture was set CultureInfo ci; if (CultureInfo.DefaultThreadCurrentUICulture != null && ((ci = GetUserDefaultCulture()) != null) && !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name)) { return SNATIVEDISPLAYNAME; } else { return GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName); } #endif // ENABLE_WINRT } private string GetRegionDisplayName(string isoCountryCode) { #if ENABLE_WINRT return WinRTInterop.Callbacks.GetRegionDisplayName(isoCountryCode); #else // Usually the UI culture shouldn't be different than what we got from WinRT except // if DefaultThreadCurrentUICulture was set CultureInfo ci; if (CultureInfo.DefaultThreadCurrentUICulture != null && ((ci = GetUserDefaultCulture()) != null) && !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name)) { return SNATIVECOUNTRY; } else { return GetLocaleInfo(LocaleStringData.LocalizedCountryName); } #endif // ENABLE_WINRT } private static CultureInfo GetUserDefaultCulture() { #if ENABLE_WINRT return (CultureInfo)WinRTInterop.Callbacks.GetUserDefaultCulture(); #else return CultureInfo.GetUserDefaultCulture(); #endif // ENABLE_WINRT } // PAL methods end here. private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride) { Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null"); // Fix lctype if we don't want overrides if (!useUserOveride) { lctype |= LOCALE_NOUSEROVERRIDE; } // Ask OS for data string result = GetLocaleInfoEx(localeName, lctype); if (result == null) { // Failed, just use empty string result = String.Empty; } return result; } //////////////////////////////////////////////////////////////////////////// // // Reescape a Win32 style quote string as a NLS+ style quoted string // // This is also the escaping style used by custom culture data files // // NLS+ uses \ to escape the next character, whether in a quoted string or // not, so we always have to change \ to \\. // // NLS+ uses \' to escape a quote inside a quoted string so we have to change // '' to \' (if inside a quoted string) // // We don't build the stringbuilder unless we find something to change //////////////////////////////////////////////////////////////////////////// internal static String ReescapeWin32String(String str) { // If we don't have data, then don't try anything if (str == null) return null; StringBuilder result = null; bool inQuote = false; for (int i = 0; i < str.Length; i++) { // Look for quote if (str[i] == '\'') { // Already in quote? if (inQuote) { // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote? if (i + 1 < str.Length && str[i + 1] == '\'') { // Found another ', so we have ''. Need to add \' instead. // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append a \' and keep going (so we don't turn off quote mode) result.Append("\\'"); i++; continue; } // Turning off quote mode, fall through to add it inQuote = false; } else { // Found beginning quote, fall through to add it inQuote = true; } } // Is there a single \ character? else if (str[i] == '\\') { // Found a \, need to change it to \\ // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append our \\ to the string & continue result.Append("\\\\"); continue; } // If we have a builder we need to add our character if (result != null) result.Append(str[i]); } // Unchanged string? , just return input string if (result == null) return str; // String changed, need to use the builder return result.ToString(); } internal static String[] ReescapeWin32Strings(String[] array) { if (array != null) { for (int i = 0; i < array.Length; i++) { array[i] = ReescapeWin32String(array[i]); } } return array; } // If we get a group from windows, then its in 3;0 format with the 0 backwards // of how NLS+ uses it (ie: if the string has a 0, then the int[] shouldn't and vice versa) // EXCEPT in the case where the list only contains 0 in which NLS and NLS+ have the same meaning. private static int[] ConvertWin32GroupString(String win32Str) { // None of these cases make any sense if (win32Str == null || win32Str.Length == 0) { return (new int[] { 3 }); } if (win32Str[0] == '0') { return (new int[] { 0 }); } // Since its in n;n;n;n;n format, we can always get the length quickly int[] values; if (win32Str[win32Str.Length - 1] == '0') { // Trailing 0 gets dropped. 1;0 -> 1 values = new int[(win32Str.Length / 2)]; } else { // Need extra space for trailing zero 1 -> 1;0 values = new int[(win32Str.Length / 2) + 2]; values[values.Length - 1] = 0; } int i; int j; for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++) { // Note that this # shouldn't ever be zero, 'cause 0 is only at end // But we'll test because its registry that could be anything if (win32Str[i] < '1' || win32Str[i] > '9') return new int[] { 3 }; values[j] = (int)(win32Str[i] - '0'); } return (values); } private static int ConvertFirstDayOfWeekMonToSun(int iTemp) { // Convert Mon-Sun to Sun-Sat format iTemp++; if (iTemp > 6) { // Wrap Sunday and convert invalid data to Sunday iTemp = 0; } return iTemp; } // Context for EnumCalendarInfoExEx callback. private class EnumLocaleData { public string regionName; public string cultureName; } // EnumSystemLocaleEx callback. // [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static unsafe Interop.BOOL EnumSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { ref EnumLocaleData context = ref Unsafe.As<byte, EnumLocaleData>(ref *(byte*)contextHandle); try { string cultureName = new string(lpLocaleString); string regionName = GetLocaleInfoEx(cultureName, LOCALE_SISO3166CTRYNAME); if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase)) { context.cultureName = cultureName; return Interop.BOOL.FALSE; // we found a match, then stop the enumeration } return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } // [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static unsafe Interop.BOOL EnumAllSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)contextHandle); try { context.strings.Add(new string(lpLocaleString)); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } // Context for EnumTimeFormatsEx callback. private struct EnumData { public LowLevelList<string> strings; } // EnumTimeFormatsEx callback itself. // [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static unsafe Interop.BOOL EnumTimeCallback(char* lpTimeFormatString, void* lParam) { ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam); try { context.strings.Add(new string(lpTimeFormatString)); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } private static unsafe String[] nativeEnumTimeFormats(String localeName, uint dwFlags, bool useUserOverride) { const uint LOCALE_SSHORTTIME = 0x00000079; const uint LOCALE_STIMEFORMAT = 0x00001003; EnumData data = new EnumData(); data.strings = new LowLevelList<string>(); // Now call the enumeration API. Work is done by our callback function Interop.Kernel32.EnumTimeFormatsEx(EnumTimeCallback, localeName, (uint)dwFlags, Unsafe.AsPointer(ref data)); if (data.strings.Count > 0) { // Now we need to allocate our stringarray and populate it string[] results = data.strings.ToArray(); if (!useUserOverride && data.strings.Count > 1) { // Since there is no "NoUserOverride" aware EnumTimeFormatsEx, we always get an override // The override is the first entry if it is overriden. // We can check if we have overrides by checking the GetLocaleInfo with no override // If we do have an override, we don't know if it is a user defined override or if the // user has just selected one of the predefined formats so we can't just remove it // but we can move it down. uint lcType = (dwFlags == TIME_NOSECONDS) ? LOCALE_SSHORTTIME : LOCALE_STIMEFORMAT; string timeFormatNoUserOverride = GetLocaleInfoFromLCType(localeName, lcType, useUserOverride); if (timeFormatNoUserOverride != "") { string firstTimeFormat = results[0]; if (timeFormatNoUserOverride != firstTimeFormat) { results[0] = results[1]; results[1] = firstTimeFormat; } } } return results; } return null; } private static int LocaleNameToLCID(string cultureName) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.Kernel32.LocaleNameToLCID(cultureName, Interop.Kernel32.LOCALE_ALLOW_NEUTRAL_NAMES); } private static unsafe string LCIDToLocaleName(int culture) { Debug.Assert(!GlobalizationMode.Invariant); char *pBuffer = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH + 1]; // +1 for the null termination int length = Interop.Kernel32.LCIDToLocaleName(culture, pBuffer, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH + 1, Interop.Kernel32.LOCALE_ALLOW_NEUTRAL_NAMES); if (length > 0) { return new String(pBuffer); } return null; } private int GetAnsiCodePage(string cultureName) { return GetLocaleInfo(LocaleNumberData.AnsiCodePage); } private int GetOemCodePage(string cultureName) { return GetLocaleInfo(LocaleNumberData.OemCodePage); } private int GetMacCodePage(string cultureName) { return GetLocaleInfo(LocaleNumberData.MacCodePage); } private int GetEbcdicCodePage(string cultureName) { return GetLocaleInfo(LocaleNumberData.EbcdicCodePage); } private int GetGeoId(string cultureName) { return GetLocaleInfo(LocaleNumberData.GeoId); } private int GetDigitSubstitution(string cultureName) { return GetLocaleInfo(LocaleNumberData.DigitSubstitution); } private string GetThreeLetterWindowsLanguageName(string cultureName) { return GetLocaleInfo(cultureName, LocaleStringData.AbbreviatedWindowsLanguageName); } private static CultureInfo[] EnumCultures(CultureTypes types) { Debug.Assert(!GlobalizationMode.Invariant); uint flags = 0; #pragma warning disable 618 if ((types & (CultureTypes.FrameworkCultures | CultureTypes.InstalledWin32Cultures | CultureTypes.ReplacementCultures)) != 0) { flags |= Interop.Kernel32.LOCALE_NEUTRALDATA | Interop.Kernel32.LOCALE_SPECIFICDATA; } #pragma warning restore 618 if ((types & CultureTypes.NeutralCultures) != 0) { flags |= Interop.Kernel32.LOCALE_NEUTRALDATA; } if ((types & CultureTypes.SpecificCultures) != 0) { flags |= Interop.Kernel32.LOCALE_SPECIFICDATA; } if ((types & CultureTypes.UserCustomCulture) != 0) { flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL; } if ((types & CultureTypes.ReplacementCultures) != 0) { flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL; } EnumData context = new EnumData(); context.strings = new LowLevelList<string>(); unsafe { Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, flags, Unsafe.AsPointer(ref context), IntPtr.Zero); } CultureInfo[] cultures = new CultureInfo[context.strings.Count]; for (int i = 0; i < cultures.Length; i++) { cultures[i] = new CultureInfo(context.strings[i]); } return cultures; } private string GetConsoleFallbackName(string cultureName) { return GetLocaleInfo(cultureName, LocaleStringData.ConsoleFallbackName); } internal bool IsFramework { get { return false; } } internal bool IsWin32Installed { get { return true; } } internal bool IsReplacementCulture { get { EnumData context = new EnumData(); context.strings = new LowLevelList<string>(); unsafe { Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, Interop.Kernel32.LOCALE_REPLACEMENT, Unsafe.AsPointer(ref context), IntPtr.Zero); } for (int i = 0; i < context.strings.Count; i++) { if (String.Compare(context.strings[i], _sWindowsName, StringComparison.OrdinalIgnoreCase) == 0) return true; } return false; } } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Security; namespace System.IO { public partial class FileStream : Stream { private const FileShare DefaultShare = FileShare.Read; private const bool DefaultIsAsync = false; internal const int DefaultBufferSize = 4096; private byte[] _buffer; private int _bufferLength; private readonly SafeFileHandle _fileHandle; /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>The path to the opened file.</summary> private readonly string _path; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary> /// Whether asynchronous read/write/flush operations should be performed using async I/O. /// On Windows FileOptions.Asynchronous controls how the file handle is configured, /// and then as a result how operations are issued against that file handle. On Unix, /// there isn't any distinction around how file descriptors are created for async vs /// sync, but we still differentiate how the operations are issued in order to provide /// similar behavioral semantics and performance characteristics as on Windows. On /// Windows, if non-async, async read/write requests just delegate to the base stream, /// and no attempt is made to synchronize between sync and async operations on the stream; /// if async, then async read/write requests are implemented specially, and sync read/write /// requests are coordinated with async ones by implementing the sync ones over the async /// ones. On Unix, we do something similar. If non-async, async read/write requests just /// delegate to the base stream, and no attempt is made to synchronize. If async, we use /// a semaphore to coordinate both sync and async operations. /// </summary> private readonly bool _useAsyncIO; /// <summary>cached task for read ops that complete synchronously</summary> private Task<int> _lastSynchronouslyCompletedTask = null; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file's actual position, /// and should only ever be out of sync if another stream with access to this same file manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access) : this(handle, access, true, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle) : this(handle, access, ownsHandle, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize) : this(handle, access, ownsHandle, bufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync) { SafeFileHandle safeHandle = new SafeFileHandle(handle, ownsHandle: ownsHandle); try { ValidateAndInitFromHandle(safeHandle, access, bufferSize, isAsync); } catch { // We don't want to take ownership of closing passed in handles // *unless* the constructor completes successfully. GC.SuppressFinalize(safeHandle); // This would also prevent Close from being called, but is unnecessary // as we've removed the object from the finalizer queue. // // safeHandle.SetHandleAsInvalid(); throw; } // Note: Cleaner to set the following fields in ValidateAndInitFromHandle, // but we can't as they're readonly. _access = access; _useAsyncIO = isAsync; // As the handle was passed in, we must set the handle field at the very end to // avoid the finalizer closing the handle when we throw errors. _fileHandle = safeHandle; } public FileStream(SafeFileHandle handle, FileAccess access) : this(handle, access, DefaultBufferSize) { } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) : this(handle, access, bufferSize, GetDefaultIsAsync(handle)) { } private void ValidateAndInitFromHandle(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle)); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (handle.IsAsync.HasValue && isAsync != handle.IsAsync.Value) throw new ArgumentException(SR.Arg_HandleNotAsync, nameof(handle)); _exposedHandle = true; _bufferLength = bufferSize; InitFromHandle(handle, access, isAsync); } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { ValidateAndInitFromHandle(handle, access, bufferSize, isAsync); // Note: Cleaner to set the following fields in ValidateAndInitFromHandle, // but we can't as they're readonly. _access = access; _useAsyncIO = isAsync; // As the handle was passed in, we must set the handle field at the very end to // avoid the finalizer closing the handle when we throw errors. _fileHandle = handle; } public FileStream(string path, FileMode mode) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access) : this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) : this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; string badArg = null; if (mode < FileMode.CreateNew || mode > FileMode.Append) badArg = nameof(mode); else if (access < FileAccess.Read || access > FileAccess.ReadWrite) badArg = nameof(access); else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete)) badArg = nameof(share); if (badArg != null) throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum); // NOTE: any change to FileOptions enum needs to be matched here in the error validation if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0) throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); // Write access validation if ((access & FileAccess.Write) == 0) { if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append) { // No write access, mode and access disagree but flag access since mode comes first throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access)); } } if ((access & FileAccess.Read) != 0 && mode == FileMode.Append) throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access)); string fullPath = Path.GetFullPath(path); _path = fullPath; _access = access; _bufferLength = bufferSize; if ((options & FileOptions.Asynchronous) != 0) _useAsyncIO = true; _fileHandle = OpenHandle(mode, share, options); try { Init(mode, share); } catch { // If anything goes wrong while setting up the stream, make sure we deterministically dispose // of the opened handle. _fileHandle.Dispose(); _fileHandle = null; throw; } } private static bool GetDefaultIsAsync(SafeFileHandle handle) { // This will eventually get more complicated as we can actually check the underlying handle type on Windows return handle.IsAsync.HasValue ? handle.IsAsync.Value : false; } [Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual IntPtr Handle { get { return SafeFileHandle.DangerousGetHandle(); } } public virtual void Lock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } LockInternal(position, length); } public virtual void Unlock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } UnlockInternal(position, length); } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(FileStream)) return base.FlushAsync(cancellationToken); return FlushAsyncInternal(cancellationToken); } public override int Read(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); return _useAsyncIO ? ReadAsyncTask(array, offset, count, CancellationToken.None).GetAwaiter().GetResult() : ReadSpan(new Span<byte>(array, offset, count)); } public override int Read(Span<byte> buffer) { if (GetType() == typeof(FileStream) && !_useAsyncIO) { if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } return ReadSpan(buffer); } else { // This type is derived from FileStream and/or the stream is in async mode. If this is a // derived type, it may have overridden Read(byte[], int, int) prior to this Read(Span<byte>) // overload being introduced. In that case, this Read(Span<byte>) overload should use the behavior // of Read(byte[],int,int) overload. Or if the stream is in async mode, we can't call the // synchronous ReadSpan, so we similarly call the base Read, which will turn delegate to // Read(byte[],int,int), which will do the right thing if we're in async mode. return base.Read(buffer); } } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/ReadAsync) when we are not sure. // Similarly, if we weren't opened for asynchronous I/O, call to the base implementation so that // Read is invoked asynchronously. if (GetType() != typeof(FileStream) || !_useAsyncIO) return base.ReadAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return ReadAsyncTask(buffer, offset, count, cancellationToken); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { if (!_useAsyncIO || GetType() != typeof(FileStream)) { // If we're not using async I/O, delegate to the base, which will queue a call to Read. // Or if this isn't a concrete FileStream, a derived type may have overridden ReadAsync(byte[],...), // which was introduced first, so delegate to the base which will delegate to that. return base.ReadAsync(buffer, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)); } if (IsClosed) { throw Error.GetFileNotOpen(); } Task<int> t = ReadAsyncInternal(buffer, cancellationToken, out int synchronousResult); return t != null ? new ValueTask<int>(t) : new ValueTask<int>(synchronousResult); } private Task<int> ReadAsyncTask(byte[] array, int offset, int count, CancellationToken cancellationToken) { Task<int> t = ReadAsyncInternal(new Memory<byte>(array, offset, count), cancellationToken, out int synchronousResult); if (t == null) { t = _lastSynchronouslyCompletedTask; Debug.Assert(t == null || t.IsCompletedSuccessfully, "Cached task should have completed successfully"); if (t == null || t.Result != synchronousResult) { _lastSynchronouslyCompletedTask = t = Task.FromResult(synchronousResult); } } return t; } public override void Write(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); if (_useAsyncIO) { WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, count), CancellationToken.None).GetAwaiter().GetResult(); } else { WriteSpan(new ReadOnlySpan<byte>(array, offset, count)); } } public override void Write(ReadOnlySpan<byte> buffer) { if (GetType() == typeof(FileStream) && !_useAsyncIO) { if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } WriteSpan(buffer); } else { // This type is derived from FileStream and/or the stream is in async mode. If this is a // derived type, it may have overridden Write(byte[], int, int) prior to this Write(ReadOnlySpan<byte>) // overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload should use the behavior // of Write(byte[],int,int) overload. Or if the stream is in async mode, we can't call the // synchronous WriteSpan, so we similarly call the base Write, which will turn delegate to // Write(byte[],int,int), which will do the right thing if we're in async mode. base.Write(buffer); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() or WriteAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write/WriteAsync) when we are not sure. if (!_useAsyncIO || GetType() != typeof(FileStream)) return base.WriteAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return WriteAsyncInternal(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { if (!_useAsyncIO || GetType() != typeof(FileStream)) { // If we're not using async I/O, delegate to the base, which will queue a call to Write. // Or if this isn't a concrete FileStream, a derived type may have overridden WriteAsync(byte[],...), // which was introduced first, so delegate to the base which will delegate to that. return base.WriteAsync(buffer, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return new ValueTask(Task.FromCanceled<int>(cancellationToken)); } if (IsClosed) { throw Error.GetFileNotOpen(); } return WriteAsyncInternal(buffer, cancellationToken); } /// <summary> /// Clears buffers for this stream and causes any buffered data to be written to the file. /// </summary> public override void Flush() { // Make sure that we call through the public virtual API Flush(flushToDisk: false); } /// <summary> /// Clears buffers for this stream, and if <param name="flushToDisk"/> is true, /// causes any buffered data to be written to the file. /// </summary> public virtual void Flush(bool flushToDisk) { if (IsClosed) throw Error.GetFileNotOpen(); FlushInternalBuffer(); if (flushToDisk && CanWrite) { FlushOSBuffer(); } } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead { get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite { get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; } } /// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary> /// <param name="array">The buffer to read from or write to.</param> /// <param name="offset">The zero-based offset into the array.</param> /// <param name="count">The maximum number of bytes to read or write.</param> private void ValidateReadWriteArgs(byte[] array, int offset, int count) { if (array == null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); if (!CanWrite) throw Error.GetWriteNotSupported(); SetLengthInternal(value); } public virtual SafeFileHandle SafeFileHandle { get { Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets the path that was passed to the constructor.</summary> public virtual string Name { get { return _path ?? SR.IO_UnknownFileName; } } /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public virtual bool IsAsync { get { return _useAsyncIO; } } /// <summary>Gets the length of the stream in bytes.</summary> public override long Length { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); return GetLengthInternal(); } } /// <summary> /// Verify that the actual position of the OS's handle equals what we expect it to. /// This will fail if someone else moved the UnixFileStream's handle or if /// our position updating code is incorrect. /// </summary> private void VerifyOSHandlePosition() { bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it #if DEBUG verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be #endif if (verifyPosition && CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(_fileHandle, 0, SeekOrigin.Current); if (oldPos != curPos) { // For reads, this is non-fatal but we still could have returned corrupted // data in some cases, so discard the internal buffer. For writes, // this is a problem; discard the buffer and error out. _readPos = _readLength = 0; if (_writePos > 0) { _writePos = 0; throw new IOException(SR.IO_FileStreamHandlePosition); } } } } /// <summary>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void AssertBufferInvariants() { // Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength); // Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength Debug.Assert(0 <= _writePos && _writePos <= _bufferLength); // Read buffering and write buffering can't both be active Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0); } /// <summary>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (_readLength == 0 && !CanRead) throw Error.GetReadNotSupported(); AssertBufferInvariants(); } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); AssertBufferInvariants(); VerifyOSHandlePosition(); // We may have read data into our buffer from the handle, such that the handle position // is artificially further along than the consumer's view of the stream's position. // Thus, when reading, our position is really starting from the handle position negatively // offset by the number of bytes in the buffer and positively offset by the number of // bytes into that buffer we've read. When writing, both the read length and position // must be zero, and our position is just the handle position offset positive by how many // bytes we've written into the buffer. return (_filePosition - _readLength) + _readPos + _writePos; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Seek(value, SeekOrigin.Begin); } } internal virtual bool IsClosed => _fileHandle.IsClosed; private static bool IsIoRelatedException(Exception e) => // These all derive from IOException // DirectoryNotFoundException // DriveNotFoundException // EndOfStreamException // FileLoadException // FileNotFoundException // PathTooLongException // PipeException e is IOException || // Note that SecurityException is only thrown on runtimes that support CAS // e is SecurityException || e is UnauthorizedAccessException || e is NotSupportedException || (e is ArgumentException && !(e is ArgumentNullException)); /// <summary> /// Gets the array used for buffering reading and writing. /// If the array hasn't been allocated, this will lazily allocate it. /// </summary> /// <returns>The buffer.</returns> private byte[] GetBuffer() { Debug.Assert(_buffer == null || _buffer.Length == _bufferLength); if (_buffer == null) { _buffer = new byte[_bufferLength]; OnBufferAllocated(); } return _buffer; } partial void OnBufferAllocated(); /// <summary> /// Flushes the internal read/write buffer for this stream. If write data has been buffered, /// that data is written out to the underlying file. Or if data has been buffered for /// reading from the stream, the data is dumped and our position in the underlying file /// is rewound as necessary. This does not flush the OS buffer. /// </summary> private void FlushInternalBuffer() { AssertBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && CanSeek) { FlushReadBuffer(); } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { // Reading is done by blocks from the file, but someone could read // 1 byte from the buffer then write. At that point, the OS's file // pointer is out of sync with the stream's position. All write // functions should call this function to preserve the position in the file. AssertBufferInvariants(); Debug.Assert(_writePos == 0, "FileStream: Write buffer must be empty in FlushReadBuffer!"); int rewind = _readPos - _readLength; if (rewind != 0) { Debug.Assert(CanSeek, "FileStream will lose buffered read data now."); SeekCore(_fileHandle, rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } /// <summary> /// Reads a byte from the file stream. Returns the byte cast to an int /// or -1 if reading from the end of the stream. /// </summary> public override int ReadByte() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { FlushWriteBuffer(); _readLength = FillReadBufferForReadByte(); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } /// <summary> /// Writes a byte to the current position in the stream and advances the position /// within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) { PrepareForWriting(); // Flush the write buffer if it's full if (_writePos == _bufferLength) FlushWriteBufferForWriteByte(); // We now have space in the buffer. Store the byte. GetBuffer()[_writePos++] = value; } /// <summary> /// Validates that we're ready to write to the stream, /// including flushing a read buffer if necessary. /// </summary> private void PrepareForWriting() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); // Make sure we're good to write. We only need to do this if there's nothing already // in our write buffer, since if there is something in the buffer, we've already done // this checking and flushing. if (_writePos == 0) { if (!CanWrite) throw Error.GetWriteNotSupported(); FlushReadBuffer(); Debug.Assert(_bufferLength > 0, "_bufferSize > 0"); } } ~FileStream() { // Preserved for compatibility since FileStream has defined a // finalizer in past releases and derived classes may depend // on Dispose(false) call. Dispose(false); } public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback callback, object state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (!IsAsync) return base.BeginRead(array, offset, numBytes, callback, state); else return TaskToApm.Begin(ReadAsyncTask(array, offset, numBytes, CancellationToken.None), callback, state); } public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback callback, object state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (!IsAsync) return base.BeginWrite(array, offset, numBytes, callback, state); else return TaskToApm.Begin(WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, numBytes), CancellationToken.None).AsTask(), callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) return base.EndRead(asyncResult); else return TaskToApm.End<int>(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) base.EndWrite(asyncResult); else TaskToApm.End(asyncResult); } } }
using System; using System.Text; using System.Reflection; using System.Collections; using Zeus.UserInterface; using Zeus.Configuration; namespace Zeus { #region ZeusContext /// <summary> /// The ZeusGuiContext object contains the data that goes through the interface segment of the template. /// </summary> public class ZeusTemplateContext : IZeusContext { protected IZeusIntrinsicObject[] _intrinsicObjects; protected IZeusInput _input; protected IZeusOutput _output; protected IGuiController _gui; protected Stack _templateStack; protected Hashtable _objects; protected ILog _log; public string Describe(string prefix, object o) { StringBuilder sb = new StringBuilder(); Describe(sb, prefix, o.GetType(), 0); return sb.ToString(); } private void Describe(StringBuilder sb, string prefix, Type t, int depth) { if (depth > 2) return; ArrayList assemblyList = new ArrayList(); assemblyList.Add("PluginInterfaces"); assemblyList.Add("Zeus"); assemblyList.Add("MyMeta"); assemblyList.Add("MyGenUtility"); assemblyList.Add("MyGeneration"); //Type t = obj.GetType(); PropertyInfo[] props = t.GetProperties(); MethodInfo[] methods = t.GetMethods(); FieldInfo[] fields = t.GetFields(); foreach (PropertyInfo pi in props) { bool isCool = false; if (pi.CanRead && pi.GetGetMethod().IsPublic) isCool = true; if (pi.CanWrite && pi.GetSetMethod().IsPublic) isCool = true; if (isCool) { sb.Append(prefix).Append('.').AppendLine(pi.Name); if (pi.CanRead) { Type chtype = pi.PropertyType; if (assemblyList.Contains(chtype.Assembly.GetName().Name)) { Describe(sb, prefix + "." + pi.Name, chtype, depth+1); } } } } foreach (MethodInfo mi in methods) { if (mi.IsPublic) { if (!mi.Name.StartsWith("get_") && !mi.Name.StartsWith("set_")) { sb.Append(prefix).Append('.').AppendLine(mi.Name); if ((mi.ReturnType != null) && (mi.GetParameters().Length == 0)) { Type chtype = mi.ReturnType; if (assemblyList.Contains(chtype.Assembly.GetName().Name)) { Describe(sb, prefix + "." + mi.Name + "()", chtype, depth + 1); } } } } } foreach (FieldInfo fi in fields) { if (fi.IsPublic) { sb.Append(prefix).Append('.').AppendLine(fi.Name); } } } /// <summary> /// Creates a new ZeusGuiContext object. /// </summary> public ZeusTemplateContext() { this._input = new ZeusInput(); this._output = new ZeusOutput(); this._gui = new GuiController(this); this._objects = new Hashtable(); this._objects["ui"] = _gui; } /// <summary> /// Creates a new ZeusGuiContext object and defaults it's properties to the passed in objects. /// </summary> /// <param name="input">The ZeusInput object to pass into the template inteface segment.</param> /// <param name="gui">The GuiController object to use in the template inteface segment.</param> /// <param name="objects">A HashTable containing any other objects that need to be included in the template context.</param> public ZeusTemplateContext(IZeusInput input, /*IGuiController gui,*/ Hashtable objects) { this._input = input; //this._gui = gui; this._gui = new GuiController(this); this._objects = objects; this._output = new ZeusOutput(); this._objects["ui"] = _gui; } /// <summary> /// The ZeusInput object is a collection containing all of the input variables to pass into the template body segment. /// </summary> public IZeusInput Input { get { return _input; } } /// <summary> /// The ZeusOutput object is the output buffer in which the template output is written. /// </summary> public IZeusOutput Output { get { return _output; } } /// <summary> /// The GuiController object describes the graphical user interface that attains input for the template body segment. /// </summary> public IZeusGuiControl Gui { get { return _gui; } } /// <summary> /// The GuiController object describes the graphical user interface that attains input for the template body segment. /// </summary> public IZeusIntrinsicObject[] IntrinsicObjects { get { return _intrinsicObjects; } } /// <summary> /// Depricated! Use: Execute(string path, bool copyContext) /// </summary> /// <param name="path"></param> public void ExecuteTemplate(string path) { ZeusTemplate template = new ZeusTemplate( FileTools.MakeAbsolute(path, this.ExecutingTemplate.FilePath) ); template.Execute(this, 0, true); } public void Execute(string path, bool copyContext) { ZeusTemplate template = new ZeusTemplate( FileTools.MakeAbsolute(path, this.ExecutingTemplate.FilePath) ); if (copyContext) { template.Execute(this.Copy(), 0, true); } else { template.Execute(this, 0, true); } } /// <summary> /// A HashTable containing any other objects that need to be included in the template context. /// </summary> public Hashtable Objects { get { return _objects; } } public void SetIntrinsicObjects(IZeusIntrinsicObject[] intrinsicObjects) { this._intrinsicObjects = intrinsicObjects; } public void SetIntrinsicObjects(ArrayList intrinsicObjects) { this.SetIntrinsicObjects( intrinsicObjects.ToArray(typeof(IZeusIntrinsicObject)) as IZeusIntrinsicObject[] ); } public IZeusTemplateStub ExecutingTemplate { get { return this.TemplateStack.Peek() as IZeusTemplateStub; } } public int ExecutionDepth { get { return this.TemplateStack.Count; } } public ILog Log { get { if (_log == null) { _log = new ZeusSimpleLog(); } return _log; } set { if (value != null) { _log = value; } } } public Stack TemplateStack { get { if (this._templateStack == null) { this._templateStack = new Stack(); } return _templateStack; } } /// <summary> /// Creates a copy of the ZeusContext with a new output object; /// </summary> /// <returns></returns> public IZeusContext Copy() { ZeusTemplateContext context = Activator.CreateInstance( this.GetType() ) as ZeusTemplateContext; context._input = this._input; context._output = new ZeusOutput(); context._objects = this._objects; context._log = this._log; context._gui = this._gui; context._intrinsicObjects = this._intrinsicObjects; context._templateStack = this._templateStack; return context; } } #endregion #region ZeusGuiContext /// <summary> /// The ZeusGuiContext object is just here for legacy support. /// </summary> public class ZeusGuiContext : ZeusTemplateContext { public ZeusGuiContext() : base() {} public ZeusGuiContext(IZeusInput input, /*IGuiController gui,*/ Hashtable objects) : base(input, /*gui,*/ objects) {} } #endregion #region ZeusTemplateContext /// <summary> /// The ZeusTemplateContext object is just here for legacy support. /// </summary> public class ZeusContext : ZeusGuiContext { public ZeusContext() : base() {} public ZeusContext(IZeusInput input, /*IGuiController gui,*/ Hashtable objects) : base(input, /*gui,*/ objects) {} } #endregion }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace CqlPoco.TypeConversion { /// <summary> /// A factory for retrieving Functions capable of converting between two Types. To use custom Type conversions, inheritors /// should derive from this class and implement the <see cref="GetUserDefinedFromDbConverter{TDatabase,TPoco}"/> and /// <see cref="GetUserDefinedToDbConverter{TPoco,TDatabase}"/> methods. /// </summary> public abstract class TypeConverter { private const BindingFlags PrivateStatic = BindingFlags.NonPublic | BindingFlags.Static; private const BindingFlags PrivateInstance = BindingFlags.NonPublic | BindingFlags.Instance; private static readonly MethodInfo FindFromDbConverterMethod = typeof (TypeConverter).GetMethod("FindFromDbConverter", PrivateInstance); private static readonly MethodInfo FindToDbConverterMethod = typeof (TypeConverter).GetMethod("FindToDbConverter", PrivateInstance); private static readonly MethodInfo ConvertToDictionaryMethod = typeof (TypeConverter).GetMethod("ConvertToDictionary", PrivateStatic); private static readonly MethodInfo ConvertToHashSetMethod = typeof(TypeConverter).GetMethod("ConvertToHashSet", PrivateStatic); private static readonly MethodInfo ConvertToSortedSetMethod = typeof(TypeConverter).GetMethod("ConvertToSortedSet", PrivateStatic); private static readonly MethodInfo ConvertToArrayMethod = typeof (Enumerable).GetMethod("ToArray", BindingFlags.Public | BindingFlags.Static); private readonly ConcurrentDictionary<Tuple<Type, Type>, Delegate> _fromDbConverterCache; private readonly ConcurrentDictionary<Tuple<Type, Type>, Delegate> _toDbConverterCache; /// <summary> /// Creates a new TypeConverter instance. /// </summary> protected TypeConverter() { _fromDbConverterCache = new ConcurrentDictionary<Tuple<Type, Type>, Delegate>(); _toDbConverterCache = new ConcurrentDictionary<Tuple<Type, Type>, Delegate>(); } /// <summary> /// Converts a value of Type <typeparamref name="TValue"/> to a value of Type <typeparamref name="TDatabase"/> using any available converters that would /// normally be used when converting a value for storage in Cassandra. If no converter is available, wlll throw an InvalidOperationException. /// </summary> /// <typeparam name="TValue">The value's original Type.</typeparam> /// <typeparam name="TDatabase">The Type expected by the database for the parameter.</typeparam> /// <param name="value">The value to be converted.</param> /// <returns>The converted value.</returns> internal TDatabase ConvertCqlArgument<TValue, TDatabase>(TValue value) { var converter = (Func<TValue, TDatabase>) GetToDbConverter(typeof (TValue), typeof (TDatabase)); if (converter == null) { throw new InvalidOperationException(string.Format("No converter is available from Type {0} to Type {1}", typeof(TValue).Name, typeof(TDatabase).Name)); } return converter(value); } /// <summary> /// Gets a Function that can convert a source type value from the database to a destination type value on a POCO. /// </summary> internal Delegate GetFromDbConverter(Type dbType, Type pocoType) { return _fromDbConverterCache.GetOrAdd(Tuple.Create(dbType, pocoType), // Invoke the generic method below with our two type parameters _ => (Delegate) FindFromDbConverterMethod.MakeGenericMethod(dbType, pocoType).Invoke(this, null)); } /// <summary> /// Gets a Function that can convert a source type value on a POCO to a destination type value for storage in C*. /// </summary> internal Delegate GetToDbConverter(Type pocoType, Type dbType) { return _toDbConverterCache.GetOrAdd(Tuple.Create(pocoType, dbType), _ => (Delegate) FindToDbConverterMethod.MakeGenericMethod(pocoType, dbType).Invoke(this, null)); } /// <summary> /// This method is generic because it seems like a good idea to enforce that the abstract method that returns a user-defined Func returns /// one with the correct type parameters, so we'd be invoking that abstract method generically via reflection anyway each time. So we might /// as well make this method generic and invoke it via reflection (it also makes the code for returning the built-in EnumStringMapper func /// simpler since that class is generic). /// </summary> // ReSharper disable once UnusedMember.Local (invoked via reflection) private Delegate FindFromDbConverter<TDatabase, TPoco>() { // Allow for user-defined conversions Delegate converter = GetUserDefinedFromDbConverter<TDatabase, TPoco>(); if (converter != null) return converter; Type dbType = typeof (TDatabase); Type pocoType = typeof (TPoco); // Allow strings from the database to be converted to an enum/nullable enum property on a POCO if (dbType == typeof(string)) { if (pocoType.IsEnum) { Func<string, TPoco> enumMapper = EnumStringMapper<TPoco>.MapStringToEnum; return enumMapper; } var underlyingPocoType = Nullable.GetUnderlyingType(pocoType); if (underlyingPocoType != null && underlyingPocoType.IsEnum) { Func<string, TPoco> enumMapper = NullableEnumStringMapper<TPoco>.MapStringToEnum; return enumMapper; } } if (dbType.IsGenericType && pocoType.IsGenericType) { Type sourceGenericDefinition = dbType.GetGenericTypeDefinition(); Type[] sourceGenericArgs = dbType.GetGenericArguments(); // Allow conversion from IDictionary<,> -> Dictionary<,> since C* driver uses SortedDictionary which can't be cast to Dictionary if (sourceGenericDefinition == typeof (IDictionary<,>) && pocoType == typeof (Dictionary<,>).MakeGenericType(sourceGenericArgs)) { return ConvertToDictionaryMethod.MakeGenericMethod(sourceGenericArgs).CreateDelegate(typeof (Func<TDatabase, TPoco>)); } // IEnumerable<> could be a Set or a List from Cassandra if (sourceGenericDefinition == typeof (IEnumerable<>)) { // For some reason, the driver uses List<> to represent Sets so allow conversion to HashSet<>, SortedSet<>, and ISet<> if (pocoType == typeof (HashSet<>).MakeGenericType(sourceGenericArgs)) { return ConvertToHashSetMethod.MakeGenericMethod(sourceGenericArgs).CreateDelegate(typeof (Func<TDatabase, TPoco>)); } if (pocoType == typeof (SortedSet<>).MakeGenericType(sourceGenericArgs) || pocoType == typeof (ISet<>).MakeGenericType(sourceGenericArgs)) { return ConvertToSortedSetMethod.MakeGenericMethod(sourceGenericArgs).CreateDelegate(typeof (Func<TDatabase, TPoco>)); } // Allow converting from set/list's IEnumerable<T> to T[] if (pocoType == sourceGenericArgs[0].MakeArrayType()) { return ConvertToArrayMethod.MakeGenericMethod(sourceGenericArgs).CreateDelegate(typeof (Func<TDatabase, TPoco>)); } } } return null; } /// <summary> /// See note above on why this is generic. /// </summary> // ReSharper disable once UnusedMember.Local (invoked via reflection) private Delegate FindToDbConverter<TPoco, TDatabase>() { // Allow for user-defined conversions Delegate converter = GetUserDefinedToDbConverter<TPoco, TDatabase>(); if (converter != null) return converter; Type pocoType = typeof (TPoco); Type dbType = typeof (TDatabase); // Support enum/nullable enum => string conversion if (dbType == typeof (string)) { if (pocoType.IsEnum) { // Just call ToStirng() on the enum value from the POCO Func<TPoco, string> enumConverter = prop => prop.ToString(); return enumConverter; } Type underlyingPocoType = Nullable.GetUnderlyingType(pocoType); if (underlyingPocoType != null && underlyingPocoType.IsEnum) { Func<TPoco, string> enumConverter = NullableEnumStringMapper<TPoco>.MapEnumToString; return enumConverter; } } return null; } // ReSharper disable UnusedMember.Local // (these methods are invoked via reflection above) private static Dictionary<TKey, TValue> ConvertToDictionary<TKey, TValue>(IDictionary<TKey, TValue> mapFromDatabase) { return new Dictionary<TKey, TValue>(mapFromDatabase); } private static HashSet<T> ConvertToHashSet<T>(IEnumerable<T> setFromDatabase) { return new HashSet<T>(setFromDatabase); } private static SortedSet<T> ConvertToSortedSet<T>(IEnumerable<T> setFromDatabase) { return new SortedSet<T>(setFromDatabase); } // ReSharper restore UnusedMember.Local /// <summary> /// Gets any user defined conversion functions that can convert a value of type <typeparamref name="TDatabase"/> (coming from Cassandra) to a /// type of <typeparamref name="TPoco"/> (a field or property on a POCO). Return null if no conversion Func is available. /// </summary> /// <typeparam name="TDatabase">The Type of the source value from Cassandra to be converted.</typeparam> /// <typeparam name="TPoco">The Type of the destination value on the POCO.</typeparam> /// <returns>A Func that can convert between the two types or null if one is not available.</returns> protected abstract Func<TDatabase, TPoco> GetUserDefinedFromDbConverter<TDatabase, TPoco>(); /// <summary> /// Gets any user defined conversion functions that can convert a value of type <typeparamref name="TPoco"/> (coming from a property/field on a /// POCO) to a type of <typeparamref name="TDatabase"/> (the Type expected by Cassandra for the database column). Return null if no conversion /// Func is available. /// </summary> /// <typeparam name="TPoco">The Type of the source value from the POCO property/field to be converted.</typeparam> /// <typeparam name="TDatabase">The Type expected by C* for the database column.</typeparam> /// <returns>A Func that can converter between the two Types or null if one is not available.</returns> protected abstract Func<TPoco, TDatabase> GetUserDefinedToDbConverter<TPoco, TDatabase>(); } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace bGApi.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); } } } }
namespace iTin.Export.Model { using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Xml.Serialization; using ComponentModel; using Helpers; /// <summary> /// Base class for the different types of field conditions supported by <strong><c>iTin Export Engine</c></strong>.<br /> /// Which acts as the base class for different conditions. /// </summary> /// <remarks> /// <para>The following table shows different conditions.</para> /// <list type="table"> /// <listheader> /// <term>Class</term> /// <description>Description</description> /// </listheader> /// <item> /// <term><see cref="T:iTin.Export.Model.MaximumCondition" /></term> /// <description>Evaluates the maximum condition over a data field.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.MinimumCondition" /></term> /// <description>Evaluates the minimum condition over a data field.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.RemarksCondition" /></term> /// <description>Evaluates custom logic condition over a data field.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.WhenChangeCondition" /></term> /// <description>Evaluates condition over a data field.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.ZeroCondition" /></term> /// <description>Evaluates condition over a data field.</description> /// </item> /// </list> /// </remarks> public partial class BaseConditionModel : ICondition { #region private constants [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const YesNo ActiveDefault = YesNo.Yes; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const YesNo EntireRowDefault = YesNo.No; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const KnownCulture LocaleDefault = KnownCulture.Current; #endregion #region private members [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string _key; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private YesNo _active; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string _field; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private YesNo _entrireRow; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private KnownCulture _locale; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private ConditionsModel _owner; #endregion #region [protected] BaseConditionModel(): Initializes a new instance of this class /// <summary> /// Initializes a new instance of the <see cref="T:iTin.Export.Model.BaseConditionModel" /> class. /// </summary> protected BaseConditionModel() { _active = ActiveDefault; _locale = LocaleDefault; _entrireRow = EntireRowDefault; } #endregion #region protected properties #region [protected] (ModelService) Service: Gets a reference to an object that contains information about the context /// <summary> /// Gets a reference to an object that contains information about the context. /// </summary> /// <value> /// A <see cref="ModelService"/> that contains information about the context. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] protected ModelService Service => ModelService.Instance; #endregion #endregion #region public readonly properties #region [public] (ConditionsModel) Owner: Gets the element that owns this condition /// <summary> /// Gets the element that owns this data field. /// </summary> /// <value> /// The <see cref="T:iTin.Export.Model.ConditionsModel" /> that owns this condition. /// </value> [XmlIgnore] [Browsable(false)] public ConditionsModel Owner => _owner; #endregion #endregion #region public properties #region [public] (YesNo) Active: Gets or sets a value that indicates if this condition is active /// <summary> /// Gets or sets a value that indicates if this condition is active. The default is <see cref="T:iTin.Export.Model.YesNo.Yes"/>. /// </summary> /// <value> /// <see cref="YesNo.Yes"/> if is active; otherwise, <see cref="YesNo.No"/>. /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition Active="Yes|No" ...&gt; /// ... /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition&gt; /// </code> /// <para> /// <para><strong>Compatibility table with native writers.</strong></para> /// <table> /// <thead> /// <tr> /// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter"/></th> /// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter"/></th> /// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter"/></th> /// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter"/></th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">X</td> /// </tr> /// </tbody> /// </table> /// A <strong><c>X</c></strong> value indicates that the writer supports this element. /// </para> /// </remarks> /// <example> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;Global.Resources&gt; /// &lt;Conditions&gt; /// &lt;MaximumCondition Key="max" Active="Yes" Field="TOTAL" EntireRow="No" Style="maxTotalStyle"/&gt; /// ... /// &lt;/Conditions&gt; /// &lt;/Global.Resources&gt; /// </code> /// </example> [XmlAttribute] [DefaultValue(ActiveDefault)] public YesNo Active { get => GetStaticBindingValue(_active.ToString()).ToUpperInvariant() == "NO" ? YesNo.No : YesNo.Yes; set { SentinelHelper.IsEnumValid(value); _active = value; } } #endregion #region [public] (YesNo) EntireRow: Gets or sets a value that indicates if condition style applies over the row /// <summary> /// Gets or sets a value that indicates if condition style applies over the row. The default is <see cref="T:iTin.Export.Model.YesNo.No"/>. /// </summary> /// <value> /// <see cref="YesNo.Yes"/> if condition style applies over row; otherwise, <see cref="YesNo.No"/> if style condition only applies over field cell. /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition EntireRow="Yes|No" ...&gt; /// ... /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition&gt; /// </code> /// <para> /// <para><strong>Compatibility table with native writers.</strong></para> /// <table> /// <thead> /// <tr> /// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter"/></th> /// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter"/></th> /// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter"/></th> /// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter"/></th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">X</td> /// </tr> /// </tbody> /// </table> /// A <strong><c>X</c></strong> value indicates that the writer supports this element. /// </para> /// </remarks> /// <example> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;Global.Resources&gt; /// &lt;Conditions&gt; /// &lt;MaximumCondition Key="max" Active="Yes" Field="TOTAL" EntireRow="No" Style="maxTotalStyle"/&gt; /// ... /// &lt;/Conditions&gt; /// &lt;/Global.Resources&gt; /// </code> /// </example> [XmlAttribute] [DefaultValue(EntireRowDefault)] public YesNo EntireRow { get => GetStaticBindingValue(_entrireRow.ToString()).ToUpperInvariant() == "NO" ? YesNo.No : YesNo.Yes; set { SentinelHelper.IsEnumValid(value); _entrireRow = value; } } #endregion #region [public] (string) Field: Gets or sets a value that represents the field on which the condition will be evaluated /// <summary> /// Gets or sets a value that represents the field on which the condition will be evaluated /// </summary> /// <value> /// A <see cref ="T:System.String"/> that represents the field on which the condition will be evaluated. /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition Field="string" ...&gt; /// ... /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition&gt; /// </code> /// <para> /// <para><strong>Compatibility table with native writers.</strong></para> /// <table> /// <thead> /// <tr> /// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter"/></th> /// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter"/></th> /// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter"/></th> /// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter"/></th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">X</td> /// </tr> /// </tbody> /// </table> /// A <strong><c>X</c></strong> value indicates that the writer supports this element. /// </para> /// </remarks> /// <example> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;Global.Resources&gt; /// &lt;Conditions&gt; /// &lt;MaximumCondition Key="max" Active="Yes" Field="TOTAL" EntireRow="No" Style="maxTotalStyle"/&gt; /// ... /// &lt;/Conditions&gt; /// &lt;/Global.Resources&gt; /// </code> /// </example> [XmlAttribute] public string Field { get => GetStaticBindingValue(_field); set { SentinelHelper.ArgumentNull(value); SentinelHelper.IsFalse(RegularExpressionHelper.IsValidFieldName(value), new InvalidFieldIdentifierNameException(ErrorMessageHelper.FieldIdentifierNameErrorMessage(GetType().Name, "Field", value))); _field = value; } } #endregion #region [public] (string) Key: Gets or sets a value that contains an identifier for this condition /// <summary> /// Gets or sets a value that contains an identifier for this condition /// </summary> /// <value> /// A <see cref ="T:System.String"/> that represents the identifier for this condition. /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition Key="string" ...&gt; /// ... /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition&gt; /// </code> /// <para> /// <para><strong>Compatibility table with native writers.</strong></para> /// <table> /// <thead> /// <tr> /// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter"/></th> /// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter"/></th> /// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter"/></th> /// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter"/></th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">X</td> /// </tr> /// </tbody> /// </table> /// A <strong><c>X</c></strong> value indicates that the writer supports this element. /// </para> /// </remarks> /// <example> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;Global.Resources&gt; /// &lt;Conditions&gt; /// &lt;MaximumCondition Key="max" Active="Yes" Field="TOTAL" EntireRow="No" Style="maxTotalStyle"/&gt; /// ... /// &lt;/Conditions&gt; /// &lt;/Global.Resources&gt; /// </code> /// </example> [XmlAttribute] public string Key { get => GetStaticBindingValue(_key); set { SentinelHelper.ArgumentNull(value); SentinelHelper.IsFalse(RegularExpressionHelper.IsValidIdentifier(value), new InvalidIdentifierNameException(ErrorMessageHelper.ModelIdentifierNameErrorMessage(GetType().Name, "Name", value))); _key = value; } } #endregion #region [public] (KnownCulture) Locale: Gets or sets the data field culture /// <summary> /// Gets or sets the data field culture. The default is <see cref="KnownCulture.Current" />. /// </summary> /// <value> /// One of the <see cref="T:iTin.Export.Model.KnownCulture" /> values. /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition Locale="Current|any culture" ...&gt; /// ... /// &lt;MaximumCondition|MinimumCondition|RemarksCondition|WhenChangeCondition|ZeroCondition&gt; /// </code> /// <para> /// <para><strong>Compatibility table with native writers.</strong></para> /// <table> /// <thead> /// <tr> /// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter" /></th> /// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter" /></th> /// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter" /></th> /// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter" /></th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">No has effect</td> /// <td align="center">X</td> /// </tr> /// </tbody> /// </table> /// A <strong><c>X</c></strong> value indicates that the writer supports this element. /// </para> /// </remarks> /// <example> /// In the following example shows how create a new style. /// <code lang="xml"> /// &lt;Global.Resources&gt; /// &lt;Conditions&gt; /// &lt;MaximumCondition Key="max" Active="Yes" Field="TOTAL" EntireRow="No" Style="maxTotalStyle" Locale="en-EN"/&gt; /// ... /// &lt;/Conditions&gt; /// &lt;/Global.Resources&gt; /// </code> /// </example> [XmlAttribute] [DefaultValue(LocaleDefault)] public KnownCulture Locale { get => _locale; set { var isValidLocale = true; if (!value.Equals(KnownCulture.Current)) { var isValidCulture = IsValidCulture(value); if (!isValidCulture) { isValidLocale = false; } } _locale = isValidLocale ? value : LocaleDefault; } } #endregion #endregion #region public override readonly properties #region [public] {overide} (bool) IsDefault: Gets a value indicating whether this instance is default /// <inheritdoc /> /// <summary> /// Gets a value indicating whether this instance is default. /// </summary> /// <value> /// <strong>true</strong> if this instance contains the default; otherwise, <strong>false</strong>. /// </value> public override bool IsDefault => string.IsNullOrEmpty(Key) && string.IsNullOrEmpty(Field); #endregion #endregion #region public methods #region [public] (ConditionResult) Evaluate(): Returns result of evaluates condition /// <inheritdoc /> /// <summary> /// Returns result of evaluates condition. /// </summary> /// <returns> /// A <see cref="T:iTin.Export.Model.ConditionResult" /> object that contains evaluate result. /// </returns> public ConditionResult Evaluate() { var service = ModelService.Instance; return Evaluate( service.CurrentRow, service.CurrentCol); } #endregion #region [public] (ConditionResult) Evaluate(int, int): Returns result of evaluates condition /// <inheritdoc /> /// <summary> /// Returns result of evaluates condition. /// </summary> /// <param name="row">Data row</param> /// <param name="col">Field column</param> /// <returns> /// A <see cref="T:iTin.Export.Model.ConditionResult" /> object that contains evaluate result. /// </returns> public ConditionResult Evaluate(int row, int col) { var normalizedField = Field.ToUpperInvariant(); var normalizedFieldName = BaseDataFieldModel.GetFieldNameFrom(Service.CurrentField).ToUpperInvariant(); return normalizedField != normalizedFieldName ? ConditionResult.Default : Evaluate(row, col, Service.CurrentField.Value.GetValue()); } #endregion #region [public] (void) SetOwner(ConditionsModel): Sets a reference to the owner object that contains this instance /// <summary> /// Sets a reference to the owner object that contains this instance. /// </summary> /// <param name="reference">Owner reference.</param> public void SetOwner(ConditionsModel reference) { _owner = reference; } #endregion #endregion #region public override methods #region [public] {override} (string) ToString(): Returns a string that represents the current object /// <inheritdoc /> /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A <see cref="T:System.String" /> that represents the current object. /// </returns> /// <remarks> /// This method <see cref="M:iTin.Export.Model.DataFieldModel.ToString" /> returns a string that includes field alias. /// </remarks> public override string ToString() { return $"Key=\"{Key}\", Field=\"{Field}\""; } #endregion #endregion #region public abstrtact methods #region [public] {abstract} (ConditionResult) Evaluate(int, int, FieldValueInformation): Returns result of evaluates condition /// <inheritdoc /> /// <summary> /// Returns result of evaluates condition. /// </summary> /// <param name="row">Data row</param> /// <param name="col">Field column</param> /// <param name="target">Field data</param> /// <returns> /// A <see cref="T:iTin.Export.Model.ConditionResult" /> object that contains evaluate result. /// </returns> public abstract ConditionResult Evaluate(int row, int col, FieldValueInformation target); #endregion #endregion #region protected methods #region [protected] (IEnumerable<string>) GetFieldAttributeEnumerable(): Returns a list of field condition content /// <summary> /// Returns a list of field condition with raw content. /// </summary> /// <returns> /// A list of field condition with raw content. /// </returns> protected IEnumerable<string> GetFieldAttributeEnumerable() { var validRawData = new Collection<string>(); foreach (var rawData in Service.RawDataFiltered) { var fieldAttr = rawData.Attribute(Field); if (fieldAttr == null) { continue; } if (string.IsNullOrEmpty(fieldAttr.Value)) { continue; } validRawData.Add(fieldAttr.Value); } return validRawData; } #endregion #endregion #region private static methods #region [private] {static} (bool) IsValidCulture: Gets a value indicating whether the specified culture is installed on this system /// <summary> /// Gets a value indicating whether the font is installed on this system. /// </summary> /// <param name="culture">Culture to check.</param> /// <returns> /// <strong>true</strong> if the specified culture is installed on the system; otherwise, <strong>false</strong>. /// </returns> private static bool IsValidCulture(KnownCulture culture) { var iw32C = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures); return iw32C.Any(clt => clt.Name == ExportsModel.GetXmlEnumAttributeFromItem(culture)); } #endregion #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using Umbraco.Core.Models; using Umbraco.Core.Persistence.DatabaseModelDefinitions; namespace Umbraco.Core.Services { /// <summary> /// A temporary interface until we are in v8, this is used to return a different result for the same method and this interface gets implemented /// explicitly. These methods will replace the normal ones in IContentService in v8 and this will be removed. /// </summary> public interface IMediaServiceOperations { //TODO: Remove this class in v8 //TODO: There's probably more that needs to be added like the EmptyRecycleBin, etc... /// <summary> /// Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin /// </summary> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> Attempt<OperationStatus> MoveToRecycleBin(IMedia media, int userId = 0); /// <summary> /// Permanently deletes an <see cref="IMedia"/> object /// </summary> /// <remarks> /// Please note that this method will completely remove the Media from the database, /// but current not from the file system. /// </remarks> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> Attempt<OperationStatus> Delete(IMedia media, int userId = 0); /// <summary> /// Saves a single <see cref="IMedia"/> object /// </summary> /// <param name="media">The <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> Attempt<OperationStatus> Save(IMedia media, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IMedia"/> objects /// </summary> /// <param name="medias">Collection of <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> Attempt<OperationStatus> Save(IEnumerable<IMedia> medias, int userId = 0, bool raiseEvents = true); } /// <summary> /// Defines the Media Service, which is an easy access to operations involving <see cref="IMedia"/> /// </summary> public interface IMediaService : IService { /// <summary> /// Rebuilds all xml content in the cmsContentXml table for all media /// </summary> /// <param name="contentTypeIds"> /// Only rebuild the xml structures for the content type ids passed in, if none then rebuilds the structures /// for all media /// </param> void RebuildXmlStructures(params int[] contentTypeIds); int Count(string contentTypeAlias = null); int CountChildren(int parentId, string contentTypeAlias = null); int CountDescendants(int parentId, string contentTypeAlias = null); IEnumerable<IMedia> GetByIds(IEnumerable<int> ids); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IMedia without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parentId">Id of Parent for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, int parentId, string mediaTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IMedia without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = 0); /// <summary> /// Gets an <see cref="IMedia"/> object by Id /// </summary> /// <param name="id">Id of the Content to retrieve</param> /// <returns><see cref="IMedia"/></returns> IMedia GetById(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetChildren(int id); [Obsolete("Use the overload with 'long' parameter types instead")] [EditorBrowsable(EditorBrowsableState.Never)] IEnumerable<IMedia> GetPagedChildren(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = ""); [Obsolete("Use the overload with 'long' parameter types instead")] [EditorBrowsable(EditorBrowsableState.Never)] IEnumerable<IMedia> GetPagedDescendants(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "Path", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy = "Path", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets descendants of a <see cref="IMedia"/> object by its Id /// </summary> /// <param name="id">Id of the Parent to retrieve descendants from</param> /// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetDescendants(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by the Id of the <see cref="IContentType"/> /// </summary> /// <param name="id">Id of the <see cref="IMediaType"/></param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetMediaOfMediaType(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects, which reside at the first level / root /// </summary> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetRootMedia(); /// <summary> /// Gets a collection of an <see cref="IMedia"/> objects, which resides in the Recycle Bin /// </summary> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetMediaInRecycleBin(); /// <summary> /// Moves an <see cref="IMedia"/> object to a new location /// </summary> /// <param name="media">The <see cref="IMedia"/> to move</param> /// <param name="parentId">Id of the Media's new Parent</param> /// <param name="userId">Id of the User moving the Media</param> void Move(IMedia media, int parentId, int userId = 0); /// <summary> /// Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin /// </summary> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> void MoveToRecycleBin(IMedia media, int userId = 0); /// <summary> /// Empties the Recycle Bin by deleting all <see cref="IMedia"/> that resides in the bin /// </summary> void EmptyRecycleBin(); /// <summary> /// Deletes all media of specified type. All children of deleted media is moved to Recycle Bin. /// </summary> /// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> /// <param name="mediaTypeId">Id of the <see cref="IMediaType"/></param> /// <param name="userId">Optional Id of the user deleting Media</param> void DeleteMediaOfType(int mediaTypeId, int userId = 0); /// <summary> /// Permanently deletes an <see cref="IMedia"/> object /// </summary> /// <remarks> /// Please note that this method will completely remove the Media from the database, /// but current not from the file system. /// </remarks> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> void Delete(IMedia media, int userId = 0); /// <summary> /// Saves a single <see cref="IMedia"/> object /// </summary> /// <param name="media">The <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IMedia media, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IMedia"/> objects /// </summary> /// <param name="medias">Collection of <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IEnumerable<IMedia> medias, int userId = 0, bool raiseEvents = true); /// <summary> /// Gets an <see cref="IMedia"/> object by its 'UniqueId' /// </summary> /// <param name="key">Guid key of the Media to retrieve</param> /// <returns><see cref="IMedia"/></returns> IMedia GetById(Guid key); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Level /// </summary> /// <param name="level">The level to retrieve Media from</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetByLevel(int level); /// <summary> /// Gets a specific version of an <see cref="IMedia"/> item. /// </summary> /// <param name="versionId">Id of the version to retrieve</param> /// <returns>An <see cref="IMedia"/> item</returns> IMedia GetByVersion(Guid versionId); /// <summary> /// Gets a collection of an <see cref="IMedia"/> objects versions by Id /// </summary> /// <param name="id"></param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetVersions(int id); /// <summary> /// Checks whether an <see cref="IMedia"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IMedia"/></param> /// <returns>True if the media has any children otherwise False</returns> bool HasChildren(int id); /// <summary> /// Permanently deletes versions from an <see cref="IMedia"/> object prior to a specific date. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> object to delete versions from</param> /// <param name="versionDate">Latest version date</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersions(int id, DateTime versionDate, int userId = 0); /// <summary> /// Permanently deletes specific version(s) from an <see cref="IMedia"/> object. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> object to delete a version from</param> /// <param name="versionId">Id of the version to delete</param> /// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0); /// <summary> /// Gets an <see cref="IMedia"/> object from the path stored in the 'umbracoFile' property. /// </summary> /// <param name="mediaPath">Path of the media item to retrieve (for example: /media/1024/koala_403x328.jpg)</param> /// <returns><see cref="IMedia"/></returns> IMedia GetMediaByPath(string mediaPath); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetAncestors(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media. /// </summary> /// <param name="media"><see cref="IMedia"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetAncestors(IMedia media); /// <summary> /// Gets descendants of a <see cref="IMedia"/> object by its Id /// </summary> /// <param name="media">The Parent <see cref="IMedia"/> object to retrieve descendants from</param> /// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetDescendants(IMedia media); /// <summary> /// Gets the parent of the current media as an <see cref="IMedia"/> item. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IMedia"/> object</returns> IMedia GetParent(int id); /// <summary> /// Gets the parent of the current media as an <see cref="IMedia"/> item. /// </summary> /// <param name="media"><see cref="IMedia"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IMedia"/> object</returns> IMedia GetParent(IMedia media); /// <summary> /// Sorts a collection of <see cref="IMedia"/> objects by updating the SortOrder according /// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>. /// </summary> /// <param name="items"></param> /// <param name="userId"></param> /// <param name="raiseEvents"></param> /// <returns>True if sorting succeeded, otherwise False</returns> bool Sort(IEnumerable<IMedia> items, int userId = 0, bool raiseEvents = true); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IMedia"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMediaWithIdentity(string name, IMedia parent, string mediaTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IMedia"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parentId">Id of Parent for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMediaWithIdentity(string name, int parentId, string mediaTypeAlias, int userId = 0); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using System.Threading.Tasks; using Windows.Foundation; namespace System { /// <summary>Provides extension methods in the System namespace for working with the Windows Runtime.<br /> /// Currently contains:<br /> /// <ul> /// <li>Extension methods for conversion between <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces /// and <code>System.Threading.Tasks.Task</code>.</li> /// <li>Extension methods for conversion between <code>System.Threading.Tasks.Task</code> /// and <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces.</li> /// </ul></summary> [CLSCompliant(false)] public static class WindowsRuntimeSystemExtensions { #region Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task #region Convenience Helpers private static void ConcatenateCancelTokens(CancellationToken source, CancellationTokenSource sink, Task concatenationLifetime) { Debug.Assert(sink != null); CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state).Cancel(); }, sink); concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state).Dispose(); }, ctReg, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } private static void ConcatenateProgress<TProgress>(IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> sink) { // This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null. source.Progress += new AsyncActionProgressHandler<TProgress>((_, info) => sink.Report(info)); } private static void ConcatenateProgress<TResult, TProgress>(IAsyncOperationWithProgress<TResult, TProgress> source, IProgress<TProgress> sink) { // This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null. source.Progress += new AsyncOperationProgressHandler<TResult, TProgress>((_, info) => sink.Report(info)); } #endregion Convenience Helpers #region Converters from IAsyncAction to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter GetAwaiter(this IAsyncAction source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask(this IAsyncAction source) { return AsTask(source, CancellationToken.None); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncActionAdapter; if (wrapper != null && !wrapper.CompletedSynchronously) { Task innerTask = wrapper.Task; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatination is useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); } return innerTask; } // Fast path to return a completed Task if the operation has already completed: switch (source.Status) { case AsyncStatus.Completed: return Task.CompletedTask; case AsyncStatus.Error: return Task.FromException(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, VoidValueTypeParameter>(cancellationToken); source.Completed = new AsyncActionCompletedHandler(bridge.CompleteFromAsyncAction); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncAction to Task #region Converters from IAsyncOperation<TResult> to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter<TResult> GetAwaiter<TResult>(this IAsyncOperation<TResult> source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source) { return AsTask(source, CancellationToken.None); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncOperationAdapter<TResult>; if (wrapper != null && !wrapper.CompletedSynchronously) { Task<TResult> innerTask = wrapper.Task as Task<TResult>; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatination is useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); } return innerTask; } // Fast path to return a completed Task if the operation has already completed switch (source.Status) { case AsyncStatus.Completed: return Task.FromResult(source.GetResults()); case AsyncStatus.Error: return Task.FromException<TResult>(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<TResult, VoidValueTypeParameter>(cancellationToken); source.Completed = new AsyncOperationCompletedHandler<TResult>(bridge.CompleteFromAsyncOperation); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncOperation<TResult> to Task #region Converters from IAsyncActionWithProgress<TProgress> to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter GetAwaiter<TProgress>(this IAsyncActionWithProgress<TProgress> source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source) { return AsTask(source, CancellationToken.None, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, CancellationToken cancellationToken) { return AsTask(source, cancellationToken, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> progress) { return AsTask(source, CancellationToken.None, progress); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, CancellationToken cancellationToken, IProgress<TProgress> progress) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>; if (wrapper != null && !wrapper.CompletedSynchronously) { Task innerTask = wrapper.Task; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatinations are useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); if (progress != null) ConcatenateProgress(source, progress); } return innerTask; } // Fast path to return a completed Task if the operation has already completed: switch (source.Status) { case AsyncStatus.Completed: return Task.CompletedTask; case AsyncStatus.Error: return Task.FromException(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Forward progress reports: if (progress != null) ConcatenateProgress(source, progress); // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, TProgress>(cancellationToken); source.Completed = new AsyncActionWithProgressCompletedHandler<TProgress>(bridge.CompleteFromAsyncActionWithProgress); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncActionWithProgress<TProgress> to Task #region Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter<TResult> GetAwaiter<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the started asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source) { return AsTask(source, CancellationToken.None, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source, CancellationToken cancellationToken) { return AsTask(source, cancellationToken, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source, IProgress<TProgress> progress) { return AsTask(source, CancellationToken.None, progress); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source, CancellationToken cancellationToken, IProgress<TProgress> progress) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>; if (wrapper != null && !wrapper.CompletedSynchronously) { Task<TResult> innerTask = wrapper.Task as Task<TResult>; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatinations are useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); if (progress != null) ConcatenateProgress(source, progress); } return innerTask; } // Fast path to return a completed Task if the operation has already completed switch (source.Status) { case AsyncStatus.Completed: return Task.FromResult(source.GetResults()); case AsyncStatus.Error: return Task.FromException<TResult>(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Forward progress reports: if (progress != null) ConcatenateProgress(source, progress); // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<TResult, TProgress>(cancellationToken); source.Completed = new AsyncOperationWithProgressCompletedHandler<TResult, TProgress>(bridge.CompleteFromAsyncOperationWithProgress); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task #endregion Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task #region Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it) public static IAsyncAction AsAsyncAction(this Task source) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return new TaskToAsyncActionAdapter(source, underlyingCancelTokenSource: null); } public static IAsyncOperation<TResult> AsAsyncOperation<TResult>(this Task<TResult> source) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return new TaskToAsyncOperationAdapter<TResult>(source, underlyingCancelTokenSource: null); } #endregion Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it) private static void CommonlyUsedGenericInstantiations() { // This method is an aid for NGen to save common generic // instantiations into the ngen image. ((IAsyncOperation<bool>)null).AsTask(); ((IAsyncOperation<string>)null).AsTask(); ((IAsyncOperation<object>)null).AsTask(); ((IAsyncOperation<uint>)null).AsTask(); ((IAsyncOperationWithProgress<uint, uint>)null).AsTask(); ((IAsyncOperationWithProgress<ulong, ulong>)null).AsTask(); ((IAsyncOperationWithProgress<string, ulong>)null).AsTask(); } } // class WindowsRuntimeSystemExtensions } // namespace // WindowsRuntimeExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using EPiServer.Commerce.Order; using EPiServer.Reference.Commerce.Site.Features.Cart.Services; using EPiServer.Reference.Commerce.Site.Features.Cart.ViewModelFactories; using EPiServer.Reference.Commerce.Site.Infrastructure.Attributes; using System.Web.Mvc; using Castle.Core.Internal; using EPiServer.Core; using EPiServer.Reference.Commerce.Site.B2B.Enums; using EPiServer.Reference.Commerce.Site.B2B.ServiceContracts; using EPiServer.Reference.Commerce.Site.Features.Start.Pages; using Mediachase.Commerce.Catalog; using Constants = EPiServer.Reference.Commerce.Site.B2B.Constants; namespace EPiServer.Reference.Commerce.Site.Features.Cart.Controllers { public class CartController : Controller { private readonly ICartService _cartService; private ICart _cart; private readonly IOrderRepository _orderRepository; readonly CartViewModelFactory _cartViewModelFactory; private readonly ICartServiceB2B _cartServiceB2B; private readonly IQuickOrderService _quickOrderService; private readonly ReferenceConverter _referenceConverter; private readonly ICustomerService _customerService; private readonly IContentLoader _contentLoader; public CartController( ICartService cartService, IOrderRepository orderRepository, CartViewModelFactory cartViewModelFactory, ICartServiceB2B cartServiceB2B, IQuickOrderService quickOrderService, ReferenceConverter referenceConverter, ICustomerService customerService, IContentLoader contentLoader) { _cartService = cartService; _orderRepository = orderRepository; _cartViewModelFactory = cartViewModelFactory; _cartServiceB2B = cartServiceB2B; _quickOrderService = quickOrderService; _referenceConverter = referenceConverter; _customerService = customerService; _contentLoader = contentLoader; } [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)] public ActionResult MiniCartDetails() { var viewModel = _cartViewModelFactory.CreateMiniCartViewModel(Cart); return PartialView("_MiniCartDetails", viewModel); } [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)] public ActionResult LargeCart() { var viewModel = _cartViewModelFactory.CreateLargeCartViewModel(Cart); return PartialView("LargeCart", viewModel); } [HttpPost] [AllowDBWrite] public ActionResult AddToCart(string code) { string warningMessage = string.Empty; ModelState.Clear(); if (Cart == null) { _cart = _cartService.LoadOrCreateCart(_cartService.DefaultCartName); } // If order comes from an quoted order. if (Cart.Properties[Constants.Quote.ParentOrderGroupId] != null) { int orderLink = int.Parse(Cart.Properties[Constants.Quote.ParentOrderGroupId].ToString()); if (orderLink != 0) { return new HttpStatusCodeResult(500, "Invalid operation on quoted cart."); } } if (_cartService.AddToCart(Cart, code, out warningMessage)) { _orderRepository.Save(Cart); return MiniCartDetails(); } // HttpStatusMessage can't be longer than 512 characters. warningMessage = warningMessage.Length < 512 ? warningMessage : warningMessage.Substring(512); return new HttpStatusCodeResult(500, warningMessage); } [HttpPost] [AllowDBWrite] public JsonResult AddVariantsToCart(List<string> variants) { var returnedMessages = new List<string>(); ModelState.Clear(); if (Cart == null) { _cart = _cartService.LoadOrCreateCart(_cartService.DefaultCartName); } foreach (var product in variants) { var sku = product.Split(';')[0]; var quantity = Convert.ToInt32(product.Split(';')[1]); ContentReference variationReference = _referenceConverter.GetContentLink(sku); var responseMessage = _quickOrderService.ValidateProduct(variationReference, Convert.ToDecimal(quantity), sku); if (responseMessage.IsNullOrEmpty()) { string warningMessage; if (_cartService.AddToCart(Cart, sku, out warningMessage)) { _cartService.ChangeCartItem(Cart, 0, sku, quantity, "", ""); _orderRepository.Save(Cart); } } else { returnedMessages.Add(responseMessage); } } Session[Constants.ErrorMesages] = returnedMessages; return Json(returnedMessages, JsonRequestBehavior.AllowGet); } [HttpPost] [AllowDBWrite] public JsonResult ClearQuotedCart() { _cartServiceB2B.DeleteCart(Cart); _cart = _cartServiceB2B.CreateNewCart(); return Json("success", JsonRequestBehavior.AllowGet); } [HttpPost] [AllowDBWrite] public ActionResult ChangeCartItem(int shipmentId, string code, decimal quantity, string size, string newSize) { ModelState.Clear(); if (quantity != 0) { // If order comes from an quoted order. if (Cart.Properties[Constants.Quote.ParentOrderGroupId] != null) { int orderLink = int.Parse(Cart.Properties[Constants.Quote.ParentOrderGroupId].ToString()); if (orderLink != 0) { return new HttpStatusCodeResult(500, "Invalid operation on quoted cart."); } } } _cartService.ChangeCartItem(Cart, shipmentId, code, quantity, size, newSize); if (!Cart.GetAllLineItems().Any() && Cart.Properties[Constants.Quote.ParentOrderGroupId] != null) { _cartServiceB2B.DeleteCart(Cart); _cart = _cartServiceB2B.CreateNewCart(); } _orderRepository.Save(Cart); return MiniCartDetails(); } [HttpPost] [AllowDBWrite] public ActionResult RequestQuote() { bool succesRequest; var currentCustomer = _customerService.GetCurrentContact(); if (currentCustomer.Role != B2BUserRoles.Purchaser) return Json(new { result = false }); if (Cart == null) { _cart = _cartService.LoadOrCreateCart(_cartService.DefaultCartName); succesRequest = _cartServiceB2B.PlaceCartForQuote(_cart); } else { succesRequest = _cartServiceB2B.PlaceCartForQuote(Cart); } _cartServiceB2B.DeleteCart(_cart); _cart = _cartServiceB2B.CreateNewCart(); return Json(new { result = succesRequest }); } [HttpPost] [AllowDBWrite] public ActionResult RequestQuoteById(int orderId) { var currentCustomer = _customerService.GetCurrentContact(); if (currentCustomer.Role != B2BUserRoles.Purchaser) return Json(new { result = false }); var placedOrderId =_cartServiceB2B.PlaceCartForQuoteById(orderId, currentCustomer.ContactId); var startPage = _contentLoader.Get<StartPage>(ContentReference.StartPage); return RedirectToAction("Index", "OrderDetails", new {currentPage = startPage.OrderDetailsPage, orderGroupId = placedOrderId }); } private ICart Cart { get { return _cart ?? (_cart = _cartService.LoadCart(_cartService.DefaultCartName)); } } public CartViewModelFactory CartViewModelFactory { get { return _cartViewModelFactory; } } } }
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; namespace TBS.ScreenManager { /// <summary> /// The screen manager is a component which manages one or more GameScreen /// instances. It maintains a stack of screens, calls their Update and Draw /// methods at the appropriate times, and automatically routes input to the /// topmost active screen. /// </summary> public class ScreenManager : DrawableGameComponent { readonly List<GameScreen> _screens = new List<GameScreen>(); readonly List<GameScreen> _screensToUpdate = new List<GameScreen>(); readonly InputState _input = new InputState(); SpriteBatch _spriteBatch; SpriteFont _font; Texture2D _blankTexture; bool _isInitialized; bool _traceEnabled; /// <summary> /// A default SpriteBatch shared by all the screens. This saves /// each screen having to bother creating their own local instance. /// </summary> public SpriteBatch SpriteBatch { get { return _spriteBatch; } } /// <summary> /// A default font shared by all the screens. This saves /// each screen having to bother loading their own local copy. /// </summary> public SpriteFont Font { get { return _font; } } /// <summary> /// If true, the manager prints out a list of all the screens /// each time it is updated. This can be useful for making sure /// everything is being added and removed at the right times. /// </summary> public bool TraceEnabled { get { return _traceEnabled; } set { _traceEnabled = value; } } /// <summary> /// Constructs a new screen manager component. /// </summary> public ScreenManager(Game game) : base(game) { // we must set EnabledGestures before we can query for them, but // we don't assume the game wants to read them. TouchPanel.EnabledGestures = GestureType.None; } /// <summary> /// Initializes the screen manager component. /// </summary> public override void Initialize() { base.Initialize(); _isInitialized = true; } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { // Load content belonging to the screen manager. var content = Game.Content; _spriteBatch = new SpriteBatch(GraphicsDevice); _font = content.Load<SpriteFont>("Fonts/Menu"); _blankTexture = content.Load<Texture2D>("Menu/Blank"); // Tell each of the screens to load their content. foreach (GameScreen screen in _screens) { screen.LoadContent(); } } /// <summary> /// Unload your graphics content. /// </summary> protected override void UnloadContent() { // Tell each of the screens to unload their content. foreach (GameScreen screen in _screens) { screen.UnloadContent(); } } /// <summary> /// Allows each screen to run logic. /// </summary> public override void Update(GameTime gameTime) { // Read the keyboard and gamepad. _input.Update(); Souris.Get().Update(Mouse.GetState()); Clavier.Get().Update(Keyboard.GetState()); // Make a copy of the master screen list, to avoid confusion if // the process of updating one screen adds or removes others. _screensToUpdate.Clear(); foreach (GameScreen screen in _screens) _screensToUpdate.Add(screen); bool otherScreenHasFocus = !Game.IsActive; bool coveredByOtherScreen = false; // Loop as long as there are screens waiting to be updated. while (_screensToUpdate.Count > 0) { // Pop the topmost screen off the waiting list. GameScreen screen = _screensToUpdate[_screensToUpdate.Count - 1]; _screensToUpdate.RemoveAt(_screensToUpdate.Count - 1); // Update the screen. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (screen.ScreenState == ScreenState.TransitionOn || screen.ScreenState == ScreenState.Active) { // If this is the first active screen we came across, // give it a chance to handle input. if (!otherScreenHasFocus) { screen.HandleInput(_input); otherScreenHasFocus = true; } // If this is an active non-popup, inform any subsequent // screens that they are covered by it. if (!screen.IsPopup) coveredByOtherScreen = true; } } // Print debug trace? if (_traceEnabled) TraceScreens(); } /// <summary> /// Prints a list of all the screens, for debugging. /// </summary> void TraceScreens() { Debug.WriteLine(string.Join(", ", _screens.Select(screen => screen.GetType().Name).ToArray())); } /// <summary> /// Tells each screen to draw itself. /// </summary> public override void Draw(GameTime gameTime) { foreach (GameScreen screen in _screens) { if (screen.ScreenState == ScreenState.Hidden) continue; screen.Draw(gameTime); } } /// <summary> /// Adds a new screen to the screen manager. /// </summary> public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer) { screen.ControllingPlayer = controllingPlayer; screen.ScreenManager = this; screen.IsExiting = false; // If we have a graphics device, tell the screen to load content. if (_isInitialized) { screen.LoadContent(); } _screens.Add(screen); // update the TouchPanel to respond to gestures this screen is interested in TouchPanel.EnabledGestures = screen.EnabledGestures; } /// <summary> /// Removes a screen from the screen manager. You should normally /// use GameScreen.ExitScreen instead of calling this directly, so /// the screen can gradually transition off rather than just being /// instantly removed. /// </summary> public void RemoveScreen(GameScreen screen) { // If we have a graphics device, tell the screen to unload content. if (_isInitialized) { screen.UnloadContent(); } _screens.Remove(screen); _screensToUpdate.Remove(screen); // if there is a screen still in the manager, update TouchPanel // to respond to gestures that screen is interested in. if (_screens.Count > 0) { TouchPanel.EnabledGestures = _screens[_screens.Count - 1].EnabledGestures; } } /// <summary> /// Expose an array holding all the screens. We return a copy rather /// than the real master list, because screens should only ever be added /// or removed using the AddScreen and RemoveScreen methods. /// </summary> public GameScreen[] GetScreens() { return _screens.ToArray(); } /// <summary> /// Helper draws a translucent black fullscreen sprite, used for fading /// screens in and out, and for darkening the background behind popups. /// </summary> public void FadeBackBufferToBlack(float alpha) { Viewport viewport = GraphicsDevice.Viewport; _spriteBatch.Begin(); _spriteBatch.Draw(_blankTexture, new Rectangle(0, 0, viewport.Width, viewport.Height), Color.Black * alpha); _spriteBatch.End(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using Cormo.Contexts; using Cormo.Impl.Utils; using Cormo.Impl.Weld.Catch; using Cormo.Impl.Weld.Components; using Cormo.Impl.Weld.Contexts; using Cormo.Impl.Weld.Injections; using Cormo.Impl.Weld.Introspectors; using Cormo.Impl.Weld.Resolutions; using Cormo.Impl.Weld.Serialization; using Cormo.Impl.Weld.Utils; using Cormo.Impl.Weld.Validations; using Cormo.Injects; namespace Cormo.Impl.Weld { public class WeldComponentManager : IComponentManager, IServiceRegistry { public WeldComponentManager(string id) { Id = id; _services.Add(typeof(ContextualStore), _contextualStore = new ContextualStore()); _services.Add(typeof(CurrentInjectionPoint), _currentInjectionPoint = new CurrentInjectionPoint()); _componentResolver = new ComponentResolver(this, _registeredComponents); _observerResolver = new ObserverResolver(this, _registeredObservers); } private readonly List<IWeldComponent> _registeredComponents = new List<IWeldComponent>(); private readonly List<EventObserverMethod> _registeredObservers = new List<EventObserverMethod>(); private readonly ComponentResolver _componentResolver; private readonly ObserverResolver _observerResolver; private MixinResolver _mixinResolver; private InterceptorResolver _interceptorResolver; private readonly ConcurrentDictionary<Type, IList<IContext>> _contexts = new ConcurrentDictionary<Type, IList<IContext>>(); private readonly IContextualStore _contextualStore; private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); private readonly CurrentInjectionPoint _currentInjectionPoint; public IContextualStore ContextualStore { get { return _contextualStore; } } public Mixin[] GetMixins(IComponent component) { if (_mixinResolver == null) throw new InvalidOperationException("Weld component manager is not yet deployed"); return _mixinResolver.Resolve(new MixinResolvable(component)).ToArray(); } public IEnumerable<IComponent> GetComponents(Type type, IQualifier[] qualifierArray) { return _componentResolver.Resolve(new ComponentResolvable(type, qualifierArray)); } public IComponent GetComponent(Type type, params IQualifier[] qualifiers) { qualifiers = qualifiers.DefaultIfEmpty(DefaultAttribute.Instance).ToArray(); var components = GetComponents(type, qualifiers).ToArray(); ResolutionValidator.ValidateSingleResult(type, qualifiers, components); return components.Single(); } public IComponent GetComponent(IInjectionPoint injectionPoint) { var components = GetComponents(injectionPoint.ComponentType, injectionPoint.Qualifiers.ToArray()).ToArray(); ResolutionValidator.ValidateSingleResult(injectionPoint, components); return components.Single(); } public object GetReference(IComponent component, ICreationalContext creationalContext, params Type[] proxyTypes) { return GetReference(null, component, creationalContext, proxyTypes); } public ICreationalContext CreateCreationalContext(IContextual contextual) { return new WeldCreationalContext(contextual); } public void Deploy(WeldEnvironment environment) { environment.AddValue(this, new IAnnotation[0], this); environment.AddValue(new ContextualStore(), new IAnnotation[0], this); var mixins = environment.Components.OfType<Mixin>().ToArray(); var interceptors = environment.Components.OfType<Interceptor>().ToArray(); _registeredComponents.AddRange(environment.Components.Except(mixins).Except(interceptors)); _componentResolver.Invalidate(); AddObservers(environment.Observers); _mixinResolver = new MixinResolver(this, mixins); _interceptorResolver = new InterceptorResolver(this, interceptors); _services.Add(typeof(IExceptionHandlerDispatcher), new ExceptionHandlerDispatcher(this, environment.ExceptionHandlers)); _componentResolver.Validate(); ExecuteConfigurations(environment); } private void ExecuteConfigurations(WeldEnvironment environment) { foreach (var config in environment.Configurations.OrderBy(x=> x.Type.Name)) { GetReference(config, CreateCreationalContext(config)); } } public object GetInjectableReference(IInjectionPoint injectionPoint, ICreationalContext creationalContext) { var proxyTypes = new []{injectionPoint.ComponentType}; var weldIp = injectionPoint as IWeldInjetionPoint; if (weldIp != null && weldIp.Unwraps) proxyTypes = new Type[0]; return GetReference(injectionPoint, injectionPoint.Component, creationalContext, proxyTypes); } private object GetReference(IInjectionPoint injectionPoint, IComponent component, ICreationalContext creationalContext, params Type[] proxyTypes) { var pushInjectionPoint = injectionPoint != null && injectionPoint.ComponentType != typeof (IInjectionPoint); try { if (pushInjectionPoint) _currentInjectionPoint.Push(injectionPoint); if (proxyTypes.Any() && component.IsProxyRequired) { foreach(var proxyType in proxyTypes) InjectionValidator.ValidateProxiable(proxyType, injectionPoint); return CormoProxyGenerator.CreateProxy(proxyTypes, () => { try { if (pushInjectionPoint) _currentInjectionPoint.Push(injectionPoint); return GetReference(injectionPoint, component, creationalContext, new Type[0]); } finally { if (pushInjectionPoint) _currentInjectionPoint.Pop(); } }); } var context = creationalContext as IWeldCreationalContext; if (context != null) { var incompleteInstance = context.GetIncompleteInstance(component); if (incompleteInstance != null) return incompleteInstance; } creationalContext = creationalContext.GetCreationalContext(component); return GetContext(component.Scope).Get(component, creationalContext); } finally { if (pushInjectionPoint) _currentInjectionPoint.Pop(); } } //public T GetReference<T>(params IQualifier[] qualifiers) //{ // return (T)GetReference(typeof(T), qualifiers); //} //public object GetReference(Type type, params IQualifier[] qualifiers) //{ // var component = GetComponent(type, qualifiers); // return GetReference(component, CreateCreationalContext(component)); //} public string Id { get; private set; } public void AddContext(IContext context) { _services.Add(context.GetType(), context); _contexts.GetOrAdd(context.Scope, _=> new List<IContext>()).Add(context); } public T GetService<T>() { return (T) _services.GetOrDefault(typeof (T)); } public IContext GetContext(Type scope) { IList<IContext> contexts; if(!_contexts.TryGetValue(scope, out contexts)) throw new ContextNotActiveException(scope); var activeContexts = contexts.Where(x => x.IsActive).ToArray(); if(!activeContexts.Any()) throw new ContextNotActiveException(scope); if (activeContexts.Count() > 1) throw new ContextException(string.Format("Duplicate contexts: [{0}]", scope.Name)); return activeContexts.Single(); } public Interceptor[] GetMethodInterceptors(Type interceptorType, MethodInfo methodInfo) { if (_interceptorResolver == null) throw new InvalidOperationException("Weld component manager is not yet deployed"); var resolvable = new InterceptorResolvable(interceptorType, methodInfo); var interceptors = _interceptorResolver.Resolve(resolvable).ToArray(); if (interceptors.Any()) InterceptionValidator.ValidateInterceptableMethod(methodInfo, resolvable); return interceptors; } public Interceptor[] GetPropertyInterceptors(Type interceptorType, PropertyInfo property, out MethodInfo[] methods) { if (_interceptorResolver == null) throw new InvalidOperationException("Weld component manager is not yet deployed"); var resolvable = new InterceptorResolvable(interceptorType, property); var interceptors = _interceptorResolver.Resolve(resolvable).ToArray(); if (interceptors.Any()) { methods = new[] {property.SetMethod, property.GetMethod}.Where(x => x != null).ToArray(); foreach(var method in methods) InterceptionValidator.ValidateInterceptableMethod(method, resolvable); } else methods = new MethodInfo[0]; return interceptors; } public Interceptor[] GetClassInterceptors(Type interceptorType, IComponent component, out MethodInfo[] methods) { if (_interceptorResolver == null) throw new InvalidOperationException("Weld component manager is not yet deployed"); var intercetorResolvable = new InterceptorResolvable(interceptorType, component); var interceptors = _interceptorResolver.Resolve(intercetorResolvable).ToArray(); var allowPartial = interceptors.All(x => x.AllowPartialInterception); if (interceptors.Any()) InterceptionValidator.ValidateInterceptableClass(component.Type, intercetorResolvable, allowPartial, out methods); else methods = new MethodInfo[0]; return interceptors; } public IEnumerable<EventObserverMethod> ResolveObservers(Type eventType, IQualifiers qualifiers) { return _observerResolver.Resolve(new ObserverResolvable(eventType, qualifiers)); } public void FireEvent<T>(T ev, IQualifiers qualifiers) { foreach (var observer in ResolveObservers(typeof (T), qualifiers)) observer.Notify(ev); } public void AddExtensions(IEnumerable<ExtensionComponent> extensions) { _registeredComponents.AddRange(extensions); _componentResolver.Invalidate(); } public void AddObservers(IEnumerable<EventObserverMethod> observers) { _registeredObservers.AddRange(observers); _observerResolver.Invalidate(); } } }
// Copyright 2017 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 // // 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 UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class omniPlug : manipObject { public GameObject mouseoverFeedback; public int ID = -1; public bool outputPlug = false; public omniJack connected; Color cordColor; LineRenderer lr; Material mat; Transform plugTrans; List<Vector3> plugPath = new List<Vector3>(); public omniPlug otherPlug; Vector3 lastPos = Vector3.zero; Vector3 lastOtherPlugPos = Vector3.zero; float calmTime = 0; public signalGenerator signal; List<omniJack> targetJackList = new List<omniJack>(); List<Transform> collCandidates = new List<Transform>(); masterControl.WireMode wireType = masterControl.WireMode.Curved; public override void Awake() { base.Awake(); gameObject.layer = 12; //jacks mat = transform.GetChild(0).GetChild(0).GetComponent<Renderer>().material; lr = GetComponent<LineRenderer>(); cordColor = new Color(Random.value, Random.value, Random.value); lr.material.SetColor("_TintColor", cordColor); mat.SetColor("_TintColor", cordColor); mouseoverFeedback.GetComponent<Renderer>().material.SetColor("_TintColor", cordColor); mouseoverFeedback.SetActive(false); plugTrans = transform.GetChild(0); if (masterControl.instance != null) { if (!masterControl.instance.jacksEnabled) GetComponent<Collider>().enabled = false; } } public void Setup(float c, bool outputting, omniPlug other) { Color jackColor = Color.HSVToRGB(c, .8f, .5f); cordColor = Color.HSVToRGB(c, .8f, .2f); mat.SetColor("_TintColor", jackColor); mouseoverFeedback.GetComponent<Renderer>().material.SetColor("_TintColor", jackColor); wireType = masterControl.instance.WireSetting; outputPlug = outputting; otherPlug = other; if (outputPlug) { lr.material.SetColor("_TintColor", cordColor); plugPath.Add(otherPlug.transform.position); updateLineVerts(); lastOtherPlugPos = otherPlug.transform.position; } } public void setLineColor(Color c) { cordColor = c; lr.material.SetColor("_TintColor", c); } public void Activate(omniPlug siblingPlug, omniJack jackIn, Vector3[] tempPath, Color tempColor) { float h, s, v; Color.RGBToHSV(tempColor, out h, out s, out v); Color c1 = Color.HSVToRGB(h, .8f, .5f); Color c2 = Color.HSVToRGB(h, .8f, .2f); cordColor = tempColor; lr.material.SetColor("_TintColor", c2); mat.SetColor("_TintColor", c1); mouseoverFeedback.GetComponent<Renderer>().material.SetColor("_TintColor", c1); if (outputPlug) { plugPath = tempPath.ToList<Vector3>(); updateLineVerts(); calmTime = 1; } otherPlug = siblingPlug; connected = jackIn; connected.beginConnection(this); signal = connected.homesignal; plugTrans.position = connected.transform.position; plugTrans.rotation = connected.transform.rotation; plugTrans.parent = connected.transform; plugTrans.Rotate(-90, 0, 0); plugTrans.Translate(0, 0, -.02f); transform.parent = plugTrans.parent; transform.position = plugTrans.position; transform.rotation = plugTrans.rotation; plugTrans.parent = transform; lastOtherPlugPos = otherPlug.plugTrans.transform.position; lastPos = transform.position; } public PlugData GetData() { PlugData data = new PlugData(); data.ID = transform.GetInstanceID(); data.position = transform.position; data.rotation = transform.rotation; data.scale = transform.localScale; data.outputPlug = outputPlug; data.connected = connected.transform.GetInstanceID(); data.otherPlug = otherPlug.transform.GetInstanceID(); data.plugPath = plugPath.ToArray(); data.cordColor = cordColor; return data; } void Update() { if (otherPlug == null) { if (lr) lr.numPositions = 0; Destroy(gameObject); return; } bool noChange = true; if (curState == manipState.grabbed) { if (collCandidates.Contains(closestJack)) { if (connected == null) updateConnection(closestJack.GetComponent<omniJack>()); else if (closestJack != connected.transform) { updateConnection(closestJack.GetComponent<omniJack>()); } } if (connected != null) { if (!collCandidates.Contains(connected.transform)) { endConnection(); } } } bool updateLineNeeded = false; if (lastPos != transform.position) { findClosestJack(); if (connected != null) transform.LookAt(connected.transform.position); else if (closestJack != null) transform.LookAt(closestJack.position); updateLineNeeded = true; lastPos = transform.position; } if (outputPlug) { if ((curState != manipState.grabbed && otherPlug.curState != manipState.grabbed) && (Vector3.Distance(plugPath.Last(), transform.position) > .002f) && (Vector3.Distance(plugPath[0], transform.position) > .002f)) { Vector3 a = plugTrans.position - plugPath.Last(); Vector3 b = otherPlug.plugTrans.transform.position - plugPath[0]; for (int i = 0; i < plugPath.Count; i++) plugPath[i] += Vector3.Lerp(b, a, (float)i / (plugPath.Count - 1)); noChange = false; } if (updateLineNeeded) { if (Vector3.Distance(plugPath.Last(), transform.position) > .005f) { plugPath.Add(plugTrans.position); calmTime = 0; noChange = false; } } if (plugPath[0] != otherPlug.plugTrans.transform.position) { if (Vector3.Distance(plugPath[0], transform.position) > .005f) { plugPath.Insert(0, otherPlug.plugTrans.transform.position); calmTime = 0; noChange = false; } } lrFlowEffect(); if (!noChange) { calming(); updateLineVerts(); } updateLineVerts(); if (noChange) calmLine(); } } float flowVal = 0; void lrFlowEffect() { flowVal = Mathf.Repeat(flowVal - Time.deltaTime, 1); lr.material.mainTextureOffset = new Vector2(flowVal, 0); lr.material.SetFloat("_EmissionGain", .6f); } Transform closestJack; float jackDist = 0; void findClosestJack() { Transform t = null; float closest = Mathf.Infinity; bool shouldUpdateList = false; foreach (omniJack j in targetJackList) { if (j == null) shouldUpdateList = true; else if (j.near == null || j.near == this) { float z = Vector3.Distance(transform.position, j.transform.position); if (z < closest) { closest = z; t = j.transform; } } } if (shouldUpdateList) updateJackList(); jackDist = closest; closestJack = t; } float calmingConstant = .5f; void calming() { for (int i = 0; i < plugPath.Count; i++) { if (i != 0 && i != plugPath.Count - 1) { Vector3 dest = (plugPath[i - 1] + plugPath[i] + plugPath[i + 1]) / 3; plugPath[i] = Vector3.Lerp(plugPath[i], dest, calmingConstant); } } for (int i = 0; i < plugPath.Count; i++) { if (i != 0 && i != plugPath.Count - 1) { if (Vector3.Distance(plugPath[i - 1], plugPath[i]) < .01f) plugPath.RemoveAt(i); } } updateLineVerts(); } public void OnDestroy() { } void calmLine() { if (calmTime == 1) { return; } Vector3 beginPoint = plugPath[0]; Vector3 endPoint = plugPath.Last(); calmTime = Mathf.Clamp01(calmTime + Time.deltaTime / 1.5f); for (int i = 0; i < plugPath.Count; i++) { if (i != 0 && i != plugPath.Count - 1) { Vector3 dest = (plugPath[i - 1] + plugPath[i] + plugPath[i + 1]) / 3; plugPath[i] = Vector3.Lerp(plugPath[i], dest, Mathf.Lerp(calmingConstant, 0, calmTime)); } } for (int i = 0; i < plugPath.Count; i++) { if (i != 0 && i != plugPath.Count - 1) { if (Vector3.Distance(plugPath[i - 1], plugPath[i]) < .01f) plugPath.RemoveAt(i); } } plugPath[0] = beginPoint; plugPath[plugPath.Count - 1] = endPoint; updateLineVerts(); } public void updateLineType(masterControl.WireMode num) { wireType = num; updateLineVerts(); } bool forcedWireShow = false; void updateLineVerts(bool justLast = false) { if (wireType == masterControl.WireMode.Curved) { lr.numPositions = plugPath.Count; if (justLast) lr.SetPosition(plugPath.Count - 1, plugPath.Last()); else lr.SetPositions(plugPath.ToArray()); } else if (wireType == masterControl.WireMode.Straight && plugPath.Count > 2) { lr.numPositions = 2; lr.SetPosition(0, plugPath[0]); lr.SetPosition(1, plugPath.Last()); } else if (forcedWireShow) { lr.numPositions = 2; lr.SetPosition(0, plugPath[0]); lr.SetPosition(1, plugPath.Last()); } else { lr.numPositions = 0; } } void updateJackList() { targetJackList.Clear(); omniJack[] possibleJacks = FindObjectsOfType<omniJack>(); for (int i = 0; i < possibleJacks.Length; i++) { if (possibleJacks[i].outgoing != outputPlug) { if (otherPlug.connected == null) { targetJackList.Add(possibleJacks[i]); } else if (otherPlug.connected.transform.parent != possibleJacks[i].transform.parent) { targetJackList.Add(possibleJacks[i]); } } } } public void Destruct() { Destroy(gameObject); } public void Release() { foreach (omniJack j in targetJackList) j.flash(Color.black); if (connected == null) { if (lr) lr.numPositions = 0; otherPlug.Destruct(); Destroy(gameObject); } else { if (plugTrans.parent != connected.transform) { plugTrans.position = connected.transform.position; plugTrans.rotation = connected.transform.rotation; plugTrans.parent = connected.transform; plugTrans.Rotate(-90, 0, 0); plugTrans.Translate(0, 0, -.02f); } transform.parent = plugTrans.parent; transform.position = plugTrans.position; transform.rotation = plugTrans.rotation; plugTrans.parent = transform; calmTime = 0; } collCandidates.Clear(); } void OnCollisionEnter(Collision coll) { if (curState != manipState.grabbed) return; if (coll.transform.tag != "omnijack") return; omniJack j = coll.transform.GetComponent<omniJack>(); if (!targetJackList.Contains(j)) return; if (j.signal != null || j.near != null) return; collCandidates.Add(j.transform); } void updateConnection(omniJack j) { if (connected == j) return; if (connected != null) endConnection(); if (manipulatorObjScript != null) manipulatorObjScript.hapticPulse(1000); connected = j; connected.beginConnection(this); signal = connected.homesignal; plugTrans.position = connected.transform.position; plugTrans.rotation = connected.transform.rotation; plugTrans.parent = connected.transform; plugTrans.Rotate(-90, 0, 0); plugTrans.Translate(0, 0, -.02f); } void OnCollisionExit(Collision coll) { omniJack j = coll.transform.GetComponent<omniJack>(); if (j != null) { if (collCandidates.Contains(coll.transform)) collCandidates.Remove(coll.transform); } } void endConnection() { connected.endConnection(); connected = null; plugTrans.parent = transform; plugTrans.localPosition = Vector3.zero; plugTrans.localRotation = Quaternion.identity; } public void updateForceWireShow(bool on) { if (outputPlug) { forcedWireShow = on; updateLineVerts(); } else { otherPlug.updateForceWireShow(on); } } public void mouseoverEvent(bool on) { mouseoverFeedback.SetActive(on); if (!on && curState == manipState.none) { updateForceWireShow(false); } else updateForceWireShow(true); } public override void setState(manipState state) { if (curState == state) return; if (curState == manipState.selected) { mouseoverFeedback.SetActive(false); } if (curState == manipState.grabbed) { Release(); } curState = state; if (curState == manipState.none) { updateForceWireShow(false); } if (curState == manipState.selected) { updateForceWireShow(true); mouseoverFeedback.SetActive(true); } if (curState == manipState.grabbed) { updateForceWireShow(true); collCandidates.Clear(); if (connected != null) collCandidates.Add(connected.transform); transform.parent = manipulatorObj; updateJackList(); foreach (omniJack j in targetJackList) j.flash(cordColor); } } }
#pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.scene.ucore { public class WardsUCore : global::UnityEngine.MonoBehaviour, global::haxe.lang.IHxObject, global::pony.IWards { public WardsUCore(global::haxe.lang.EmptyObject empty) : base() { unchecked { } #line default } public WardsUCore() : base() { unchecked { #line 60 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.rn = ((float) (0) ); #line 52 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.currentPos = -1; #line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.speed = ((float) (200) ); #line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.withTimeScale = true; #line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.withRotation = true; #line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.change = new global::pony.events.Signal(((object) (this) )); object __temp_stmt634 = default(object); #line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" { #line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("changeHandler"), ((int) (648696890) ))) ), 1); #line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" __temp_stmt634 = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false); } #line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.change.@add(__temp_stmt634, default(global::haxe.lang.Null<int>)); this.changed = new global::pony.events.Signal(((object) (this) )); } #line default } public static object __hx_createEmpty() { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return new global::pony.unity3d.scene.ucore.WardsUCore(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static object __hx_create(global::Array arr) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return new global::pony.unity3d.scene.ucore.WardsUCore(); } #line default } public bool withRotation; public bool withTimeScale; public float speed; public int currentPos; public global::pony.events.Signal change; public global::pony.events.Signal changed; public global::UnityEngine.GameObject target; public global::Array<object> wards; public global::haxe.lang.Null<int> toN; public global::UnityEngine.Transform toObj; public float rn; public virtual void Start() { unchecked { #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" if (( this.target == default(global::UnityEngine.GameObject) )) { #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.target = global::hugs.GameObjectMethods.getChildGameObject(this.gameObject, "obj"); } #line 73 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.wards = new global::Array<object>(new object[]{}); { #line 74 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" int _g = 1; #line 74 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" while (( _g < 10000 )) { #line 74 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" int i = _g++; global::UnityEngine.Transform t = this.transform.Find(global::Std.@string(i)); if (( t == default(global::UnityEngine.Transform) )) { #line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" break; } this.wards.push(t); } } #line 79 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" { #line 79 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" global::pony.events.Signal _this = this.change; #line 79 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" _this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{0})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 79 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" global::pony.events.Signal __temp_expr629 = _this; } } #line default } public virtual void changeHandler(int n) { unchecked { #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" if (( n == this.currentPos )) { #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ; } this.currentPos = n; this.toN = new global::haxe.lang.Null<int>(new global::haxe.lang.Null<int>(n, true).@value, true); this.toObj = ((global::UnityEngine.Transform) (this.wards[n]) ); } #line default } public void @goto(int n) { unchecked { #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" global::pony.events.Signal _this = this.change; #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" _this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{n})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" global::pony.events.Signal __temp_expr630 = _this; } #line default } public virtual void Update() { unchecked { #line 93 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" if (( this.toObj == default(global::UnityEngine.Transform) )) { #line 93 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ; } float dt = default(float); #line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" if (this.withTimeScale) { #line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" dt = global::UnityEngine.Time.deltaTime; } else { #line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" dt = global::UnityEngine.Time.fixedDeltaTime; } global::UnityEngine.Vector3 p = this.toObj.position; global::UnityEngine.Quaternion r = this.toObj.rotation; this.target.transform.position = global::UnityEngine.Vector3.MoveTowards(this.target.transform.position, p, ( this.speed * dt )); if (this.withRotation) { this.target.transform.rotation = global::UnityEngine.Quaternion.Slerp(this.target.transform.rotation, r, ( ( this.speed * (this.rn += ( this.speed * 2 )) ) * dt )); } if (( this.target.transform.position == p )) { #line 102 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.toN = new global::haxe.lang.Null<int>(default(global::haxe.lang.Null<int>).@value, true); this.toObj = default(global::UnityEngine.Transform); this.rn = ((float) (0) ); #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" { #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" global::pony.events.Signal _this = this.changed; #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" _this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{this.currentPos})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" global::pony.events.Signal __temp_expr631 = _this; } } } #line default } public virtual void goNext() { unchecked { #line 111 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" if (( this.currentPos < ( this.wards.length - 1 ) )) { global::pony.events.Signal _this = this.change; #line 112 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" _this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{( this.currentPos + 1 )})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 112 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" global::pony.events.Signal __temp_expr632 = _this; } } #line default } public virtual void goPrev() { unchecked { #line 117 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" if (( this.currentPos > 0 )) { global::pony.events.Signal _this = this.change; #line 118 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" _this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{( this.currentPos - 1 )})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 118 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" global::pony.events.Signal __temp_expr633 = _this; } } #line default } public virtual bool __hx_deleteField(string field, int hash) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return false; } #line default } public virtual object __hx_lookupField(string field, int hash, bool throwErrors, bool isCheck) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" if (isCheck) { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return global::haxe.lang.Runtime.undefined; } else { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" if (throwErrors) { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" throw global::haxe.lang.HaxeException.wrap("Field not found."); } else { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return default(object); } } } #line default } public virtual double __hx_lookupField_f(string field, int hash, bool throwErrors) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" if (throwErrors) { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" throw global::haxe.lang.HaxeException.wrap("Field not found or incompatible field type."); } else { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return default(double); } } #line default } public virtual object __hx_lookupSetField(string field, int hash, object @value) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing."); } #line default } public virtual double __hx_lookupSetField_f(string field, int hash, double @value) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing or incompatible type."); } #line default } public virtual double __hx_setField_f(string field, int hash, double @value, bool handleProperties) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" switch (hash) { case 25532: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.rn = ((float) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 1194336987: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.currentPos = ((int) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 23697287: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.speed = ((float) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } default: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.__hx_lookupSetField_f(field, hash, @value); } } } #line default } public virtual object __hx_setField(string field, int hash, object @value, bool handleProperties) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" switch (hash) { case 1575675685: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.hideFlags = ((global::UnityEngine.HideFlags) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 1224700491: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.name = global::haxe.lang.Runtime.toString(@value); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 5790298: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.tag = global::haxe.lang.Runtime.toString(@value); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 373703110: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.active = ((bool) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 2117141633: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.enabled = ((bool) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 896046654: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.useGUILayout = ((bool) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 25532: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.rn = ((float) (global::haxe.lang.Runtime.toInt(@value)) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 337002812: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.toObj = ((global::UnityEngine.Transform) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 5793395: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.toN = new global::haxe.lang.Null<int>(global::haxe.lang.Null<object>.ofDynamic<int>(@value).@value, true); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 1159959223: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.wards = ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (@value) ))) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 116192081: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.target = ((global::UnityEngine.GameObject) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 1288483060: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.changed = ((global::pony.events.Signal) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 930255216: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.change = ((global::pony.events.Signal) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 1194336987: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.currentPos = ((int) (global::haxe.lang.Runtime.toInt(@value)) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 23697287: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.speed = ((float) (global::haxe.lang.Runtime.toInt(@value)) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 916069463: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.withTimeScale = ((bool) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } case 557770084: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.withRotation = ((bool) (@value) ); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return @value; } default: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.__hx_lookupSetField(field, hash, @value); } } } #line default } public virtual object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" switch (hash) { case 1826409040: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetType"), ((int) (1826409040) ))) ); } case 304123084: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("ToString"), ((int) (304123084) ))) ); } case 276486854: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetInstanceID"), ((int) (276486854) ))) ); } case 295397041: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetHashCode"), ((int) (295397041) ))) ); } case 1955029599: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Equals"), ((int) (1955029599) ))) ); } case 1575675685: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.hideFlags; } case 1224700491: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.name; } case 294420221: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessageUpwards"), ((int) (294420221) ))) ); } case 139469119: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessage"), ((int) (139469119) ))) ); } case 967979664: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentsInChildren"), ((int) (967979664) ))) ); } case 2122408236: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponents"), ((int) (2122408236) ))) ); } case 1328964235: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentInChildren"), ((int) (1328964235) ))) ); } case 1723652455: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponent"), ((int) (1723652455) ))) ); } case 89600725: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CompareTag"), ((int) (89600725) ))) ); } case 2134927590: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("BroadcastMessage"), ((int) (2134927590) ))) ); } case 5790298: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.tag; } case 373703110: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.active; } case 1471506513: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.gameObject; } case 1751728597: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.particleSystem; } case 524620744: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.particleEmitter; } case 964013983: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.hingeJoint; } case 1238753076: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.collider; } case 674101152: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.guiTexture; } case 262266241: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.guiElement; } case 1515196979: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.networkView; } case 801759432: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.guiText; } case 662730966: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.audio; } case 853263683: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.renderer; } case 1431885287: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.constantForce; } case 1261760260: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.animation; } case 1962709206: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.light; } case 931940005: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.camera; } case 1895479501: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.rigidbody; } case 1167273324: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.transform; } case 2117141633: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.enabled; } case 2084823382: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopCoroutine"), ((int) (2084823382) ))) ); } case 1856815770: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopAllCoroutines"), ((int) (1856815770) ))) ); } case 832859768: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine_Auto"), ((int) (832859768) ))) ); } case 987108662: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine"), ((int) (987108662) ))) ); } case 602588383: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("IsInvoking"), ((int) (602588383) ))) ); } case 1641152943: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("InvokeRepeating"), ((int) (1641152943) ))) ); } case 1416948632: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Invoke"), ((int) (1416948632) ))) ); } case 757431474: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CancelInvoke"), ((int) (757431474) ))) ); } case 896046654: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.useGUILayout; } case 1299478843: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goPrev"), ((int) (1299478843) ))) ); } case 1276657467: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goNext"), ((int) (1276657467) ))) ); } case 999946793: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Update"), ((int) (999946793) ))) ); } case 1147771299: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goto"), ((int) (1147771299) ))) ); } case 648696890: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("changeHandler"), ((int) (648696890) ))) ); } case 389604418: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Start"), ((int) (389604418) ))) ); } case 25532: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.rn; } case 337002812: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.toObj; } case 5793395: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return (this.toN).toDynamic(); } case 1159959223: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.wards; } case 116192081: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.target; } case 1288483060: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.changed; } case 930255216: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.change; } case 1194336987: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.currentPos; } case 23697287: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.speed; } case 916069463: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.withTimeScale; } case 557770084: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.withRotation; } default: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.__hx_lookupField(field, hash, throwErrors, isCheck); } } } #line default } public virtual double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" switch (hash) { case 25532: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((double) (this.rn) ); } case 1194336987: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((double) (this.currentPos) ); } case 23697287: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((double) (this.speed) ); } default: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return this.__hx_lookupField_f(field, hash, throwErrors); } } } #line default } public virtual object __hx_invokeField(string field, int hash, global::Array dynargs) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" switch (hash) { case 757431474:case 1416948632:case 1641152943:case 602588383:case 987108662:case 832859768:case 1856815770:case 2084823382:case 2134927590:case 89600725:case 1723652455:case 1328964235:case 2122408236:case 967979664:case 139469119:case 294420221:case 1955029599:case 295397041:case 276486854:case 304123084:case 1826409040: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return global::haxe.lang.Runtime.slowCallField(this, field, dynargs); } case 1299478843: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.goPrev(); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" break; } case 1276657467: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.goNext(); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" break; } case 999946793: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.Update(); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" break; } case 1147771299: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.@goto(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) )); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" break; } case 648696890: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.changeHandler(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) )); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" break; } case 389604418: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" this.Start(); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" break; } default: { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return ((global::haxe.lang.Function) (this.__hx_getField(field, hash, true, false, false)) ).__hx_invokeDynamic(dynargs); } } #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" return default(object); } #line default } public virtual void __hx_getFields(global::Array<object> baseArr) { unchecked { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("hideFlags"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("name"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("tag"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("active"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("gameObject"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("particleSystem"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("particleEmitter"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("hingeJoint"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("collider"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("guiTexture"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("guiElement"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("networkView"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("guiText"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("audio"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("renderer"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("constantForce"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("animation"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("light"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("camera"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("rigidbody"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("transform"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("enabled"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("useGUILayout"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("rn"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("toObj"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("toN"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("wards"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("target"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("changed"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("change"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("currentPos"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("speed"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("withTimeScale"); #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/ucore/WardsUCore.hx" baseArr.push("withRotation"); } #line default } } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates <see cref="IGrainMethodInvoker"/> for grains. /// </summary> internal static class GrainMethodInvokerGenerator { /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "MethodInvoker"; /// <summary> /// Returns the name of the generated class for the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>The name of the generated class for the provided type.</returns> internal static string GetGeneratedClassName(Type type) => CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(type) + ClassSuffix; /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="grainType">The grain interface type.</param> /// <param name="className">The name for the generated class.</param> /// <returns> /// The generated class. /// </returns> internal static TypeDeclarationSyntax GenerateClass(Type grainType, string className) { var baseTypes = new List<BaseTypeSyntax> { SF.SimpleBaseType(typeof(IGrainMethodInvoker).GetTypeSyntax()) }; var genericTypes = grainType.IsGenericTypeDefinition ? grainType.GetGenericArguments() .Select(_ => SF.TypeParameter(_.ToString())) .ToArray() : new TypeParameterSyntax[0]; // Create the special method invoker marker attribute. var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(grainType); var interfaceIdArgument = SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)); var grainTypeArgument = SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false)); var attributes = new List<AttributeSyntax> { CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(MethodInvokerAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(grainTypeArgument), SF.AttributeArgument(interfaceIdArgument)), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()) }; var members = new List<MemberDeclarationSyntax>(GenerateGenericInvokerFields(grainType)) { GenerateInvokeMethod(grainType), GenerateInterfaceIdProperty(grainType), GenerateInterfaceVersionProperty(grainType), }; // If this is an IGrainExtension, make the generated class implement IGrainExtensionMethodInvoker. if (typeof(IGrainExtension).IsAssignableFrom(grainType)) { baseTypes.Add(SF.SimpleBaseType(typeof(IGrainExtensionMethodInvoker).GetTypeSyntax())); members.Add(GenerateExtensionInvokeMethod(grainType)); } var classDeclaration = SF.ClassDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddBaseListTypes(baseTypes.ToArray()) .AddConstraintClauses(grainType.GetTypeConstraintSyntax()) .AddMembers(members.ToArray()) .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray())); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } return classDeclaration; } /// <summary> /// Returns method declaration syntax for the InterfaceId property. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>Method declaration syntax for the InterfaceId property.</returns> private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType) { var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceId); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType))); return SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)); } private static MemberDeclarationSyntax GenerateInterfaceVersionProperty(Type grainType) { var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceVersion); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceVersion(grainType))); return SF.PropertyDeclaration(typeof(ushort).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)); } /// <summary> /// Generates syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <returns> /// Syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method. /// </returns> private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType) { // Get the method with the correct type. var invokeMethod = TypeUtils.Method( (IGrainMethodInvoker x) => x.Invoke(default(IAddressable), default(InvokeMethodRequest))); return GenerateInvokeMethod(grainType, invokeMethod); } /// <summary> /// Generates syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <returns> /// Syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method. /// </returns> private static MethodDeclarationSyntax GenerateExtensionInvokeMethod(Type grainType) { // Get the method with the correct type. var invokeMethod = TypeUtils.Method( (IGrainExtensionMethodInvoker x) => x.Invoke(default(IGrainExtension), default(InvokeMethodRequest))); return GenerateInvokeMethod(grainType, invokeMethod); } /// <summary> /// Generates syntax for an invoke method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="invokeMethod"> /// The invoke method to generate. /// </param> /// <returns> /// Syntax for an invoke method. /// </returns> private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType, MethodInfo invokeMethod) { var parameters = invokeMethod.GetParameters(); var grainArgument = parameters[0].Name.ToIdentifierName(); var requestArgument = parameters[1].Name.ToIdentifierName(); // Store the relevant values from the request in local variables. var interfaceIdDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(int).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("interfaceId") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.InterfaceId))))); var interfaceIdVariable = SF.IdentifierName("interfaceId"); var methodIdDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(int).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("methodId") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.MethodId))))); var methodIdVariable = SF.IdentifierName("methodId"); var argumentsDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(object[]).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("arguments") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.Arguments))))); var argumentsVariable = SF.IdentifierName("arguments"); var methodDeclaration = invokeMethod.GetDeclarationSyntax() .AddModifiers(SF.Token(SyntaxKind.AsyncKeyword)) .AddBodyStatements(interfaceIdDeclaration, methodIdDeclaration, argumentsDeclaration); var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch( grainType, methodIdVariable, methodType => GenerateInvokeForMethod(grainType, grainArgument, methodType, argumentsVariable)); // Generate the default case, which will throw a NotImplementedException. var errorMessage = SF.BinaryExpression( SyntaxKind.AddExpression, "interfaceId=".GetLiteralExpression(), interfaceIdVariable); var throwStatement = SF.ThrowStatement( SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(errorMessage))); var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement); var interfaceIdSwitch = SF.SwitchStatement(interfaceIdVariable).AddSections(interfaceCases.ToArray()).AddSections(defaultCase); // If the provided grain is null, throw an argument exception. var argumentNullException = SF.ObjectCreationExpression(typeof(ArgumentNullException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(parameters[0].Name.GetLiteralExpression())); var grainArgumentCheck = SF.IfStatement( SF.BinaryExpression( SyntaxKind.EqualsExpression, grainArgument, SF.LiteralExpression(SyntaxKind.NullLiteralExpression)), SF.ThrowStatement(argumentNullException)); return methodDeclaration.AddBodyStatements(grainArgumentCheck, interfaceIdSwitch); } /// <summary> /// Generates syntax to invoke a method on a grain. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="grain"> /// The grain instance expression. /// </param> /// <param name="method"> /// The method. /// </param> /// <param name="arguments"> /// The arguments expression. /// </param> /// <returns> /// Syntax to invoke a method on a grain. /// </returns> private static StatementSyntax[] GenerateInvokeForMethod( Type grainType, IdentifierNameSyntax grain, MethodInfo method, ExpressionSyntax arguments) { var castGrain = SF.ParenthesizedExpression(SF.CastExpression(grainType.GetTypeSyntax(), grain)); // Construct expressions to retrieve each of the method's parameters. var parameters = new List<ExpressionSyntax>(); var methodParameters = method.GetParameters().ToList(); for (var i = 0; i < methodParameters.Count; i++) { var parameter = methodParameters[i]; var parameterType = parameter.ParameterType.GetTypeSyntax(); var indexArg = SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(i))); var arg = SF.CastExpression( parameterType, SF.ElementAccessExpression(arguments).AddArgumentListArguments(indexArg)); parameters.Add(arg); } // If the method is a generic method definition, use the generic method invoker field to invoke the method. if (method.IsGenericMethodDefinition) { var invokerFieldName = GetGenericMethodInvokerFieldName(method); var invokerCall = SF.InvocationExpression( SF.IdentifierName(invokerFieldName) .Member((GenericMethodInvoker invoker) => invoker.Invoke(null, null))) .AddArgumentListArguments(SF.Argument(grain), SF.Argument(arguments)); return new StatementSyntax[] { SF.ReturnStatement(SF.AwaitExpression(invokerCall)) }; } // Invoke the method. var grainMethodCall = SF.InvocationExpression(castGrain.Member(method.Name)) .AddArgumentListArguments(parameters.Select(SF.Argument).ToArray()); // For void methods, invoke the method and return null. if (method.ReturnType == typeof(void)) { return new StatementSyntax[] { SF.ExpressionStatement(grainMethodCall), SF.ReturnStatement(SF.LiteralExpression(SyntaxKind.NullLiteralExpression)) }; } // For methods which return non-generic Task, await the method and return null. if (method.ReturnType == typeof(Task)) { return new StatementSyntax[] { SF.ExpressionStatement(SF.AwaitExpression(grainMethodCall)), SF.ReturnStatement(SF.LiteralExpression(SyntaxKind.NullLiteralExpression)) }; } if (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition().FullName == "System.Threading.Tasks.ValueTask`1") { var convertToTaskResult = SF.IdentifierName("AsTask"); // Converting ValueTask method result to Task since "Invoke" method should return Task. // Temporary solution. Need to change when Orleans will be using ValueTask instead of Task. grainMethodCall = SF.InvocationExpression( SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SF.ExpressionStatement(grainMethodCall).Expression, convertToTaskResult)); } return new StatementSyntax[] { SF.ReturnStatement(SF.AwaitExpression(grainMethodCall)) }; } /// <summary> /// Generates <see cref="GenericMethodInvoker"/> fields for the generic methods in <paramref name="grainType"/>. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>The generated fields.</returns> private static MemberDeclarationSyntax[] GenerateGenericInvokerFields(Type grainType) { var methods = GrainInterfaceUtils.GetMethods(grainType); var result = new List<MemberDeclarationSyntax>(); foreach (var method in methods) { if (!method.IsGenericMethodDefinition) continue; result.Add(GenerateGenericInvokerField(method)); } return result.ToArray(); } /// <summary> /// Generates a <see cref="GenericMethodInvoker"/> field for the provided generic method. /// </summary> /// <param name="method">The method.</param> /// <returns>The generated field.</returns> private static MemberDeclarationSyntax GenerateGenericInvokerField(MethodInfo method) { var fieldInfoVariable = SF.VariableDeclarator(GetGenericMethodInvokerFieldName(method)) .WithInitializer( SF.EqualsValueClause( SF.ObjectCreationExpression(typeof(GenericMethodInvoker).GetTypeSyntax()) .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(method.DeclaringType.GetTypeSyntax())), SF.Argument(method.Name.GetLiteralExpression()), SF.Argument( SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(method.GetGenericArguments().Length)))))); return SF.FieldDeclaration( SF.VariableDeclaration(typeof(GenericMethodInvoker).GetTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword)); } /// <summary> /// Returns the name of the <see cref="GenericMethodInvoker"/> field corresponding to <paramref name="method"/>. /// </summary> /// <param name="method">The method.</param> /// <returns>The name of the invoker field corresponding to the provided method.</returns> private static string GetGenericMethodInvokerFieldName(MethodInfo method) { return method.Name + string.Join("_", method.GetGenericArguments().Select(arg => arg.Name)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A wrapper class for the primitive type float. ** ** ===========================================================*/ using System.Globalization; using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; namespace System { [Serializable] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Single : IComparable, IFormattable, IConvertible , IComparable<Single>, IEquatable<Single> { private float _value; // // Public constants // public const float MinValue = (float)-3.40282346638528859e+38; public const float Epsilon = (float)1.4e-45; public const float MaxValue = (float)3.40282346638528859e+38; public const float PositiveInfinity = (float)1.0 / (float)0.0; public const float NegativeInfinity = (float)-1.0 / (float)0.0; public const float NaN = (float)0.0 / (float)0.0; internal static float NegativeZero = BitConverter.Int32BitsToSingle(unchecked((int)0x80000000)); [Pure] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsInfinity(float f) { return (*(int*)(&f) & 0x7FFFFFFF) == 0x7F800000; } [Pure] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsPositiveInfinity(float f) { return *(int*)(&f) == 0x7F800000; } [Pure] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsNegativeInfinity(float f) { return *(int*)(&f) == unchecked((int)0xFF800000); } [Pure] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsNaN(float f) { return (*(int*)(&f) & 0x7FFFFFFF) > 0x7F800000; } [Pure] internal unsafe static bool IsNegative(float f) { return (*(uint*)(&f) & 0x80000000) == 0x80000000; } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Single, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Single) { float f = (float)value; if (_value < f) return -1; if (_value > f) return 1; if (_value == f) return 0; // At least one of the values is NaN. if (IsNaN(_value)) return (IsNaN(f) ? 0 : -1); else // f is NaN. return 1; } throw new ArgumentException(SR.Arg_MustBeSingle); } public int CompareTo(Single value) { if (_value < value) return -1; if (_value > value) return 1; if (_value == value) return 0; // At least one of the values is NaN. if (IsNaN(_value)) return (IsNaN(value) ? 0 : -1); else // f is NaN. return 1; } [System.Runtime.Versioning.NonVersionable] public static bool operator ==(Single left, Single right) { return left == right; } [System.Runtime.Versioning.NonVersionable] public static bool operator !=(Single left, Single right) { return left != right; } [System.Runtime.Versioning.NonVersionable] public static bool operator <(Single left, Single right) { return left < right; } [System.Runtime.Versioning.NonVersionable] public static bool operator >(Single left, Single right) { return left > right; } [System.Runtime.Versioning.NonVersionable] public static bool operator <=(Single left, Single right) { return left <= right; } [System.Runtime.Versioning.NonVersionable] public static bool operator >=(Single left, Single right) { return left >= right; } public override bool Equals(Object obj) { if (!(obj is Single)) { return false; } float temp = ((Single)obj)._value; if (temp == _value) { return true; } return IsNaN(temp) && IsNaN(_value); } public bool Equals(Single obj) { if (obj == _value) { return true; } return IsNaN(obj) && IsNaN(_value); } public unsafe override int GetHashCode() { float f = _value; if (f == 0) { // Ensure that 0 and -0 have the same hash code return 0; } int v = *(int*)(&f); return v; } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(_value, format, NumberFormatInfo.GetInstance(provider)); } // Parses a float from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static float Parse(String s) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Parse(s, style, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static float Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static float Parse(String s, NumberStyles style, NumberFormatInfo info) { return Number.ParseSingle(s, style, info); } public static Boolean TryParse(String s, out Single result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static Boolean TryParse(String s, NumberStyles style, NumberFormatInfo info, out Single result) { if (s == null) { result = 0; return false; } bool success = Number.TryParseSingle(s, style, info, out result); if (!success) { String sTrim = s.Trim(); if (sTrim.Equals(info.PositiveInfinitySymbol)) { result = PositiveInfinity; } else if (sTrim.Equals(info.NegativeInfinitySymbol)) { result = NegativeInfinity; } else if (sTrim.Equals(info.NaNSymbol)) { result = NaN; } else return false; // We really failed } return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Single; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_value); } float IConvertible.ToSingle(IFormatProvider provider) { return _value; } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DifferenceFinders.cs" company="NFluent"> // Copyright 2021 Cyrille DUPUYDAUBY // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace NFluent.Helpers { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Extensions; using Kernel; internal static class DifferenceFinders { internal static AggregatedDifference ValueDifference<TA, TE>(TA firstItem, string firstName, TE otherItem) { return ValueDifference(firstItem, firstName, otherItem, 0, new List<object>()); } /// <summary> /// Check Equality between actual and expected and provides details regarding differences, if any. /// </summary> /// <remarks> /// Is recursive. /// Algorithm focuses on value comparison, to better match expectations. Here is a summary of the logic: /// 1. deals with expected = null case /// 2. tries Equals, if success, values are considered equals /// 3. if there is recursion (self referencing object), values are assumed as different /// 4. if both values are numerical, compare them after conversion if needed. /// 5. if expected is an anonymous type, use a property based comparison /// 6. if both are enumerations, perform enumeration comparison /// 7. report values as different. /// </remarks> /// <typeparam name="TA">type of the actual value</typeparam> /// <typeparam name="TE">type of the expected value</typeparam> /// <param name="actual">actual value</param> /// <param name="firstName">name/label to use for messages</param> /// <param name="expected">expected value</param> /// <param name="refIndex">reference index (for collections)</param> /// <param name="firstSeen">track recursion</param> /// <returns></returns> private static AggregatedDifference ValueDifference<TA, TE>(TA actual, string firstName, TE expected, int refIndex, ICollection<object> firstSeen) { var result = new AggregatedDifference(); // handle null case first if (expected == null) { if (actual != null) { result.Add(DifferenceDetails.DoesNotHaveExpectedValue(firstName, actual, null, refIndex)); } return result; } // if both equals from a BCL perspective, we are done. if (EqualityHelper.CustomEquals(expected, actual)) { return result; } // handle actual is null if (actual == null) { result.Add(DifferenceDetails.DoesNotHaveExpectedValue(firstName, null, expected, refIndex)); return result; } // do not recurse if (firstSeen.Contains(actual)) { result.Add(DifferenceDetails.DoesNotHaveExpectedValue(firstName, actual, expected, 0)); return result; } firstSeen = new List<object>(firstSeen) {actual}; // deals with numerical var type = expected.GetType(); var commonType = actual.GetType().FindCommonNumericalType(type); // we silently convert numerical values if (commonType != null) { return NumericalValueDifference(actual, firstName, expected, refIndex, commonType, result); } if (type.TypeIsAnonymous()) { return AnonymousTypeDifference(actual, expected, type, result); } // handle enumeration if (actual.IsAnEnumeration(false) && expected.IsAnEnumeration(false)) { return ValueDifferenceEnumerable(actual as IEnumerable, firstName, expected as IEnumerable, firstSeen); } result.Add(DifferenceDetails.DoesNotHaveExpectedValue(firstName, actual, expected, refIndex)); return result; } private static AggregatedDifference AnonymousTypeDifference<TA, TE>(TA actual, TE expected, Type type, AggregatedDifference result) { var criteria = new ClassMemberCriteria(BindingFlags.Instance); criteria.SetPublic(); criteria.CaptureProperties(); criteria.CaptureFields(); // use field based comparison var wrapper = ReflectionWrapper.BuildFromInstance(type, expected, criteria); var actualWrapped = ReflectionWrapper.BuildFromInstance(actual.GetType(), actual, criteria); foreach (var match in actualWrapped.MemberMatches(wrapper).Where(match => !match.DoValuesMatches)) { result.Add(DifferenceDetails.FromMatch(match)); } return result; } private static AggregatedDifference NumericalValueDifference<TA, TE>(TA actual, string firstName, TE expected, int refIndex, Type commonType, AggregatedDifference result) { var convertedActual = Convert.ChangeType(actual, commonType); var convertedExpected = Convert.ChangeType(expected, commonType); if (convertedExpected.Equals(convertedActual)) { return result; } result.Add(DifferenceDetails.DoesNotHaveExpectedValue(firstName, actual, expected, refIndex)); return result; } private static AggregatedDifference ValueDifferenceDictionary(IReadOnlyDictionary<object, object> sutDictionary, string sutName, IReadOnlyDictionary<object, object> expectedDictionary, ICollection<object> firstItemsSeen) { var valueDifferences = new AggregatedDifference {IsEquivalent = true}; using var actualKeyIterator = sutDictionary.Keys.GetEnumerator(); using var expectedKeyIterator = expectedDictionary.Keys.GetEnumerator(); var stillExpectedKeys = true; var stillActualKeys = true; var index = 0; for (;;) { stillExpectedKeys = stillExpectedKeys && expectedKeyIterator.MoveNext(); stillActualKeys = stillActualKeys && actualKeyIterator.MoveNext(); if (!stillExpectedKeys) { // no more expected keys if (!stillActualKeys) { // we're done break; } // the sut has extra key(s) valueDifferences.Add(DifferenceDetails.WasNotExpected( $"{sutName}[{actualKeyIterator.Current.ToStringProperlyFormatted()}]", sutDictionary[actualKeyIterator.Current], index)); valueDifferences.IsEquivalent = false; } else if (!stillActualKeys) { // key not found valueDifferences.IsEquivalent = false; valueDifferences.Add(DifferenceDetails.WasNotFound( $"{sutName}[{expectedKeyIterator.Current.ToStringProperlyFormatted()}]", // ReSharper disable once AssignNullToNotNullAttribute new DictionaryEntry(expectedKeyIterator.Current, expectedDictionary[expectedKeyIterator.Current]), 0)); } else { var actualKey = actualKeyIterator.Current; var actualKeyName = $"{sutName} key[{index}]"; var itemDiffs = ValueDifference(actualKey, actualKeyName, expectedKeyIterator.Current, index, firstItemsSeen); if (!expectedDictionary.TryGetValue(actualKey!, out _)) { valueDifferences.Add(DifferenceDetails.WasNotExpected( $"{sutName}'s key {actualKey.ToStringProperlyFormatted()}", sutDictionary[actualKey], index)); valueDifferences.IsEquivalent = false; } else { itemDiffs = ValueDifference(sutDictionary[actualKey], $"{sutName}[{actualKey.ToStringProperlyFormatted()}]", expectedDictionary[actualKey], index, firstItemsSeen); valueDifferences.IsEquivalent &= !itemDiffs.IsDifferent || itemDiffs.IsEquivalent; } valueDifferences.Merge(itemDiffs); } index++; } return valueDifferences; } private static AggregatedDifference ValueDifferenceArray(Array firstArray, string firstName, Array secondArray, ICollection<object> firstSeen) { var valueDifferences = new AggregatedDifference(); if (firstArray.Rank != secondArray.Rank) { valueDifferences.Add(DifferenceDetails.DoesNotHaveExpectedAttribute($"{firstName}.Rank", firstArray.Rank, secondArray.Rank, 0)); return valueDifferences; } for (var i = 0; i < firstArray.Rank; i++) { if (firstArray.SizeOfDimension(i) == secondArray.SizeOfDimension(i)) { continue; } valueDifferences.Add(DifferenceDetails.DoesNotHaveExpectedAttribute($"{firstName}.Dimension({i})", firstArray.SizeOfDimension(i), secondArray.SizeOfDimension(i), i)); return valueDifferences; } return ScanEnumeration(firstArray, secondArray, index => { var temp = index; var indices = new int[firstArray.Rank]; for (var j = 0; j < firstArray.Rank; j++) { var currentIndex = temp % firstArray.SizeOfDimension(j); indices[firstArray.Rank - j - 1] = currentIndex; temp /= firstArray.SizeOfDimension(j); } return $"actual[{string.Join(",", indices.Select(x => x.ToString()).ToArray())}]"; }, firstSeen); } private static AggregatedDifference ValueDifferenceEnumerable(IEnumerable firstItem, string firstName, IEnumerable otherItem, ICollection<object> firstSeen) { if (firstItem.GetType().IsArray && otherItem.GetType().IsArray) { return ValueDifferenceArray(firstItem as Array, firstName, otherItem as Array, firstSeen); } var dictionary = DictionaryExtensions.WrapDictionary<object, object>(otherItem); if (dictionary != null) { var wrapDictionary = DictionaryExtensions.WrapDictionary<object, object>(firstItem); if (wrapDictionary != null) { return ValueDifferenceDictionary(wrapDictionary, firstName, dictionary, firstSeen); } } return ScanEnumeration(firstItem, otherItem, x => $"{firstName}[{x}]", firstSeen); } private static AggregatedDifference ScanEnumeration(IEnumerable firstItem, IEnumerable otherItem, Func<int, string> namingCallback, ICollection<object> firstSeen) { var index = 0; var mayBeEquivalent = true; var expected = new List<KeyValuePair<object, int>>(); var unexpected = new List<KeyValuePair<object, int>>(); var aggregatedDifferences = new Dictionary<int, AggregatedDifference>(); var valueDifferences = new AggregatedDifference(); var scanner = otherItem.GetEnumerator(); foreach (var item in firstItem) { var firstItemName = namingCallback(index); if (!scanner.MoveNext()) { valueDifferences.Add(DifferenceDetails.WasNotExpected(firstItemName, item, index)); unexpected.Add(new KeyValuePair<object, int>(item, index)); break; } var aggregatedDifference = ValueDifference(item, firstItemName, scanner.Current, index, firstSeen); if (aggregatedDifference.IsDifferent) { aggregatedDifferences.Add(index, aggregatedDifference); if (!aggregatedDifference.IsEquivalent) { // try to see it was at a different position var indexOrigin = expected.FindIndex(pair => FluentEquivalent(pair.Key, item)); if (indexOrigin >= 0) { // we found the value at another index valueDifferences.Add(DifferenceDetails.WasFoundElseWhere(firstItemName, item, index, expected[indexOrigin].Value)); expected.RemoveAt(indexOrigin); aggregatedDifferences.Remove(indexOrigin); aggregatedDifferences.Remove(index); } else { unexpected.Add(new KeyValuePair<object, int>(item, index)); } // what about the expected value var indexOther = unexpected.FindIndex(pair => FluentEquivalent(pair.Key, scanner.Current)); if (indexOther >= 0) { valueDifferences.Add(DifferenceDetails.WasFoundElseWhere(firstItemName, unexpected[indexOther].Key, unexpected[indexOther].Value, index)); aggregatedDifferences.Remove(unexpected[indexOther].Value); unexpected.RemoveAt(indexOther); } else { expected.Add(new KeyValuePair<object, int>(scanner.Current, index)); } } } index++; } if (scanner.MoveNext()) { valueDifferences.Add(DifferenceDetails.WasNotFound(namingCallback(index), scanner.Current, index)); mayBeEquivalent = false; } foreach (var differencesValue in aggregatedDifferences.Values) { valueDifferences.Merge(differencesValue); } for (var i = 0; i < Math.Min(unexpected.Count, expected.Count); i++) { //aggregatedDifferences.Remove(unexpected[i].Value); valueDifferences.Add(DifferenceDetails.WasFoundInsteadOf(namingCallback(unexpected[i].Value), unexpected[i].Key, expected[i].Key)); } if (mayBeEquivalent && valueDifferences.IsDifferent) { valueDifferences.IsEquivalent = expected.Count == 0 && unexpected.Count == 0; } return valueDifferences; } private static bool FluentEquivalent<TS, TE>(TS instance, TE expected) { var scan = EqualityHelper.FluentEquals(instance, expected, Check.EqualMode); return !scan.IsDifferent || scan.IsEquivalent; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>Tensorboard</c> resource.</summary> public sealed partial class TensorboardName : gax::IResourceName, sys::IEquatable<TensorboardName> { /// <summary>The possible contents of <see cref="TensorboardName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c>. /// </summary> ProjectLocationTensorboard = 1, } private static gax::PathTemplate s_projectLocationTensorboard = new gax::PathTemplate("projects/{project}/locations/{location}/tensorboards/{tensorboard}"); /// <summary>Creates a <see cref="TensorboardName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TensorboardName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static TensorboardName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TensorboardName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TensorboardName"/> with the pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorboardId">The <c>Tensorboard</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TensorboardName"/> constructed from the provided ids.</returns> public static TensorboardName FromProjectLocationTensorboard(string projectId, string locationId, string tensorboardId) => new TensorboardName(ResourceNameType.ProjectLocationTensorboard, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tensorboardId: gax::GaxPreconditions.CheckNotNullOrEmpty(tensorboardId, nameof(tensorboardId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TensorboardName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorboardId">The <c>Tensorboard</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TensorboardName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c>. /// </returns> public static string Format(string projectId, string locationId, string tensorboardId) => FormatProjectLocationTensorboard(projectId, locationId, tensorboardId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TensorboardName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorboardId">The <c>Tensorboard</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TensorboardName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c>. /// </returns> public static string FormatProjectLocationTensorboard(string projectId, string locationId, string tensorboardId) => s_projectLocationTensorboard.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tensorboardId, nameof(tensorboardId))); /// <summary>Parses the given resource name string into a new <see cref="TensorboardName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c></description> /// </item> /// </list> /// </remarks> /// <param name="tensorboardName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TensorboardName"/> if successful.</returns> public static TensorboardName Parse(string tensorboardName) => Parse(tensorboardName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TensorboardName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tensorboardName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TensorboardName"/> if successful.</returns> public static TensorboardName Parse(string tensorboardName, bool allowUnparsed) => TryParse(tensorboardName, allowUnparsed, out TensorboardName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TensorboardName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c></description> /// </item> /// </list> /// </remarks> /// <param name="tensorboardName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TensorboardName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tensorboardName, out TensorboardName result) => TryParse(tensorboardName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TensorboardName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tensorboardName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TensorboardName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tensorboardName, bool allowUnparsed, out TensorboardName result) { gax::GaxPreconditions.CheckNotNull(tensorboardName, nameof(tensorboardName)); gax::TemplatedResourceName resourceName; if (s_projectLocationTensorboard.TryParseName(tensorboardName, out resourceName)) { result = FromProjectLocationTensorboard(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(tensorboardName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TensorboardName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string tensorboardId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; TensorboardId = tensorboardId; } /// <summary> /// Constructs a new instance of a <see cref="TensorboardName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorboardId">The <c>Tensorboard</c> ID. Must not be <c>null</c> or empty.</param> public TensorboardName(string projectId, string locationId, string tensorboardId) : this(ResourceNameType.ProjectLocationTensorboard, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tensorboardId: gax::GaxPreconditions.CheckNotNullOrEmpty(tensorboardId, nameof(tensorboardId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Tensorboard</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TensorboardId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationTensorboard: return s_projectLocationTensorboard.Expand(ProjectId, LocationId, TensorboardId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TensorboardName); /// <inheritdoc/> public bool Equals(TensorboardName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TensorboardName a, TensorboardName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TensorboardName a, TensorboardName b) => !(a == b); } public partial class Tensorboard { /// <summary> /// <see cref="gcav::TensorboardName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::TensorboardName TensorboardName { get => string.IsNullOrEmpty(Name) ? null : gcav::TensorboardName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
/* * SqlDataStorageManager.cs 12/26/2002 * * Copyright 2002 Fluent Consulting, Inc. All rights reserved. * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ using System; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Reflection; using System.Text; using System.Data.SqlTypes; using Inform.Common; using Inform.Sql.Mappings; using Fluent.Text; namespace Inform.Sql { /// <summary> /// Summary description for SqlDataStorageManager. /// </summary> public class SqlDataStorageManager : DataStorageManager { public SqlDataStorageManager(SqlDataStore dataStore) : base(dataStore) { AddDefaultPropertyMappingsTypes(); } override public bool ExistsStorage(TypeMapping typeMapping){ return CheckMapping(typeMapping).Condition != TypeMappingState.TypeMappingStateCondition.TableMissing; } override public string GenerateCreateTableSql(TypeMapping typeMapping){ StringBuilder sqlCreateTable = new StringBuilder(); //Create statement sqlCreateTable.Append("CREATE TABLE [dbo].[" + typeMapping.TableName + "] (\r\n"); //Add the columns bool addComa = false; foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ //add comas after column definitions if(addComa){ sqlCreateTable.Append(",\r\n"); } sqlCreateTable.Append("\t[" + propertyMapping.ColumnName + "] "+ propertyMapping.MemberDbType.ToSql()); if (propertyMapping.PrimaryKey){ if(propertyMapping.Identity){ sqlCreateTable.Append(" IDENTITY (1, 1) PRIMARY KEY NOT NULL"); } else { sqlCreateTable.Append(" PRIMARY KEY"); } } else { if(propertyMapping.MemberDbType.IsNullable) { sqlCreateTable.Append(" NULL"); } else { sqlCreateTable.Append(" NOT NULL"); } } addComa = true; } //return from last column defintion sqlCreateTable.Append("\r\n"); //close create statement sqlCreateTable.Append(")\r\n"); return sqlCreateTable.ToString(); } override public string GenerateDeleteTableSql(TypeMapping typeMapping){ return "DROP TABLE [dbo].[" + typeMapping.TableName + "]"; } override public string GenerateCreateRelationshipSql(RelationshipMapping rm){ //TODO: check rm? StringBuilder sqlCreateRelationship = new StringBuilder(); TypeMapping childTypeMapping = this.GetTypeMapping(rm.ChildType, true); TypeMapping parentTypeMapping = this.GetTypeMapping(rm.ParentType, true); sqlCreateRelationship.AppendFormat("ALTER TABLE [{0}] \r\n",childTypeMapping.TableName); sqlCreateRelationship.AppendFormat("ADD CONSTRAINT {0} \r\n", rm.Name); sqlCreateRelationship.AppendFormat("FOREIGN KEY ([{0}]) REFERENCES [{1}]([{2}]) ON DELETE NO ACTION", childTypeMapping.MemberMappings.GetByName(rm.ChildMember).ColumnName, parentTypeMapping.TableName, parentTypeMapping.MemberMappings.GetByName(rm.ParentMember).ColumnName); return sqlCreateRelationship.ToString(); } override public string GenerateDropProcedureSql(string procedureName){ string sql = "IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[" + procedureName + "]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)\r\n"; return sql += "DROP PROCEDURE [dbo].[" + procedureName + "]"; } override public string GenerateInsertSql(TypeMapping typeMapping){ StringBuilder sqlCreateInsert = new StringBuilder(); sqlCreateInsert.AppendFormat("INSERT INTO {0} (\r\n",typeMapping.TableName); //Add the column names StringConcatenator concatenator = new StringConcatenator(sqlCreateInsert,",\r\n"); foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ if(propertyMapping.PrimaryKey && propertyMapping.Identity){ continue; } concatenator.AppendFormat("\t[{0}]", propertyMapping.ColumnName); } sqlCreateInsert.Append("\r\n) VALUES (\r\n"); //Add the values concatenator.Reset(); foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ if(propertyMapping.PrimaryKey && propertyMapping.Identity){ continue; } concatenator.AppendFormat("\t@{0}", propertyMapping.ColumnName); } sqlCreateInsert.Append("\r\n"); sqlCreateInsert.Append(")\r\n"); if(typeMapping.PrimaryKey != null && typeMapping.PrimaryKey.Identity){ sqlCreateInsert.AppendFormat("SELECT @{0} = @@IDENTITY\r\n",typeMapping.PrimaryKey.ColumnName); } return sqlCreateInsert.ToString(); } override public string GenerateUpdateSql(TypeMapping typeMapping){ StringBuilder sqlCreateSQL = new StringBuilder(); sqlCreateSQL.AppendFormat("UPDATE {0}\r\n",typeMapping.TableName); sqlCreateSQL.Append("SET \r\n"); //Add the columns bool addComa = false; foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ if(propertyMapping.PrimaryKey){ continue; } //add comas after column definitions if(addComa){ sqlCreateSQL.Append(",\r\n"); } sqlCreateSQL.AppendFormat("\t[{0}] = @{0}", propertyMapping.ColumnName); addComa = true; } //return from last column defintion sqlCreateSQL.Append("\r\n"); sqlCreateSQL.AppendFormat("WHERE {0} = @{0}\r\n", typeMapping.PrimaryKey.ColumnName); return sqlCreateSQL.ToString(); } override public string GenerateDeleteSql(TypeMapping typeMapping){ if(typeMapping.PrimaryKey == null){ throw new DataStoreException("Can not create delete procedure without defined primary key"); } StringBuilder sqlCreateSQL = new StringBuilder(); sqlCreateSQL.AppendFormat("DELETE FROM {0}\r\n",typeMapping.TableName); sqlCreateSQL.AppendFormat("WHERE {0} = @{0}\r\n", typeMapping.PrimaryKey.ColumnName); return sqlCreateSQL.ToString(); } override public string GenerateCreateInsertProcedureSql(TypeMapping typeMapping){ StringBuilder sqlCreateInsert = new StringBuilder(); sqlCreateInsert.AppendFormat("CREATE PROCEDURE dbo.{0}\r\n", GetInsertProcedureName(typeMapping)); sqlCreateInsert.Append("(\r\n"); //Add the columns bool addComa = false; foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ //add comas after column definitions if(addComa){ sqlCreateInsert.Append(",\r\n"); } sqlCreateInsert.AppendFormat("\t@{0} {1}", propertyMapping.ColumnName, propertyMapping.MemberDbType.ToSql()); if(propertyMapping.PrimaryKey && propertyMapping.Identity){ sqlCreateInsert.Append(" OUTPUT"); } addComa = true; } //return from last column defintion sqlCreateInsert.Append("\r\n"); sqlCreateInsert.Append(")\r\n"); sqlCreateInsert.Append("AS\r\n"); sqlCreateInsert.AppendFormat("INSERT INTO {0} (\r\n",typeMapping.TableName); //Add the column names addComa = false; foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ if(propertyMapping.PrimaryKey && propertyMapping.Identity){ continue; } //add comas after column definitions if(addComa){ sqlCreateInsert.Append(",\r\n"); } sqlCreateInsert.AppendFormat("\t[{0}]", propertyMapping.ColumnName); addComa = true; } sqlCreateInsert.Append("\r\n) VALUES (\r\n"); //Add the values addComa = false; foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ if(propertyMapping.PrimaryKey && propertyMapping.Identity){ continue; } //add comas after column definitions if(addComa){ sqlCreateInsert.Append(",\r\n"); } sqlCreateInsert.AppendFormat("\t@{0}", propertyMapping.ColumnName); addComa = true; } //return from last column defintion sqlCreateInsert.Append("\r\n"); sqlCreateInsert.Append(")\r\n"); if(typeMapping.PrimaryKey.Identity){ sqlCreateInsert.AppendFormat("SELECT @{0} = @@IDENTITY\r\n",typeMapping.PrimaryKey.ColumnName); } return sqlCreateInsert.ToString(); } override public string GenerateCreateUpdateProcedureSql(TypeMapping typeMapping){ StringBuilder sqlCreateSQL = new StringBuilder(); sqlCreateSQL.AppendFormat("CREATE PROCEDURE dbo.{0}\r\n", GetUpdateProcedureName(typeMapping)); sqlCreateSQL.Append("(\r\n"); //Add the columns bool addComa = false; foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ //add comas after column definitions if(addComa){ sqlCreateSQL.Append(",\r\n"); } sqlCreateSQL.AppendFormat("\t@{0} {1}", propertyMapping.ColumnName, propertyMapping.MemberDbType.ToSql()); addComa = true; } //return from last column defintion sqlCreateSQL.Append("\r\n"); sqlCreateSQL.Append(")\r\n"); sqlCreateSQL.Append("AS\r\n"); sqlCreateSQL.AppendFormat("UPDATE {0}\r\n",typeMapping.TableName); sqlCreateSQL.Append("SET \r\n"); //Add the columns addComa = false; foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ if(propertyMapping.PrimaryKey){ continue; } //add comas after column definitions if(addComa){ sqlCreateSQL.Append(",\r\n"); } sqlCreateSQL.AppendFormat("\t[{0}] = @{0}", propertyMapping.ColumnName); addComa = true; } //return from last column defintion sqlCreateSQL.Append("\r\n"); sqlCreateSQL.AppendFormat("WHERE {0} = @{0}\r\n", typeMapping.PrimaryKey.ColumnName); return sqlCreateSQL.ToString(); } override public string GenerateCreateDeleteProcedureSql(TypeMapping typeMapping){ if(typeMapping.PrimaryKey == null){ throw new DataStoreException("Can not create delete procedure without defined primary key"); } StringBuilder sqlCreateSQL = new StringBuilder(); sqlCreateSQL.AppendFormat("CREATE PROCEDURE dbo.{0}\r\n", GetDeleteProcedureName(typeMapping)); sqlCreateSQL.Append("(\r\n"); IMemberMapping primarykeyMapping = typeMapping.PrimaryKey; sqlCreateSQL.AppendFormat("\t@{0} {1}\r\n", primarykeyMapping.ColumnName, primarykeyMapping.MemberDbType.ToSql()); sqlCreateSQL.Append(")\r\n"); sqlCreateSQL.Append("AS\r\n"); sqlCreateSQL.AppendFormat("DELETE FROM {0}\r\n",typeMapping.TableName); sqlCreateSQL.AppendFormat("WHERE {0} = @{0}\r\n", typeMapping.PrimaryKey.ColumnName); return sqlCreateSQL.ToString(); } override public string GenerateFindByPrimaryKeySql(TypeMapping typeMapping){ if(typeMapping.PrimaryKey == null) { throw new DataStoreException("TypeMapping does not have defined PrimaryKey for " + typeMapping.MappedType.FullName); } StringBuilder sqlCreateSQL = new StringBuilder(); sqlCreateSQL.AppendFormat("WHERE [{0}].[{1}] = @{1}", typeMapping.TableName, typeMapping.PrimaryKey.ColumnName); return sqlCreateSQL.ToString(); } private void AddDefaultPropertyMappingsTypes(){ AddPropertyMappingType(typeof(string),typeof(SqlStringMapping)); AddPropertyMappingType(typeof(Byte),typeof(SqlByteMapping)); AddPropertyMappingType(typeof(Char),typeof(SqlCharMapping)); AddPropertyMappingType(typeof(Int16),typeof(SqlInt16Mapping)); AddPropertyMappingType(typeof(int),typeof(SqlInt32Mapping)); AddPropertyMappingType(typeof(Int64),typeof(SqlInt64Mapping)); AddPropertyMappingType(typeof(bool),typeof(SqlBoolMapping)); AddPropertyMappingType(typeof(double),typeof(SqlDoubleMapping)); AddPropertyMappingType(typeof(float),typeof(SqlSingleMapping)); AddPropertyMappingType(typeof(Byte[]),typeof(SqlByteArrayMapping)); AddPropertyMappingType(typeof(Enum),typeof(SqlEnumMapping)); AddPropertyMappingType(typeof(Decimal),typeof(SqlDecimalMapping)); AddPropertyMappingType(typeof(DateTime),typeof(SqlDateTimeMapping)); AddPropertyMappingType(typeof(Guid),typeof(SqlGuidMapping)); AddPropertyMappingType(typeof(SqlByte),typeof(SqlSqlByteMapping)); AddPropertyMappingType(typeof(SqlInt16),typeof(SqlSqlInt16Mapping)); AddPropertyMappingType(typeof(SqlInt32),typeof(SqlSqlInt32Mapping)); AddPropertyMappingType(typeof(SqlInt64),typeof(SqlSqlInt64Mapping)); AddPropertyMappingType(typeof(SqlGuid),typeof(SqlSqlGuidMapping)); AddPropertyMappingType(typeof(SqlSingle),typeof(SqlSqlSingleMapping)); AddPropertyMappingType(typeof(SqlDouble),typeof(SqlSqlDoubleMapping)); AddPropertyMappingType(typeof(SqlBoolean),typeof(SqlSqlBooleanMapping)); AddPropertyMappingType(typeof(SqlDateTime),typeof(SqlSqlDateTimeMapping)); AddPropertyMappingType(typeof(SqlDecimal),typeof(SqlSqlDecimalMapping)); AddPropertyMappingType(typeof(SqlMoney),typeof(SqlSqlMoneyMapping)); AddPropertyMappingType(typeof(SqlString),typeof(SqlSqlStringMapping)); } override public TypeMappingState CheckMapping(TypeMapping typeMapping){ if(!TableExists(typeMapping.TableName)){ return new TypeMappingState(TypeMappingState.TypeMappingStateCondition.TableMissing); } IDataAccessCommand command = ManagedDataStore.CreateDataAccessCommand("SELECT * FROM " + typeMapping.TableName, CommandType.Text); //Get Schema IDataReader r = null; DataTable schema; try { r = command.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.CloseConnection); schema = r.GetSchemaTable(); } finally { if(r != null){ r.Close(); } } //Check Schema ArrayList errors = new ArrayList(); foreach(IMemberMapping mapping in typeMapping.MemberMappings){ DataRow[] rows = schema.Select("ColumnName = '" + mapping.ColumnName + "'"); if(rows.Length != 1){ errors.Add(new MemberMappingError(MemberMappingError.MemberMappingErrorCode.ColumnMissing,mapping)); } } if(errors.Count > 0){ return new TypeMappingState(errors); } else { return new TypeMappingState(TypeMappingState.TypeMappingStateCondition.None); } } override public bool TableExists(string tableName){ SqlDataAccessCommand command = (SqlDataAccessCommand)ManagedDataStore.CreateDataAccessCommand("SELECT COUNT(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @TableName", CommandType.Text); command.CreateInputParameter("@tableName", SqlDbType.VarChar, tableName); return ((int)command.ExecuteScalar()) > 0; } override public string CreateQuery(Type type, string filter, bool polymorphic){ if(filter != null && filter.TrimStart().ToUpper().StartsWith("SELECT")){ return filter; } TypeMapping typeMapping = null; if((typeMapping = this.GetTypeMapping(type)) == null){ throw new DataStoreException("DataStore does not contain storage for " + type.FullName); } StringBuilder sqlQuerySQL = new StringBuilder(); if(!polymorphic){ sqlQuerySQL.AppendFormat("SELECT {0}.*{1} FROM {0}\r\n", typeMapping.TableName, BuildBaseClassColumnList(typeMapping)); // if(typeMapping.BaseType != null){ // TypeMapping baseTypeMapping = GetTypeMapping(typeMapping.BaseType); // sqlQuerySQL.AppendFormat("INNER JOIN {0}\r\n ON {0}.{1} = {2}.{1}\r\n", baseTypeMapping.TableName, typeMapping.PrimaryKey.ColumnName, typeMapping.TableName); // } } else { //TODO: extend recursively sqlQuerySQL.AppendFormat("SELECT {1}{2} FROM {0}\r\n", typeMapping.TableName, BuildSubClassColumnList(typeMapping), BuildBaseClassColumnList(typeMapping)); AppendSubClassJoins(typeMapping, sqlQuerySQL); //TODO: add to oledb TypeMapping baseTypeMapping = typeMapping; while (baseTypeMapping.BaseType != null) { baseTypeMapping = GetTypeMapping(baseTypeMapping.BaseType); sqlQuerySQL.AppendFormat("INNER JOIN {0}\r\n ON {0}.{1} = {2}.{1}\r\n", baseTypeMapping.TableName, typeMapping.PrimaryKey.ColumnName, typeMapping.TableName); } //sqlQuerySQL.AppendFormat("INNER JOIN {0}\r\n ON {0}.{1} = {2}.{1}\r\n",GetSubclassTableName(typeMapping),typeMapping.PrimaryKey,typeMapping.TableName); //sqlQuerySQL.AppendFormat("INNER JOIN {0}\r\n ON {0}.{1} = {2}.{1}\r\n",GetTypeTableName(),"TypeID",GetSubclassTableName(typeMapping)); } return sqlQuerySQL.ToString() + " " + filter; } private void AppendSubClassJoins(TypeMapping typeMapping, StringBuilder sqlQuerySQL) { foreach (Type subClass in typeMapping.SubClasses) { TypeMapping subClassMapping = GetTypeMapping(subClass); sqlQuerySQL.AppendFormat("LEFT OUTER JOIN {0}\r\n ON {0}.{1} = {2}.{1}\r\n", subClassMapping.TableName, typeMapping.PrimaryKey.ColumnName, typeMapping.TableName); AppendSubClassJoins(subClassMapping, sqlQuerySQL); } } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using GoCardless.Internals; namespace GoCardless.Resources { /// <summary> /// Represents a payment resource. /// /// Payment objects represent payments from a /// [customer](#core-endpoints-customers) to a /// [creditor](#core-endpoints-creditors), taken against a Direct Debit /// [mandate](#core-endpoints-mandates). /// /// GoCardless will notify you via a [webhook](#appendix-webhooks) whenever /// the state of a payment changes. /// </summary> public class Payment { /// <summary> /// Amount, in the lowest denomination for the currency (e.g. pence in /// GBP, cents in EUR). /// </summary> [JsonProperty("amount")] public int? Amount { get; set; } /// <summary> /// Amount [refunded](#core-endpoints-refunds), in the lowest /// denomination for the currency (e.g. pence in GBP, cents in EUR). /// </summary> [JsonProperty("amount_refunded")] public int? AmountRefunded { get; set; } /// <summary> /// A future date on which the payment should be collected. If not /// specified, the payment will be collected as soon as possible. If the /// value is before the [mandate](#core-endpoints-mandates)'s /// `next_possible_charge_date` creation will fail. If the value is not /// a working day it will be rolled forwards to the next available one. /// </summary> [JsonProperty("charge_date")] public string ChargeDate { get; set; } /// <summary> /// Fixed [timestamp](#api-usage-time-zones--dates), recording when this /// resource was created. /// </summary> [JsonProperty("created_at")] public DateTimeOffset? CreatedAt { get; set; } /// <summary> /// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes) /// currency code. Currently "AUD", "CAD", "DKK", "EUR", "GBP", "NZD", /// "SEK" and "USD" are supported. /// </summary> [JsonProperty("currency")] public PaymentCurrency? Currency { get; set; } /// <summary> /// A human-readable description of the payment. This will be included /// in the notification email GoCardless sends to your customer if your /// organisation does not send its own notifications (see [compliance /// requirements](#appendix-compliance-requirements)). /// </summary> [JsonProperty("description")] public string Description { get; set; } /// <summary> /// /// </summary> [JsonProperty("fx")] public PaymentFx Fx { get; set; } /// <summary> /// Unique identifier, beginning with "PM". /// </summary> [JsonProperty("id")] public string Id { get; set; } /// <summary> /// Resources linked to this Payment. /// </summary> [JsonProperty("links")] public PaymentLinks Links { get; set; } /// <summary> /// Key-value store of custom data. Up to 3 keys are permitted, with key /// names up to 50 characters and values up to 500 characters. /// </summary> [JsonProperty("metadata")] public IDictionary<string, string> Metadata { get; set; } /// <summary> /// An optional reference that will appear on your customer's bank /// statement. The character limit for this reference is dependent on /// the scheme.<br /> <strong>ACH</strong> - 10 characters<br /> /// <strong>Autogiro</strong> - 11 characters<br /> /// <strong>Bacs</strong> - 10 characters<br /> <strong>BECS</strong> - /// 30 characters<br /> <strong>BECS NZ</strong> - 12 characters<br /> /// <strong>Betalingsservice</strong> - 30 characters<br /> /// <strong>PAD</strong> - 12 characters<br /> <strong>SEPA</strong> - /// 140 characters<br /> Note that this reference must be unique (for /// each merchant) for the BECS scheme as it is a scheme requirement. <p /// class='restricted-notice'><strong>Restricted</strong>: You can only /// specify a payment reference for Bacs payments (that is, when /// collecting from the UK) if you're on the <a /// href='https://gocardless.com/pricing'>GoCardless Plus, Pro or /// Enterprise packages</a>.</p> /// </summary> [JsonProperty("reference")] public string Reference { get; set; } /// <summary> /// On failure, automatically retry the payment using [intelligent /// retries](#success-intelligent-retries). Default is `false`. /// </summary> [JsonProperty("retry_if_possible")] public bool? RetryIfPossible { get; set; } /// <summary> /// One of: /// <ul> /// <li>`pending_customer_approval`: we're waiting for the customer to /// approve this payment</li> /// <li>`pending_submission`: the payment has been created, but not yet /// submitted to the banks</li> /// <li>`submitted`: the payment has been submitted to the banks</li> /// <li>`confirmed`: the payment has been confirmed as collected</li> /// <li>`paid_out`: the payment has been included in a /// [payout](#core-endpoints-payouts)</li> /// <li>`cancelled`: the payment has been cancelled</li> /// <li>`customer_approval_denied`: the customer has denied approval for /// the payment. You should contact the customer directly</li> /// <li>`failed`: the payment failed to be processed. Note that payments /// can fail after being confirmed if the failure message is sent late /// by the banks.</li> /// <li>`charged_back`: the payment has been charged back</li> /// </ul> /// </summary> [JsonProperty("status")] public PaymentStatus? Status { get; set; } } /// <summary> /// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes) currency code. Currently /// "AUD", "CAD", "DKK", "EUR", "GBP", "NZD", "SEK" and "USD" are supported. /// </summary> [JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)] public enum PaymentCurrency { /// <summary>Unknown status</summary> [EnumMember(Value = "unknown")] Unknown = 0, /// <summary>`currency` with a value of "AUD"</summary> [EnumMember(Value = "AUD")] AUD, /// <summary>`currency` with a value of "CAD"</summary> [EnumMember(Value = "CAD")] CAD, /// <summary>`currency` with a value of "DKK"</summary> [EnumMember(Value = "DKK")] DKK, /// <summary>`currency` with a value of "EUR"</summary> [EnumMember(Value = "EUR")] EUR, /// <summary>`currency` with a value of "GBP"</summary> [EnumMember(Value = "GBP")] GBP, /// <summary>`currency` with a value of "NZD"</summary> [EnumMember(Value = "NZD")] NZD, /// <summary>`currency` with a value of "SEK"</summary> [EnumMember(Value = "SEK")] SEK, /// <summary>`currency` with a value of "USD"</summary> [EnumMember(Value = "USD")] USD, } public class PaymentFx { /// <summary> /// Estimated rate that will be used in the foreign exchange of the /// `amount` into the `fx_currency`. /// This will vary based on the prevailing market rate until the moment /// that it is paid out. /// Present only before a resource is paid out. Has up to 10 decimal /// places. /// </summary> [JsonProperty("estimated_exchange_rate")] public string EstimatedExchangeRate { get; set; } /// <summary> /// Rate used in the foreign exchange of the `amount` into the /// `fx_currency`. /// Present only after a resource is paid out. Has up to 10 decimal /// places. /// </summary> [JsonProperty("exchange_rate")] public string ExchangeRate { get; set; } /// <summary> /// Amount that was paid out in the `fx_currency` after foreign /// exchange. /// Present only after the resource has been paid out. /// </summary> [JsonProperty("fx_amount")] public int? FxAmount { get; set; } /// <summary> /// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes) code /// for the currency in which amounts will be paid out (after foreign /// exchange). Currently "AUD", "CAD", "DKK", "EUR", "GBP", "NZD", "SEK" /// and "USD" are supported. Present only if payouts will be (or were) /// made via foreign exchange. /// </summary> [JsonProperty("fx_currency")] public PaymentFxFxCurrency? FxCurrency { get; set; } } /// <summary> /// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes) code for the currency in /// which amounts will be paid out (after foreign exchange). Currently "AUD", "CAD", "DKK", /// "EUR", "GBP", "NZD", "SEK" and "USD" are supported. Present only if payouts will be (or /// were) made via foreign exchange. /// </summary> [JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)] public enum PaymentFxFxCurrency { /// <summary>Unknown status</summary> [EnumMember(Value = "unknown")] Unknown = 0, /// <summary>`fx_currency` with a value of "AUD"</summary> [EnumMember(Value = "AUD")] AUD, /// <summary>`fx_currency` with a value of "CAD"</summary> [EnumMember(Value = "CAD")] CAD, /// <summary>`fx_currency` with a value of "DKK"</summary> [EnumMember(Value = "DKK")] DKK, /// <summary>`fx_currency` with a value of "EUR"</summary> [EnumMember(Value = "EUR")] EUR, /// <summary>`fx_currency` with a value of "GBP"</summary> [EnumMember(Value = "GBP")] GBP, /// <summary>`fx_currency` with a value of "NZD"</summary> [EnumMember(Value = "NZD")] NZD, /// <summary>`fx_currency` with a value of "SEK"</summary> [EnumMember(Value = "SEK")] SEK, /// <summary>`fx_currency` with a value of "USD"</summary> [EnumMember(Value = "USD")] USD, } /// <summary> /// Resources linked to this Payment /// </summary> public class PaymentLinks { /// <summary> /// ID of [creditor](#core-endpoints-creditors) to which the collected /// payment will be sent. /// </summary> [JsonProperty("creditor")] public string Creditor { get; set; } /// <summary> /// ID of [instalment_schedule](#core-endpoints-instalment-schedules) /// from which this payment was created.<br/>**Note**: this property /// will only be present if this payment is part of an instalment /// schedule. /// </summary> [JsonProperty("instalment_schedule")] public string InstalmentSchedule { get; set; } /// <summary> /// ID of the [mandate](#core-endpoints-mandates) against which this /// payment should be collected. /// </summary> [JsonProperty("mandate")] public string Mandate { get; set; } /// <summary> /// ID of [payout](#core-endpoints-payouts) which contains the funds /// from this payment.<br/>_Note_: this property will not be present /// until the payment has been successfully collected. /// </summary> [JsonProperty("payout")] public string Payout { get; set; } /// <summary> /// ID of [subscription](#core-endpoints-subscriptions) from which this /// payment was created.<br/>_Note_: this property will only be present /// if this payment is part of a subscription. /// </summary> [JsonProperty("subscription")] public string Subscription { get; set; } } /// <summary> /// One of: /// <ul> /// <li>`pending_customer_approval`: we're waiting for the customer to approve this payment</li> /// <li>`pending_submission`: the payment has been created, but not yet submitted to the /// banks</li> /// <li>`submitted`: the payment has been submitted to the banks</li> /// <li>`confirmed`: the payment has been confirmed as collected</li> /// <li>`paid_out`: the payment has been included in a [payout](#core-endpoints-payouts)</li> /// <li>`cancelled`: the payment has been cancelled</li> /// <li>`customer_approval_denied`: the customer has denied approval for the payment. You should /// contact the customer directly</li> /// <li>`failed`: the payment failed to be processed. Note that payments can fail after being /// confirmed if the failure message is sent late by the banks.</li> /// <li>`charged_back`: the payment has been charged back</li> /// </ul> /// </summary> [JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)] public enum PaymentStatus { /// <summary>Unknown status</summary> [EnumMember(Value = "unknown")] Unknown = 0, /// <summary>`status` with a value of "pending_customer_approval"</summary> [EnumMember(Value = "pending_customer_approval")] PendingCustomerApproval, /// <summary>`status` with a value of "pending_submission"</summary> [EnumMember(Value = "pending_submission")] PendingSubmission, /// <summary>`status` with a value of "submitted"</summary> [EnumMember(Value = "submitted")] Submitted, /// <summary>`status` with a value of "confirmed"</summary> [EnumMember(Value = "confirmed")] Confirmed, /// <summary>`status` with a value of "paid_out"</summary> [EnumMember(Value = "paid_out")] PaidOut, /// <summary>`status` with a value of "cancelled"</summary> [EnumMember(Value = "cancelled")] Cancelled, /// <summary>`status` with a value of "customer_approval_denied"</summary> [EnumMember(Value = "customer_approval_denied")] CustomerApprovalDenied, /// <summary>`status` with a value of "failed"</summary> [EnumMember(Value = "failed")] Failed, /// <summary>`status` with a value of "charged_back"</summary> [EnumMember(Value = "charged_back")] ChargedBack, } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using RestSharp; using Systran.MultimodalClientLib.Client; using Systran.MultimodalClientLib.Model; namespace Systran.MultimodalClientLib.Api { public interface ISpeechApi { /// <summary> /// Align speech Align text and audio files.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="TextFile">Plain text file, ASCII, ISO-8859 or UTF8 encoded.\n\nThe text should include one sentence or clause per line ending with a punctuation mark.\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Model">Model name\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechAlignResponse</returns> SpeechAlignResponse MultimodalSpeechAlignGet (string AudioFile, string TextFile, string Lang, string Model, string Sampling, string Callback); /// <summary> /// Align speech Align text and audio files.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="TextFile">Plain text file, ASCII, ISO-8859 or UTF8 encoded.\n\nThe text should include one sentence or clause per line ending with a punctuation mark.\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Model">Model name\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechAlignResponse</returns> Task<SpeechAlignResponse> MultimodalSpeechAlignGetAsync (string AudioFile, string TextFile, string Lang, string Model, string Sampling, string Callback); /// <summary> /// Speech language detection Detect languages from an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechDetectLanguageResponse</returns> SpeechDetectLanguageResponse MultimodalSpeechDetectLanguageGet (string AudioFile, string Sampling, int? MaxSpeaker, string Callback); /// <summary> /// Speech language detection Detect languages from an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechDetectLanguageResponse</returns> Task<SpeechDetectLanguageResponse> MultimodalSpeechDetectLanguageGetAsync (string AudioFile, string Sampling, int? MaxSpeaker, string Callback); /// <summary> /// Segment speech Segment an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechSegmentResponse</returns> SpeechSegmentResponse MultimodalSpeechSegmentGet (string AudioFile, string Sampling, int? MaxSpeaker, string Callback); /// <summary> /// Segment speech Segment an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechSegmentResponse</returns> Task<SpeechSegmentResponse> MultimodalSpeechSegmentGetAsync (string AudioFile, string Sampling, int? MaxSpeaker, string Callback); /// <summary> /// Supported Languages List of languages in which Speech is supported.\n /// </summary> /// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechSupportedLanguagesResponse</returns> SpeechSupportedLanguagesResponse MultimodalSpeechSupportedLanguagesGet (string Callback); /// <summary> /// Supported Languages List of languages in which Speech is supported.\n /// </summary> /// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechSupportedLanguagesResponse</returns> Task<SpeechSupportedLanguagesResponse> MultimodalSpeechSupportedLanguagesGetAsync (string Callback); /// <summary> /// Transcribe speech Get text from an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Model">Model name\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechTranscribeResponse</returns> SpeechTranscribeResponse MultimodalSpeechTranscribeGet (string AudioFile, string Lang, string Model, string Sampling, int? MaxSpeaker, string Callback); /// <summary> /// Transcribe speech Get text from an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Model">Model name\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechTranscribeResponse</returns> Task<SpeechTranscribeResponse> MultimodalSpeechTranscribeGetAsync (string AudioFile, string Lang, string Model, string Sampling, int? MaxSpeaker, string Callback); } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class SpeechApi : ISpeechApi { /// <summary> /// Initializes a new instance of the <see cref="SpeechApi"/> class. /// </summary> /// <param name="apiClient"> an instance of ApiClient (optional) /// <returns></returns> public SpeechApi(ApiClient apiClient = null) { if (apiClient == null) { // use the default one in Configuration this.apiClient = Configuration.apiClient; } else { this.apiClient = apiClient; } } /// <summary> /// Initializes a new instance of the <see cref="SpeechApi"/> class. /// </summary> /// <returns></returns> public SpeechApi(String basePath) { this.apiClient = new ApiClient(basePath); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> public void SetBasePath(String basePath) { this.apiClient.basePath = basePath; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath(String basePath) { return this.apiClient.basePath; } /// <summary> /// Gets or sets the API client. /// </summary> /// <value>The API client</value> public ApiClient apiClient {get; set;} /// <summary> /// Align speech Align text and audio files.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="TextFile">Plain text file, ASCII, ISO-8859 or UTF8 encoded.\n\nThe text should include one sentence or clause per line ending with a punctuation mark.\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Model">Model name\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechAlignResponse</returns> public SpeechAlignResponse MultimodalSpeechAlignGet (string AudioFile, string TextFile, string Lang, string Model, string Sampling, string Callback) { // verify the required parameter 'AudioFile' is set if (AudioFile == null) throw new ApiException(400, "Missing required parameter 'AudioFile' when calling MultimodalSpeechAlignGet"); // verify the required parameter 'TextFile' is set if (TextFile == null) throw new ApiException(400, "Missing required parameter 'TextFile' when calling MultimodalSpeechAlignGet"); // verify the required parameter 'Lang' is set if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling MultimodalSpeechAlignGet"); var path = "/multimodal/speech/align"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter if (Model != null) queryParams.Add("model", apiClient.ParameterToString(Model)); // query parameter if (Sampling != null) queryParams.Add("sampling", apiClient.ParameterToString(Sampling)); // query parameter if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter if (AudioFile != null) fileParams.Add("audioFile", AudioFile); if (TextFile != null) fileParams.Add("textFile", TextFile); // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechAlignGet: " + response.Content, response.Content); } return (SpeechAlignResponse) apiClient.Deserialize(response.Content, typeof(SpeechAlignResponse)); } /// <summary> /// Align speech Align text and audio files.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="TextFile">Plain text file, ASCII, ISO-8859 or UTF8 encoded.\n\nThe text should include one sentence or clause per line ending with a punctuation mark.\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Model">Model name\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechAlignResponse</returns> public async Task<SpeechAlignResponse> MultimodalSpeechAlignGetAsync (string AudioFile, string TextFile, string Lang, string Model, string Sampling, string Callback) { // verify the required parameter 'AudioFile' is set if (AudioFile == null) throw new ApiException(400, "Missing required parameter 'AudioFile' when calling MultimodalSpeechAlignGet"); // verify the required parameter 'TextFile' is set if (TextFile == null) throw new ApiException(400, "Missing required parameter 'TextFile' when calling MultimodalSpeechAlignGet"); // verify the required parameter 'Lang' is set if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling MultimodalSpeechAlignGet"); var path = "/multimodal/speech/align"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter if (Model != null) queryParams.Add("model", apiClient.ParameterToString(Model)); // query parameter if (Sampling != null) queryParams.Add("sampling", apiClient.ParameterToString(Sampling)); // query parameter if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter if (AudioFile != null) fileParams.Add("audioFile", AudioFile); if (TextFile != null) fileParams.Add("textFile", TextFile); // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechAlignGet: " + response.Content, response.Content); } return (SpeechAlignResponse) apiClient.Deserialize(response.Content, typeof(SpeechAlignResponse)); } /// <summary> /// Speech language detection Detect languages from an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechDetectLanguageResponse</returns> public SpeechDetectLanguageResponse MultimodalSpeechDetectLanguageGet (string AudioFile, string Sampling, int? MaxSpeaker, string Callback) { // verify the required parameter 'AudioFile' is set if (AudioFile == null) throw new ApiException(400, "Missing required parameter 'AudioFile' when calling MultimodalSpeechDetectLanguageGet"); var path = "/multimodal/speech/detectLanguage"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Sampling != null) queryParams.Add("sampling", apiClient.ParameterToString(Sampling)); // query parameter if (MaxSpeaker != null) queryParams.Add("maxSpeaker", apiClient.ParameterToString(MaxSpeaker)); // query parameter if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter if (AudioFile != null) fileParams.Add("audioFile", AudioFile); // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechDetectLanguageGet: " + response.Content, response.Content); } return (SpeechDetectLanguageResponse) apiClient.Deserialize(response.Content, typeof(SpeechDetectLanguageResponse)); } /// <summary> /// Speech language detection Detect languages from an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechDetectLanguageResponse</returns> public async Task<SpeechDetectLanguageResponse> MultimodalSpeechDetectLanguageGetAsync (string AudioFile, string Sampling, int? MaxSpeaker, string Callback) { // verify the required parameter 'AudioFile' is set if (AudioFile == null) throw new ApiException(400, "Missing required parameter 'AudioFile' when calling MultimodalSpeechDetectLanguageGet"); var path = "/multimodal/speech/detectLanguage"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Sampling != null) queryParams.Add("sampling", apiClient.ParameterToString(Sampling)); // query parameter if (MaxSpeaker != null) queryParams.Add("maxSpeaker", apiClient.ParameterToString(MaxSpeaker)); // query parameter if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter if (AudioFile != null) fileParams.Add("audioFile", AudioFile); // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechDetectLanguageGet: " + response.Content, response.Content); } return (SpeechDetectLanguageResponse) apiClient.Deserialize(response.Content, typeof(SpeechDetectLanguageResponse)); } /// <summary> /// Segment speech Segment an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechSegmentResponse</returns> public SpeechSegmentResponse MultimodalSpeechSegmentGet (string AudioFile, string Sampling, int? MaxSpeaker, string Callback) { // verify the required parameter 'AudioFile' is set if (AudioFile == null) throw new ApiException(400, "Missing required parameter 'AudioFile' when calling MultimodalSpeechSegmentGet"); var path = "/multimodal/speech/segment"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Sampling != null) queryParams.Add("sampling", apiClient.ParameterToString(Sampling)); // query parameter if (MaxSpeaker != null) queryParams.Add("maxSpeaker", apiClient.ParameterToString(MaxSpeaker)); // query parameter if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter if (AudioFile != null) fileParams.Add("audioFile", AudioFile); // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechSegmentGet: " + response.Content, response.Content); } return (SpeechSegmentResponse) apiClient.Deserialize(response.Content, typeof(SpeechSegmentResponse)); } /// <summary> /// Segment speech Segment an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechSegmentResponse</returns> public async Task<SpeechSegmentResponse> MultimodalSpeechSegmentGetAsync (string AudioFile, string Sampling, int? MaxSpeaker, string Callback) { // verify the required parameter 'AudioFile' is set if (AudioFile == null) throw new ApiException(400, "Missing required parameter 'AudioFile' when calling MultimodalSpeechSegmentGet"); var path = "/multimodal/speech/segment"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Sampling != null) queryParams.Add("sampling", apiClient.ParameterToString(Sampling)); // query parameter if (MaxSpeaker != null) queryParams.Add("maxSpeaker", apiClient.ParameterToString(MaxSpeaker)); // query parameter if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter if (AudioFile != null) fileParams.Add("audioFile", AudioFile); // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechSegmentGet: " + response.Content, response.Content); } return (SpeechSegmentResponse) apiClient.Deserialize(response.Content, typeof(SpeechSegmentResponse)); } /// <summary> /// Supported Languages List of languages in which Speech is supported.\n /// </summary> /// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechSupportedLanguagesResponse</returns> public SpeechSupportedLanguagesResponse MultimodalSpeechSupportedLanguagesGet (string Callback) { var path = "/multimodal/speech/supportedLanguages"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechSupportedLanguagesGet: " + response.Content, response.Content); } return (SpeechSupportedLanguagesResponse) apiClient.Deserialize(response.Content, typeof(SpeechSupportedLanguagesResponse)); } /// <summary> /// Supported Languages List of languages in which Speech is supported.\n /// </summary> /// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechSupportedLanguagesResponse</returns> public async Task<SpeechSupportedLanguagesResponse> MultimodalSpeechSupportedLanguagesGetAsync (string Callback) { var path = "/multimodal/speech/supportedLanguages"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechSupportedLanguagesGet: " + response.Content, response.Content); } return (SpeechSupportedLanguagesResponse) apiClient.Deserialize(response.Content, typeof(SpeechSupportedLanguagesResponse)); } /// <summary> /// Transcribe speech Get text from an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Model">Model name\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechTranscribeResponse</returns> public SpeechTranscribeResponse MultimodalSpeechTranscribeGet (string AudioFile, string Lang, string Model, string Sampling, int? MaxSpeaker, string Callback) { // verify the required parameter 'AudioFile' is set if (AudioFile == null) throw new ApiException(400, "Missing required parameter 'AudioFile' when calling MultimodalSpeechTranscribeGet"); // verify the required parameter 'Lang' is set if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling MultimodalSpeechTranscribeGet"); var path = "/multimodal/speech/transcribe"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter if (Model != null) queryParams.Add("model", apiClient.ParameterToString(Model)); // query parameter if (Sampling != null) queryParams.Add("sampling", apiClient.ParameterToString(Sampling)); // query parameter if (MaxSpeaker != null) queryParams.Add("maxSpeaker", apiClient.ParameterToString(MaxSpeaker)); // query parameter if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter if (AudioFile != null) fileParams.Add("audioFile", AudioFile); // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechTranscribeGet: " + response.Content, response.Content); } return (SpeechTranscribeResponse) apiClient.Deserialize(response.Content, typeof(SpeechTranscribeResponse)); } /// <summary> /// Transcribe speech Get text from an audio file.\n /// </summary> /// <param name="AudioFile">Audio file ([details](#description_audio_files)).\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Model">Model name\n</param>/// <param name="Sampling">Sampling quality of the audio file.\n * high: wide band audio such as radio and TV broadcast (sampling higher or equal to 16KHz)\n * low: telephone data with sampling rates higher or equal to 8KHz. It is highly recommended to not use a bit rate lower than 32Kbps.\n</param>/// <param name="MaxSpeaker">Maximum number of speakers. Default 1 for low sampling and infinity for high sampling</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param> /// <returns>SpeechTranscribeResponse</returns> public async Task<SpeechTranscribeResponse> MultimodalSpeechTranscribeGetAsync (string AudioFile, string Lang, string Model, string Sampling, int? MaxSpeaker, string Callback) { // verify the required parameter 'AudioFile' is set if (AudioFile == null) throw new ApiException(400, "Missing required parameter 'AudioFile' when calling MultimodalSpeechTranscribeGet"); // verify the required parameter 'Lang' is set if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling MultimodalSpeechTranscribeGet"); var path = "/multimodal/speech/transcribe"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, String>(); String postBody = null; if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter if (Model != null) queryParams.Add("model", apiClient.ParameterToString(Model)); // query parameter if (Sampling != null) queryParams.Add("sampling", apiClient.ParameterToString(Sampling)); // query parameter if (MaxSpeaker != null) queryParams.Add("maxSpeaker", apiClient.ParameterToString(MaxSpeaker)); // query parameter if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter if (AudioFile != null) fileParams.Add("audioFile", AudioFile); // authentication setting, if any String[] authSettings = new String[] { "accessToken", "apiKey" }; // make the HTTP request IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling MultimodalSpeechTranscribeGet: " + response.Content, response.Content); } return (SpeechTranscribeResponse) apiClient.Deserialize(response.Content, typeof(SpeechTranscribeResponse)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace Xamarin.Forms { public static class MessagingCenter { class Sender : Tuple<string, Type, Type> { public Sender(string message, Type senderType, Type argType) : base(message, senderType, argType) { } } delegate bool Filter(object sender); class MaybeWeakReference { WeakReference DelegateWeakReference { get; set; } object DelegateStrongReference { get; set; } readonly bool _isStrongReference; public MaybeWeakReference(object subscriber, object delegateSource) { if (subscriber.Equals(delegateSource)) { // The target is the subscriber; we can use a weakreference DelegateWeakReference = new WeakReference(delegateSource); _isStrongReference = false; } else { DelegateStrongReference = delegateSource; _isStrongReference = true; } } public object Target => _isStrongReference ? DelegateStrongReference : DelegateWeakReference.Target; public bool IsAlive => _isStrongReference || DelegateWeakReference.IsAlive; } class Subscription : Tuple<WeakReference, MaybeWeakReference, MethodInfo, Filter> { public Subscription(object subscriber, object delegateSource, MethodInfo methodInfo, Filter filter) : base(new WeakReference(subscriber), new MaybeWeakReference(subscriber, delegateSource), methodInfo, filter) { } public WeakReference Subscriber => Item1; MaybeWeakReference DelegateSource => Item2; MethodInfo MethodInfo => Item3; Filter Filter => Item4; public void InvokeCallback(object sender, object args) { if (!Filter(sender)) { return; } if (MethodInfo.IsStatic) { MethodInfo.Invoke(null, MethodInfo.GetParameters().Length == 1 ? new[] { sender } : new[] { sender, args }); return; } var target = DelegateSource.Target; if (target == null) { return; // Collected } MethodInfo.Invoke(target, MethodInfo.GetParameters().Length == 1 ? new[] { sender } : new[] { sender, args }); } public bool CanBeRemoved() { return !Subscriber.IsAlive || !DelegateSource.IsAlive; } } static readonly Dictionary<Sender, List<Subscription>> s_subscriptions = new Dictionary<Sender, List<Subscription>>(); public static void Send<TSender, TArgs>(TSender sender, string message, TArgs args) where TSender : class { if (sender == null) throw new ArgumentNullException(nameof(sender)); InnerSend(message, typeof(TSender), typeof(TArgs), sender, args); } public static void Send<TSender>(TSender sender, string message) where TSender : class { if (sender == null) throw new ArgumentNullException(nameof(sender)); InnerSend(message, typeof(TSender), null, sender, null); } public static void Subscribe<TSender, TArgs>(object subscriber, string message, Action<TSender, TArgs> callback, TSender source = null) where TSender : class { if (subscriber == null) throw new ArgumentNullException(nameof(subscriber)); if (callback == null) throw new ArgumentNullException(nameof(callback)); var target = callback.Target; Filter filter = sender => { var send = (TSender)sender; return (source == null || send == source); }; InnerSubscribe(subscriber, message, typeof(TSender), typeof(TArgs), target, callback.GetMethodInfo(), filter); } public static void Subscribe<TSender>(object subscriber, string message, Action<TSender> callback, TSender source = null) where TSender : class { if (subscriber == null) throw new ArgumentNullException(nameof(subscriber)); if (callback == null) throw new ArgumentNullException(nameof(callback)); var target = callback.Target; Filter filter = sender => { var send = (TSender)sender; return (source == null || send == source); }; InnerSubscribe(subscriber, message, typeof(TSender), null, target, callback.GetMethodInfo(), filter); } public static void Unsubscribe<TSender, TArgs>(object subscriber, string message) where TSender : class { InnerUnsubscribe(message, typeof(TSender), typeof(TArgs), subscriber); } public static void Unsubscribe<TSender>(object subscriber, string message) where TSender : class { InnerUnsubscribe(message, typeof(TSender), null, subscriber); } internal static void ClearSubscribers() { s_subscriptions.Clear(); } static void InnerSend(string message, Type senderType, Type argType, object sender, object args) { if (message == null) throw new ArgumentNullException(nameof(message)); var key = new Sender(message, senderType, argType); if (!s_subscriptions.ContainsKey(key)) return; List<Subscription> subcriptions = s_subscriptions[key]; if (subcriptions == null || !subcriptions.Any()) return; // should not be reachable // ok so this code looks a bit funky but here is the gist of the problem. It is possible that in the course // of executing the callbacks for this message someone will subscribe/unsubscribe from the same message in // the callback. This would invalidate the enumerator. To work around this we make a copy. However if you unsubscribe // from a message you can fairly reasonably expect that you will therefor not receive a call. To fix this we then // check that the item we are about to send the message to actually exists in the live list. List<Subscription> subscriptionsCopy = subcriptions.ToList(); foreach (Subscription subscription in subscriptionsCopy) { if (subscription.Subscriber.Target != null && subcriptions.Contains(subscription)) { subscription.InvokeCallback(sender, args); } } } static void InnerSubscribe(object subscriber, string message, Type senderType, Type argType, object target, MethodInfo methodInfo, Filter filter) { if (message == null) throw new ArgumentNullException(nameof(message)); var key = new Sender(message, senderType, argType); var value = new Subscription(subscriber, target, methodInfo, filter); if (s_subscriptions.ContainsKey(key)) { s_subscriptions[key].Add(value); } else { var list = new List<Subscription> { value }; s_subscriptions[key] = list; } } static void InnerUnsubscribe(string message, Type senderType, Type argType, object subscriber) { if (subscriber == null) throw new ArgumentNullException(nameof(subscriber)); if (message == null) throw new ArgumentNullException(nameof(message)); var key = new Sender(message, senderType, argType); if (!s_subscriptions.ContainsKey(key)) return; s_subscriptions[key].RemoveAll(sub => sub.CanBeRemoved() || sub.Subscriber.Target == subscriber); if (!s_subscriptions[key].Any()) s_subscriptions.Remove(key); } } }
using System; using System.Linq.Expressions; using NSpec.Domain; using System.Threading.Tasks; namespace NSpec { /// <summary> /// Inherit from this class to create your own specifications. NSpecRunner will look through your project for /// classes that derive from this class (inheritance chain is taken into consideration). /// </summary> public class nspec { public nspec() { context = new ActionRegister(AddContext); xcontext = new ActionRegister(AddIgnoredContext); describe = new ActionRegister(AddContext); xdescribe = new ActionRegister(AddIgnoredContext); it = new ActionRegister((name, tags, action) => AddExample(new Example(name, tags, action, pending: action == todo))); xit = new ActionRegister((name, tags, action) => AddExample(new Example(name, tags, action, pending: true))); itAsync = new AsyncActionRegister((name, tags, asyncAction) => AddExample(new AsyncExample(name, tags, asyncAction, pending: asyncAction == todoAsync))); xitAsync = new AsyncActionRegister((name, tags, asyncAction) => AddExample(new AsyncExample(name, tags, asyncAction, pending: true))); } /// <summary> /// Create a specification/example using a single line lambda with an assertion(should). /// The name of the specification will be parsed from the Expression /// <para>For Example:</para> /// <para>specify = () => _controller.should_be(false);</para> /// </summary> public virtual Expression<Action> specify { set { AddExample(new Example(value)); } } /* No need for the following, as async lambda expressions cannot be converted to expression trees: public virtual Expression<Func<Task>> specifyAsync { ... } */ /// <summary> /// Mark a spec as pending /// <para>For Example:</para> /// <para>xspecify = () => _controller.should_be(false);</para> /// <para>(the example will be marked as pending any lambda provided will not be executed)</para> /// </summary> public virtual Expression<Action> xspecify { set { AddExample(new Example(value, pending: true)); } } /* No need for the following, as async lambda expressions cannot be converted to expression trees: public virtual Expression<Func<Task>> xspecifyAsync { ... } */ /// <summary> /// This Action gets executed before each example is run. /// <para>For Example:</para> /// <para>before = () => someList = new List&lt;int&gt;();</para> /// <para>The before can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Action before { get { return Context.Before; } set { Context.Before = value; } } /// <summary> /// This Function gets executed asynchronously before each example is run. /// <para>For Example:</para> /// <para>beforeAsync = async () => someList = await GetListAsync();</para> /// <para>The beforeAsync can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Func<Task> beforeAsync { get { return Context.BeforeAsync; } set { Context.BeforeAsync = value; } } /// <summary> /// This Action is an alias of before. This Action gets executed before each example is run. /// <para>For Example:</para> /// <para>beforeEach = () => someList = new List&lt;int&gt;();</para> /// <para>The beforeEach can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Action beforeEach { get { return Context.Before; } set { Context.Before = value; } } /// <summary> /// This Function is an alias of beforeAsync. It gets executed asynchronously before each example is run. /// <para>For Example:</para> /// <para>beforeEachAsync = async () => someList = await GetListAsync();</para> /// <para>The beforeEachAsync can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Func<Task> beforeEachAsync { get { return Context.BeforeAsync; } set { Context.BeforeAsync = value; } } /// <summary> /// This Action gets executed before all examples in a context. /// <para>For Example:</para> /// <para>beforeAll = () => someList = new List&lt;int&gt;();</para> /// <para>The beforeAll can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Action beforeAll { get { return Context.BeforeAll; } set { Context.BeforeAll = value; } } /// <summary> /// This Function gets executed asynchronously before all examples in a context. /// <para>For Example:</para> /// <para>beforeAllAsync = async () => someList = await GetListAsync();</para> /// <para>The beforeAllAsync can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Func<Task> beforeAllAsync { get { return Context.BeforeAllAsync; } set { Context.BeforeAllAsync = value; } } /// <summary> /// This Action gets executed after each example is run. /// <para>For Example:</para> /// <para>after = () => someList = new List&lt;int&gt;();</para> /// <para>The after can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Action after { get { return Context.After; } set { Context.After = value; } } /// <summary> /// This Function gets executed asynchronously after each example is run. /// <para>For Example:</para> /// <para>afterAsync = async () => someList = await GetListAsync();</para> /// <para>The after can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Func<Task> afterAsync { get { return Context.AfterAsync; } set { Context.AfterAsync = value; } } /// <summary> /// This Action is an alias of after. This Action gets executed after each example is run. /// <para>For Example:</para> /// <para>afterEach = () => someList = new List&lt;int&gt;();</para> /// <para>The afterEach can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Action afterEach { get { return Context.After; } set { Context.After = value; } } /// <summary> /// This Action is an alias of afterAsync. This Function gets executed asynchronously after each example is run. /// <para>For Example:</para> /// <para>afterEachAsync = async () => someList = await GetListAsync();</para> /// <para>The after can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Func<Task> afterEachAsync { get { return Context.AfterAsync; } set { Context.AfterAsync = value; } } /// <summary> /// This Action gets executed after all examples in a context. /// <para>For Example:</para> /// <para>afterAll = () => someList = new List&lt;int&gt;();</para> /// <para>The afterAll can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Action afterAll { get { return Context.AfterAll; } set { Context.AfterAll = value; } } /// <summary> /// This Function gets executed asynchronously after all examples in a context. /// <para>For Example:</para> /// <para>afterAllAsync = async () => someList = await GetListAsync();</para> /// <para>The afterAllAsync can be a multi-line lambda. Setting the member multiple times through out sub-contexts will not override the action, but instead will append to your setup (this is a good thing). For more information visit http://www.nspec.org</para> /// </summary> public virtual Func<Task> afterAllAsync { get { return Context.AfterAllAsync; } set { Context.AfterAllAsync = value; } } /// <summary> /// Assign this member within your context. The Action assigned will gets executed /// with every example in scope. Befores will run first, then acts, then your examples. It's a way for you to define once a common Act in Arrange-Act-Assert for all subcontexts. For more information visit http://www.nspec.org /// </summary> public virtual Action act { get { return Context.Act; } set { Context.Act = value; } } /// <summary> /// Assign this member within your context. The Function assigned will gets executed asynchronously /// with every example in scope. Befores will run first, then acts, then your examples. It's a way for you to define once a common Act in Arrange-Act-Assert for all subcontexts. For more information visit http://www.nspec.org /// </summary> public virtual Func<Task> actAsync { get { return Context.ActAsync; } set { Context.ActAsync = value; } } /// <summary> /// Create a subcontext. /// <para>For Examples see http://www.nspec.org</para> /// </summary> public ActionRegister context; /// <summary> /// Mark a subcontext as pending (add all child contexts as pending) /// </summary> public ActionRegister xcontext; /// <summary> /// This is an alias for creating a subcontext. Use this to create sub contexts within your methods. /// <para>For Examples see http://www.nspec.org</para> /// </summary> public ActionRegister describe; /// <summary> /// This is an alias for creating a xcontext. /// <para>For Examples see http://www.nspec.org</para> /// </summary> public ActionRegister xdescribe; /// <summary> /// Create a specification/example using a name and a lambda with an assertion(should). /// <para>For Example:</para> /// <para>it["should return false"] = () => _controller.should_be(false);</para> /// </summary> public ActionRegister it; /// <summary> /// Create an asynchronous specification/example using a name and an async lambda with an assertion(should). /// <para>For Example:</para> /// <para>itAsync["should return false"] = async () => (await GetResultAsync()).should_be(false);</para> /// </summary> public AsyncActionRegister itAsync; /// <summary> /// Mark a spec as pending /// <para>For Example:</para> /// <para>xit["should return false"] = () => _controller.should_be(false);</para> /// <para>(the example will be marked as pending, any lambda provided will not be executed)</para> /// </summary> public ActionRegister xit; /// <summary> /// Mark an asynchronous spec as pending /// <para>For Example:</para> /// <para>xitAsync["should return false"] = async () => (await GetResultAsync()).should_be(false);</para> /// <para>(the example will be marked as pending, any lambda provided will not be executed)</para> /// </summary> public AsyncActionRegister xitAsync; /// <summary> /// Set up a pending spec. /// <para>For Example:</para> /// <para>it["a test i haven't flushed out yet, but need to"] = todo;</para> /// </summary> public readonly Action todo = () => { }; /// <summary> /// Set up a pending asynchronous spec. /// <para>For Example:</para> /// <para>itAsync["a test i haven't flushed out yet, but need to"] = todoAsync;</para> /// </summary> public readonly Func<Task> todoAsync = () => Task.Run(() => { }); /// <summary> /// Set up an expectation for a particular exception type to be thrown before expectation. /// <para>For Example:</para> /// <para>it["should throw exception"] = expect&lt;InvalidOperationException&gt;();</para> /// </summary> public virtual Action expect<T>() where T : Exception { return expect<T>(expectedMessage: null); } /// <summary> /// Set up an expectation for a particular exception type to be thrown before expectation, with an expected message. /// <para>For Example:</para> /// <para>it["should throw exception"] = expect&lt;InvalidOperationException&gt;();</para> /// </summary> public virtual Action expect<T>(string expectedMessage) where T : Exception { var specContext = Context; return () => { var actException = specContext.ActChain.AnyException(); if (actException == null) throw new ExceptionNotThrown(IncorrectType<T>()); AssertExpectedException<T>(actException, expectedMessage); // do not clear exception right now, during first phase, but leave a note for second phase specContext.ClearExpectedException = true; }; } /// <summary> /// Set up an expectation for a particular exception type to be thrown inside passed action. /// <para>For Example:</para> /// <para>it["should throw exception"] = expect&lt;InvalidOperationException&gt;(() => SomeMethodThatThrowsException());</para> /// </summary> public virtual Action expect<T>(Action action) where T : Exception { return expect<T>(null, action); } /// <summary> /// Set up an expectation for a particular exception type to be thrown inside passed action, with an expected message. /// <para>For Example:</para> /// <para>it["should throw exception with message Error"] = expect&lt;InvalidOperationException&gt;("Error", () => SomeMethodThatThrowsException());</para> /// </summary> public virtual Action expect<T>(string expectedMessage, Action action) where T : Exception { return () => { var closureType = typeof(T); try { action(); throw new ExceptionNotThrown(IncorrectType<T>()); } catch (ExceptionNotThrown) { throw; } catch (Exception ex) { AssertExpectedException<T>(ex, expectedMessage); } }; } /// <summary> /// Set up an asynchronous expectation for a particular exception type to be thrown inside passed asynchronous action. /// <para>For Example:</para> /// <para>itAsync["should throw exception"] = expectAsync&lt;InvalidOperationException&gt;(async () => await SomeAsyncMethodThatThrowsException());</para> /// </summary> public virtual Func<Task> expectAsync<T>(Func<Task> asyncAction) where T : Exception { return expectAsync<T>(null, asyncAction); } /// <summary> /// Set up an asynchronous expectation for a particular exception type to be thrown inside passed asynchronous action, with an expected message. /// <para>For Example:</para> /// <para>itAsync["should throw exception with message Error"] = expectAsync&lt;InvalidOperationException&gt;("Error", async () => await SomeAsyncMethodThatThrowsException());</para> /// </summary> public virtual Func<Task> expectAsync<T>(string expectedMessage, Func<Task> asyncAction) where T : Exception { return async () => { var closureType = typeof(T); try { await asyncAction(); throw new ExceptionNotThrown(IncorrectType<T>()); } catch (ExceptionNotThrown) { throw; } catch (Exception ex) { AssertExpectedException<T>(ex, expectedMessage); } }; } /// <summary> /// Override this method to alter the stack trace that NSpec prints. This is useful to override /// if you want to provide additional information (eg. information from a log that is generated out of proc). /// </summary> /// <param name="flattenedStackTrace">A clean stack trace that excludes NSpec specfic namespaces</param> /// <returns></returns> public virtual string StackTraceToPrint(string flattenedStackTrace) { return flattenedStackTrace; } /// <summary> /// Override this method to return another exception in the event of a failure of a test. This is useful to override /// when catching for specific exceptions and returning a more meaningful exception to the developer. /// </summary> /// <param name="originalException">Original exception that was thrown.</param> /// <returns></returns> public virtual Exception ExceptionToReturn(Exception originalException) { return originalException; } // TODO if this is intendend to be overridden by client spec classes, add describing comments public virtual string OnError(string flattenedStackTrace) { return flattenedStackTrace; } static string IncorrectType<T>() where T : Exception { return "Exception of type " + typeof(T).Name + " was not thrown."; } static string IncorrectMessage(string expected, string actual) { return String.Format("Expected message: \"{0}\" But was: \"{1}\"", expected, actual); } void AddExample(ExampleBase example) { Context.AddExample(example); } void AddContext(string name, string tags, Action action) { var childContext = new Context(name, tags); RunContext(childContext, action); } void AddIgnoredContext(string name, string tags, Action action) { var ignored = new Context(name, tags, isPending: true); RunContext(ignored, action); } void RunContext(Context subContext, Action action) { Context.AddContext(subContext); var originalContext = Context; Context = subContext; try { action(); } catch (Exception ex) { AddFailingExample(ex); } Context = originalContext; } void AddFailingExample(Exception reportedEx) { string exampleName = "Context body throws an exception of type '{0}'".With(reportedEx.GetType().Name); it[exampleName] = () => { throw new ContextBareCodeException(reportedEx); }; } void AssertExpectedException<T>(Exception actualException, string expectedMessage) where T : Exception { var expectedType = typeof(T); Exception matchingException = null; if (actualException.GetType() == expectedType) { matchingException = actualException; } else { var aggregateException = actualException as AggregateException; if (aggregateException != null) { foreach (var innerException in aggregateException.InnerExceptions) { if (innerException.GetType() == expectedType) { matchingException = innerException; break; } } } } if (matchingException == null) { throw new ExceptionNotThrown(IncorrectType<T>()); } if (expectedMessage != null && expectedMessage != matchingException.Message) { throw new ExceptionNotThrown(IncorrectMessage(expectedMessage, matchingException.Message)); } } internal Context Context { get; set; } /// <summary>Tags required to be present or not present in context or example</summary> /// <remarks> /// Currently, multiple tags indicates any of the tags must be present to be included/excluded. In other words, they are OR'd, not AND'd. /// NOTE: Cucumber's tags wiki offers ideas for handling tags: https://github.com/cucumber/cucumber/wiki/tags /// </remarks> internal Tags tagsFilter = new Tags(); } }
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Linq; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Reflection; using System.Web.Hosting; using Spark.Bindings; using Spark.Compiler; using Spark.Compiler.CSharp; using Spark.Parser; using Spark.FileSystem; using Spark.Parser.Syntax; namespace Spark { public class SparkViewEngine : ISparkViewEngine, ISparkServiceInitialize { public SparkViewEngine() : this(null) { } public SparkViewEngine(ISparkSettings settings) { Settings = settings ?? (ISparkSettings)ConfigurationManager.GetSection("spark") ?? new SparkSettings(); SyntaxProvider = new DefaultSyntaxProvider(Settings); ViewActivatorFactory = new DefaultViewActivator(); } public void Initialize(ISparkServiceContainer container) { Settings = container.GetService<ISparkSettings>(); SyntaxProvider = container.GetService<ISparkSyntaxProvider>(); ViewActivatorFactory = container.GetService<IViewActivatorFactory>(); LanguageFactory = container.GetService<ISparkLanguageFactory>(); BindingProvider = container.GetService<IBindingProvider>(); ResourcePathManager = container.GetService<IResourcePathManager>(); TemplateLocator = container.GetService<ITemplateLocator>(); CompiledViewHolder = container.GetService<ICompiledViewHolder>(); PartialProvider = container.GetService<IPartialProvider>(); PartialReferenceProvider = container.GetService<IPartialReferenceProvider>(); SetViewFolder(container.GetService<IViewFolder>()); } private IViewFolder _viewFolder; public IViewFolder ViewFolder { get { if (_viewFolder == null) SetViewFolder(CreateDefaultViewFolder()); return _viewFolder; } set { SetViewFolder(value); } } private ISparkLanguageFactory _langaugeFactory; public ISparkLanguageFactory LanguageFactory { get { if (_langaugeFactory == null) _langaugeFactory = new DefaultLanguageFactory(); return _langaugeFactory; } set { _langaugeFactory = value; } } private IBindingProvider _bindingProvider; public IBindingProvider BindingProvider { get { if (_bindingProvider == null) _bindingProvider = new DefaultBindingProvider(); return _bindingProvider; } set { _bindingProvider = value; } } private IPartialProvider _partialProvider; public IPartialProvider PartialProvider { get { if (_partialProvider == null) _partialProvider = new DefaultPartialProvider(); return _partialProvider; } set { _partialProvider = value; } } private IPartialReferenceProvider _partialReferenceProvider; public IPartialReferenceProvider PartialReferenceProvider { get { if (_partialReferenceProvider == null) _partialReferenceProvider = new DefaultPartialReferenceProvider(() => PartialProvider); return _partialReferenceProvider; } set { _partialReferenceProvider = value; } } private static IViewFolder CreateDefaultViewFolder() { if (HostingEnvironment.IsHosted && HostingEnvironment.VirtualPathProvider != null) return new VirtualPathProviderViewFolder("~/Views"); var appBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; return new FileSystemViewFolder(Path.Combine(appBase, "Views")); } private void SetViewFolder(IViewFolder value) { var aggregateViewFolder = value; foreach (var viewFolderSettings in Settings.ViewFolders) { IViewFolder viewFolder = ActivateViewFolder(viewFolderSettings); if (!string.IsNullOrEmpty(viewFolderSettings.Subfolder)) viewFolder = new SubViewFolder(viewFolder, viewFolderSettings.Subfolder); aggregateViewFolder = aggregateViewFolder.Append(viewFolder); } _viewFolder = aggregateViewFolder; } private IViewFolder ActivateViewFolder(IViewFolderSettings viewFolderSettings) { Type type; switch (viewFolderSettings.FolderType) { case ViewFolderType.FileSystem: type = typeof(FileSystemViewFolder); break; case ViewFolderType.EmbeddedResource: type = typeof(EmbeddedViewFolder); break; case ViewFolderType.VirtualPathProvider: type = typeof(VirtualPathProviderViewFolder); break; case ViewFolderType.Custom: type = Type.GetType(viewFolderSettings.Type); break; default: throw new ArgumentException("Unknown value for view folder type"); } ConstructorInfo bestConstructor = null; foreach (var constructor in type.GetConstructors()) { if (bestConstructor == null || bestConstructor.GetParameters().Length < constructor.GetParameters().Length) { if (constructor.GetParameters().All(param => viewFolderSettings.Parameters.ContainsKey(param.Name))) { bestConstructor = constructor; } } } if (bestConstructor == null) throw new MissingMethodException(string.Format("No suitable constructor for {0} located", type.FullName)); var args = bestConstructor.GetParameters() .Select(param => ChangeType(viewFolderSettings, param)) .ToArray(); return (IViewFolder)Activator.CreateInstance(type, args); } private object ChangeType(IViewFolderSettings viewFolderSettings, ParameterInfo param) { if (param.ParameterType == typeof(Assembly)) return Assembly.Load(viewFolderSettings.Parameters[param.Name]); return Convert.ChangeType(viewFolderSettings.Parameters[param.Name], param.ParameterType); } private IResourcePathManager _resourcePathManager; public IResourcePathManager ResourcePathManager { get { if (_resourcePathManager == null) _resourcePathManager = new DefaultResourcePathManager(Settings); return _resourcePathManager; } set { _resourcePathManager = value; } } public ISparkExtensionFactory ExtensionFactory { get; set; } public IViewActivatorFactory ViewActivatorFactory { get; set; } private ITemplateLocator _templateLocator; public ITemplateLocator TemplateLocator { get { if (_templateLocator == null) _templateLocator = new DefaultTemplateLocator(); return _templateLocator; } set { _templateLocator = value; } } private ICompiledViewHolder _compiledViewHolder; public ICompiledViewHolder CompiledViewHolder { get { if (_compiledViewHolder == null) _compiledViewHolder = new CompiledViewHolder(); return _compiledViewHolder; } set { _compiledViewHolder = value; } } public ISparkSyntaxProvider SyntaxProvider { get; set; } public ISparkSettings Settings { get; set; } public string DefaultPageBaseType { get; set; } public ISparkViewEntry GetEntry(SparkViewDescriptor descriptor) { return CompiledViewHolder.Lookup(descriptor); } public ISparkView CreateInstance(SparkViewDescriptor descriptor) { return CreateEntry(descriptor).CreateInstance(); } public void ReleaseInstance(ISparkView view) { if (view == null) throw new ArgumentNullException("view"); var entry = CompiledViewHolder.Lookup(view.GeneratedViewId); if (entry != null) entry.ReleaseInstance(view); } public ISparkViewEntry CreateEntry(SparkViewDescriptor descriptor) { var entry = CompiledViewHolder.Lookup(descriptor); if (entry == null) { entry = CreateEntryInternal(descriptor, true); CompiledViewHolder.Store(entry); } return entry; } public ISparkViewEntry CreateEntryInternal(SparkViewDescriptor descriptor, bool compile) { var entry = new CompiledViewEntry { Descriptor = descriptor, Loader = CreateViewLoader(), Compiler = LanguageFactory.CreateViewCompiler(this, descriptor), LanguageFactory = LanguageFactory }; var chunksLoaded = new List<IList<Chunk>>(); var templatesLoaded = new List<string>(); LoadTemplates(entry.Loader, entry.Descriptor.Templates, chunksLoaded, templatesLoaded); if (compile) { entry.Compiler.CompileView(chunksLoaded, entry.Loader.GetEverythingLoaded()); entry.Activator = ViewActivatorFactory.Register(entry.Compiler.CompiledType); } else { entry.Compiler.GenerateSourceCode(chunksLoaded, entry.Loader.GetEverythingLoaded()); } return entry; } void LoadTemplates(ViewLoader loader, IEnumerable<string> templates, ICollection<IList<Chunk>> chunksLoaded, ICollection<string> templatesLoaded) { foreach (var template in templates) { if (templatesLoaded.Contains(template)) { throw new CompilerException(string.Format( "Unable to include template '{0}' recusively", templates)); } var chunks = loader.Load(template); chunksLoaded.Add(chunks); templatesLoaded.Add(template); } } private ViewLoader CreateViewLoader() { return new ViewLoader { ViewFolder = ViewFolder, SyntaxProvider = SyntaxProvider, ExtensionFactory = ExtensionFactory, Prefix = Settings.Prefix, BindingProvider = BindingProvider, ParseSectionTagAsSegment = Settings.ParseSectionTagAsSegment, AttributeBehaviour = Settings.AttributeBehaviour, PartialProvider = PartialProvider, PartialReferenceProvider = PartialReferenceProvider }; } public Assembly BatchCompilation(IList<SparkViewDescriptor> descriptors) { return BatchCompilation(null /*outputAssembly*/, descriptors); } public Assembly BatchCompilation(string outputAssembly, IList<SparkViewDescriptor> descriptors) { var batch = new List<CompiledViewEntry>(); var sourceCode = new List<string>(); foreach (var descriptor in descriptors) { var entry = new CompiledViewEntry { Descriptor = descriptor, Loader = CreateViewLoader(), Compiler = LanguageFactory.CreateViewCompiler(this, descriptor) }; var chunksLoaded = new List<IList<Chunk>>(); var templatesLoaded = new List<string>(); LoadTemplates(entry.Loader, descriptor.Templates, chunksLoaded, templatesLoaded); entry.Compiler.GenerateSourceCode(chunksLoaded, entry.Loader.GetEverythingLoaded()); sourceCode.Add(entry.Compiler.SourceCode); batch.Add(entry); } var batchCompiler = new BatchCompiler { OutputAssembly = outputAssembly }; var assembly = batchCompiler.Compile(Settings.Debug, "csharp", sourceCode.ToArray()); foreach (var entry in batch) { entry.Compiler.CompiledType = assembly.GetType(entry.Compiler.ViewClassFullName); entry.Activator = ViewActivatorFactory.Register(entry.Compiler.CompiledType); CompiledViewHolder.Store(entry); } return assembly; } public IList<SparkViewDescriptor> LoadBatchCompilation(Assembly assembly) { var descriptors = new List<SparkViewDescriptor>(); foreach (var type in assembly.GetExportedTypes()) { if (!typeof(ISparkView).IsAssignableFrom(type)) continue; var attributes = type.GetCustomAttributes(typeof(SparkViewAttribute), false); if (attributes == null || attributes.Length == 0) continue; var descriptor = ((SparkViewAttribute)attributes[0]).BuildDescriptor(); var entry = new CompiledViewEntry { Descriptor = descriptor, Loader = new ViewLoader { PartialProvider = PartialProvider, PartialReferenceProvider = PartialReferenceProvider }, Compiler = new CSharpViewCompiler { CompiledType = type }, Activator = ViewActivatorFactory.Register(type) }; CompiledViewHolder.Store(entry); descriptors.Add(descriptor); } return descriptors; } } }
// 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.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { public sealed partial class ImmutableSortedSet<T> { /// <summary> /// A node in the AVL tree storing this set. /// </summary> [DebuggerDisplay("{_key}")] internal sealed class Node : IBinaryTree<T>, IEnumerable<T> { /// <summary> /// The default empty node. /// </summary> internal static readonly Node EmptyNode = new Node(); /// <summary> /// The key associated with this node. /// </summary> private readonly T _key; /// <summary> /// A value indicating whether this node has been frozen (made immutable). /// </summary> /// <remarks> /// Nodes must be frozen before ever being observed by a wrapping collection type /// to protect collections from further mutations. /// </remarks> private bool _frozen; /// <summary> /// The depth of the tree beneath this node. /// </summary> private byte _height; // AVL tree max height <= ~1.44 * log2(maxNodes + 2) /// <summary> /// The number of elements contained by this subtree starting at this node. /// </summary> /// <remarks> /// If this node would benefit from saving 4 bytes, we could have only a few nodes /// scattered throughout the graph actually record the count of nodes beneath them. /// Those without the count could query their descendants, which would often short-circuit /// when they hit a node that *does* include a count field. /// </remarks> private int _count; /// <summary> /// The left tree. /// </summary> private Node _left; /// <summary> /// The right tree. /// </summary> private Node _right; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}.Node"/> class /// that is pre-frozen. /// </summary> private Node() { Contract.Ensures(this.IsEmpty); _frozen = true; // the empty node is *always* frozen. } /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}.Node"/> class /// that is not yet frozen. /// </summary> /// <param name="key">The value stored by this node.</param> /// <param name="left">The left branch.</param> /// <param name="right">The right branch.</param> /// <param name="frozen">Whether this node is prefrozen.</param> private Node(T key, Node left, Node right, bool frozen = false) { Requires.NotNull(left, nameof(left)); Requires.NotNull(right, nameof(right)); Debug.Assert(!frozen || (left._frozen && right._frozen)); _key = key; _left = left; _right = right; _height = checked((byte)(1 + Math.Max(left._height, right._height))); _count = 1 + left._count + right._count; _frozen = frozen; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return _left == null; } } /// <summary> /// Gets the height of the tree beneath this node. /// </summary> public int Height { get { return _height; } } /// <summary> /// Gets the left branch of this node. /// </summary> public Node Left { get { return _left; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree IBinaryTree.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> public Node Right { get { return _right; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree IBinaryTree.Right { get { return _right; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree<T> IBinaryTree<T>.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree<T> IBinaryTree<T>.Right { get { return _right; } } /// <summary> /// Gets the value represented by the current node. /// </summary> public T Value { get { return _key; } } /// <summary> /// Gets the number of elements contained by this subtree starting at this node. /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets the key. /// </summary> internal T Key { get { return _key; } } /// <summary> /// Gets the maximum value in the collection, as defined by the comparer. /// </summary> /// <value>The maximum value in the set.</value> internal T Max { get { if (this.IsEmpty) { return default(T); } Node n = this; while (!n._right.IsEmpty) { n = n._right; } return n._key; } } /// <summary> /// Gets the minimum value in the collection, as defined by the comparer. /// </summary> /// <value>The minimum value in the set.</value> internal T Min { get { if (this.IsEmpty) { return default(T); } Node n = this; while (!n._left.IsEmpty) { n = n._left; } return n._key; } } /// <summary> /// Gets the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>The element at the given position.</returns> internal T this[int index] { get { Requires.Range(index >= 0 && index < this.Count, nameof(index)); if (index < _left._count) { return _left[index]; } if (index > _left._count) { return _right[index - _left._count - 1]; } return _key; } } #if FEATURE_ITEMREFAPI /// <summary> /// Gets a read-only reference to the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>A read-only reference to the element at the given position.</returns> internal ref readonly T ItemRef(int index) { Requires.Range(index >= 0 && index < this.Count, nameof(index)); if (index < _left._count) { return ref _left.ItemRef(index); } if (index > _left._count) { return ref _right.ItemRef(index - _left._count - 1); } return ref _key; } #endif #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] // internal and never called, but here for the interface. IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] // internal and never called, but here for the interface. IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <param name="builder">The builder, if applicable.</param> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> internal Enumerator GetEnumerator(Builder builder) { return new Enumerator(this, builder); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> internal void CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (var item in this) { array[arrayIndex++] = item; } } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> internal void CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (var item in this) { array.SetValue(item, arrayIndex++); } } /// <summary> /// Adds the specified key to the tree. /// </summary> /// <param name="key">The key.</param> /// <param name="comparer">The comparer.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new tree.</returns> internal Node Add(T key, IComparer<T> comparer, out bool mutated) { Requires.NotNull(comparer, nameof(comparer)); if (this.IsEmpty) { mutated = true; return new Node(key, this, this); } else { Node result = this; int compareResult = comparer.Compare(key, _key); if (compareResult > 0) { var newRight = _right.Add(key, comparer, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } else if (compareResult < 0) { var newLeft = _left.Add(key, comparer, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { mutated = false; return this; } return mutated ? MakeBalanced(result) : result; } } /// <summary> /// Removes the specified key from the tree. /// </summary> /// <param name="key">The key.</param> /// <param name="comparer">The comparer.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new tree.</returns> internal Node Remove(T key, IComparer<T> comparer, out bool mutated) { Requires.NotNull(comparer, nameof(comparer)); if (this.IsEmpty) { mutated = false; return this; } else { Node result = this; int compare = comparer.Compare(key, _key); if (compare == 0) { // We have a match. mutated = true; // If this is a leaf, just remove it // by returning Empty. If we have only one child, // replace the node with the child. if (_right.IsEmpty && _left.IsEmpty) { result = EmptyNode; } else if (_right.IsEmpty && !_left.IsEmpty) { result = _left; } else if (!_right.IsEmpty && _left.IsEmpty) { result = _right; } else { // We have two children. Remove the next-highest node and replace // this node with it. var successor = _right; while (!successor._left.IsEmpty) { successor = successor._left; } bool dummyMutated; var newRight = _right.Remove(successor._key, comparer, out dummyMutated); result = successor.Mutate(left: _left, right: newRight); } } else if (compare < 0) { var newLeft = _left.Remove(key, comparer, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { var newRight = _right.Remove(key, comparer, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } return result.IsEmpty ? result : MakeBalanced(result); } } /// <summary> /// Determines whether the specified key is in this tree. /// </summary> /// <param name="key">The key.</param> /// <param name="comparer">The comparer.</param> /// <returns> /// <c>true</c> if the tree contains the specified key; otherwise, <c>false</c>. /// </returns> [Pure] internal bool Contains(T key, IComparer<T> comparer) { Requires.NotNull(comparer, nameof(comparer)); return !this.Search(key, comparer).IsEmpty; } /// <summary> /// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes. /// </summary> internal void Freeze() { // If this node is frozen, all its descendants must already be frozen. if (!_frozen) { _left.Freeze(); _right.Freeze(); _frozen = true; } } /// <summary> /// Searches for the specified key. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="comparer">The comparer.</param> /// <returns>The matching node, or <see cref="EmptyNode"/> if no match was found.</returns> [Pure] internal Node Search(T key, IComparer<T> comparer) { Requires.NotNull(comparer, nameof(comparer)); if (this.IsEmpty) { return this; } else { int compare = comparer.Compare(key, _key); if (compare == 0) { return this; } else if (compare > 0) { return _right.Search(key, comparer); } else { return _left.Search(key, comparer); } } } /// <summary> /// Searches for the specified key. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="comparer">The comparer.</param> /// <returns>The matching node, or <see cref="EmptyNode"/> if no match was found.</returns> [Pure] internal int IndexOf(T key, IComparer<T> comparer) { Requires.NotNull(comparer, nameof(comparer)); if (this.IsEmpty) { return -1; } else { int compare = comparer.Compare(key, _key); if (compare == 0) { return _left.Count; } else if (compare > 0) { int result = _right.IndexOf(key, comparer); bool missing = result < 0; if (missing) { result = ~result; } result = _left.Count + 1 + result; if (missing) { result = ~result; } return result; } else { return _left.IndexOf(key, comparer); } } } /// <summary> /// Returns an <see cref="IEnumerable{T}"/> that iterates over this /// collection in reverse order. /// </summary> /// <returns> /// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}"/> /// in reverse order. /// </returns> [Pure] internal IEnumerator<T> Reverse() { return new Enumerator(this, reverse: true); } #region Tree balancing methods /// <summary> /// AVL rotate left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node RotateLeft(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._right.IsEmpty) { return tree; } var right = tree._right; return right.Mutate(left: tree.Mutate(right: right._left)); } /// <summary> /// AVL rotate right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node RotateRight(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._left.IsEmpty) { return tree; } var left = tree._left; return left.Mutate(right: tree.Mutate(left: left._right)); } /// <summary> /// AVL rotate double-left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node DoubleLeft(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._right.IsEmpty) { return tree; } Node rotatedRightChild = tree.Mutate(right: RotateRight(tree._right)); return RotateLeft(rotatedRightChild); } /// <summary> /// AVL rotate double-right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node DoubleRight(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._left.IsEmpty) { return tree; } Node rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left)); return RotateRight(rotatedLeftChild); } /// <summary> /// Returns a value indicating whether the tree is in balance. /// </summary> /// <param name="tree">The tree.</param> /// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns> [Pure] private static int Balance(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return tree._right._height - tree._left._height; } /// <summary> /// Determines whether the specified tree is right heavy. /// </summary> /// <param name="tree">The tree.</param> /// <returns> /// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>. /// </returns> [Pure] private static bool IsRightHeavy(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return Balance(tree) >= 2; } /// <summary> /// Determines whether the specified tree is left heavy. /// </summary> [Pure] private static bool IsLeftHeavy(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return Balance(tree) <= -2; } /// <summary> /// Balances the specified tree. /// </summary> /// <param name="tree">The tree.</param> /// <returns>A balanced tree.</returns> [Pure] private static Node MakeBalanced(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (IsRightHeavy(tree)) { return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree); } if (IsLeftHeavy(tree)) { return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree); } return tree; } #endregion /// <summary> /// Creates a node tree that contains the contents of a list. /// </summary> /// <param name="items">An indexable list with the contents that the new node tree should contain.</param> /// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param> /// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param> /// <returns>The root of the created node tree.</returns> [Pure] internal static Node NodeTreeFromList(IOrderedCollection<T> items, int start, int length) { Requires.NotNull(items, nameof(items)); Debug.Assert(start >= 0); Debug.Assert(length >= 0); if (length == 0) { return EmptyNode; } int rightCount = (length - 1) / 2; int leftCount = (length - 1) - rightCount; Node left = NodeTreeFromList(items, start, leftCount); Node right = NodeTreeFromList(items, start + leftCount + 1, rightCount); return new Node(items[start + leftCount], left, right, true); } /// <summary> /// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node /// with the described changes. /// </summary> /// <param name="left">The left branch of the mutated node.</param> /// <param name="right">The right branch of the mutated node.</param> /// <returns>The mutated (or created) node.</returns> private Node Mutate(Node left = null, Node right = null) { if (_frozen) { return new Node(_key, left ?? _left, right ?? _right); } else { if (left != null) { _left = left; } if (right != null) { _right = right; } _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); _count = 1 + _left._count + _right._count; return this; } } } } }
#region Using using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.IO; using System.Xml.Linq; using System.Drawing; using System.Windows.Forms; using TribalWars.Controls; using TribalWars.Forms; using TribalWars.Forms.Small; using TribalWars.Maps.Drawing.Displays; using TribalWars.Tools; using TribalWars.Villages; using TribalWars.Villages.Units; using TribalWars.WorldTemplate; #endregion namespace TribalWars.Worlds { public partial class World { /// <summary> /// Handles the Path and files stuff for the World type /// </summary> public sealed class InternalStructure { #region Constants private const string AvailableWorlds = "https://www.{0}/backend/get_servers.php"; private const string UnitGraphicsUrlFormat = "http://dsen.innogamescdn.com/8.24/20950/graphic/unit/unit_{0}.png"; private const string ServerSettingsUrl = "https://{0}.{1}/interface.php?func={2}"; /// <summary> /// Match input like nl1, de5, en9, ... /// </summary> private static readonly Regex WorldSplitterRegex = new Regex(@"(\D*)(\d*)"); private const string FileVillageString = @"village.txt"; private const string FileTribeString = @"ally.txt"; private const string FilePlayerString = @"tribe.txt"; public const string DirectorySettingsString = "Settings"; public const string DirectoryDataString = "Data"; private const string DirectoryWorldDataString = "WorldData"; private const string DirectoryReportsString = "Reports"; private const string DirectoryScreenshotString = "Screenshot"; public const string DefaultSettingsString = "default.sets"; /// <summary> /// With . /// </summary> public const string SettingsExtensionString = ".sets"; private const string WorldXmlString = "world.xml"; private const string WorldXmlTemplateString = "WorldSettings.xml"; /// <summary> /// Contains the VillageTypes (Off, Def, ...) of all villages /// </summary> private const string VillageTypesString = "villagetypes.dat"; private const int WorldPlayerCount = 10000; private const int WorldTribeCount = 5000; #endregion #region Fields private static string _currentDirectory; private string _currentWorld; private string _currentData; private string _previousData; #endregion #region Properties /// <summary> /// Gets or sets the the URL to village.txt /// </summary> public string DownloadVillage { get; set; } /// <summary> /// Gets or sets the the URL to tribe.txt /// </summary> public string DownloadPlayer { get; set; } /// <summary> /// Gets or sets the the URL to ally.txt /// </summary> public string DownloadTribe { get; set; } /// <summary> /// Gets the date of the current data /// </summary> public DateTime? CurrentData { get { DateTime test; if (DateTime.TryParseExact(_currentData, "yyyyMMddHH", CultureInfo.InvariantCulture, DateTimeStyles.None, out test)) { return test; } return null; } } /// <summary> /// Gets the date of the previous data /// </summary> public DateTime? PreviousData { get { DateTime test; if (DateTime.TryParseExact(_previousData, "yyyyMMddHH", CultureInfo.InvariantCulture, DateTimeStyles.None, out test)) { return test; } return null; } } /// <summary> /// Gets a MemoryStream containing the user defined village types /// </summary> public FileStream CurrentVillageTypes { get { if (!File.Exists(CurrentWorldDirectory + VillageTypesString)) { using (FileStream stream = File.Create(Path.Combine(CurrentWorldDirectory, VillageTypesString))) { for (int i = 1; i <= 999999; i++) stream.WriteByte(0); } } return File.Open(CurrentWorldDirectory + VillageTypesString, FileMode.Open, FileAccess.ReadWrite); } } /// <summary> /// Template directory with files required for creating a new world /// </summary> private static string WorldTemplateDirectory { get { return AppDomain.CurrentDomain.BaseDirectory + @"\WorldTemplate"; } } #endregion #region Constructors /// <summary> /// Sets up the paths /// Reads world.xml /// Downloads the data if necessary /// </summary> public void SetPath(string world) { try { _currentData = string.Empty; _previousData = string.Empty; var worldPath = new DirectoryInfo(world); Debug.Assert(worldPath.Parent != null, "worldPath.Parent != null"); if (worldPath.Parent.Name == DirectoryWorldDataString && worldPath.Name != DirectoryWorldDataString) { // general world selected _currentWorld = worldPath.Name; ReadWorldConfiguration(worldPath.FullName); // If there is no datapath, read the last directory string[] dirs = Directory.GetDirectories(CurrentWorldDataDirectory); if (dirs.Length != 0) { _currentData = new DirectoryInfo(dirs[dirs.Length - 1]).Name; if (dirs.Length != 1) _previousData = new DirectoryInfo(dirs[dirs.Length - 2]).Name; // Redownload after x hours TimeSpan? lastDownload = Default.Settings.ServerTime - CurrentData; if (lastDownload.HasValue && lastDownload.Value.TotalHours >= 12) { string text = string.Format(ControlsRes.InternalStructure_DownloadNewTwSnapshot, (int)lastDownload.Value.TotalHours); DialogResult doDownload = MessageBox.Show(text, ControlsRes.InternalStructure_DownloadNewTwSnapshotTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (doDownload == DialogResult.Yes) { DownloadNewTwSnapshot(); } } } else { // no data found: download! DownloadNewTwSnapshot(); dirs = Directory.GetDirectories(CurrentWorldDataDirectory); _currentData = new DirectoryInfo(dirs[0]).Name; } } else { _currentData = worldPath.Name; worldPath = worldPath.Parent.Parent; Debug.Assert(worldPath != null, "worldPath != null"); _currentWorld = worldPath.Name; string[] dirs = Directory.GetDirectories(CurrentWorldDataDirectory).OrderBy(x => x).ToArray(); if (dirs.Length > 1) { DirectoryInfo lastDir = null; foreach (DirectoryInfo dir in dirs.Select(x => new DirectoryInfo(x))) { if (dir.Name == _currentData && lastDir != null) { _previousData = lastDir.Name; } lastDir = dir; } } ReadWorldConfiguration(worldPath.FullName); } } catch (Exception ex) { MessageBox.Show(ex.Message + Environment.NewLine + "Loading world: " + world); throw; } } /// <summary> /// World stats (server sets, Buildings & units) /// </summary> private void ReadWorldConfiguration(string worldPath) { Builder.ReadWorld(Path.Combine(worldPath, WorldXmlString)); } #endregion #region Path Properties /// <summary> /// Gets the executable directory /// </summary> private static string MainDirectory { get { if (_currentDirectory == null) _currentDirectory = Environment.CurrentDirectory + "\\"; return _currentDirectory; } } /// <summary> /// Gets the WorldData directory /// </summary> /// <remarks>\WorldData\</remarks> public static string WorldDataDirectory { get { return GetPath(MainDirectory + DirectoryWorldDataString + "\\"); } } /// <summary> /// Gets the loaded world directory /// </summary> /// <remarks>\WorldData\World 1\</remarks> public string CurrentWorldDirectory { get { return GetPath(MainDirectory + DirectoryWorldDataString + "\\" + _currentWorld + "\\"); } } /// <summary> /// Gets the location of world.xml /// </summary> public FileInfo CurrentWorldXmlPath { get { return new FileInfo(CurrentWorldDirectory + WorldXmlString); } } /// <summary> /// Gets the reports directory /// </summary> /// <remarks>\WorldData\World 1\Reports\</remarks> public string CurrentWorldReportsDirectory { get { return GetPath(MainDirectory + DirectoryWorldDataString + "\\" + _currentWorld + "\\" + DirectoryReportsString + "\\"); } } /// <summary> /// Gets the directory with user screenshots /// </summary> /// <remarks>\WorldData\World 1\Screenshot\</remarks> public string CurrentWorldScreenshotDirectory { get { return GetPath(MainDirectory + DirectoryWorldDataString + "\\" + _currentWorld + "\\" + DirectoryScreenshotString + "\\"); } } /// <summary> /// Gets the directory with the different settings files /// </summary> /// <remarks>\WorldData\World 1\Settings\</remarks> public string CurrentWorldSettingsDirectory { get { return GetPath(MainDirectory + DirectoryWorldDataString + "\\" + _currentWorld + "\\" + DirectorySettingsString + "\\"); } } /// <summary> /// Gets the directory with all the downloaded TW data /// </summary> /// <remarks>\WorldData\World 1\Data\</remarks> public string CurrentWorldDataDirectory { get { return GetPath(MainDirectory + DirectoryWorldDataString + "\\" + _currentWorld + "\\" + DirectoryDataString + "\\"); } } /// <summary> /// Gets the directory with the currently loaded TW data /// </summary> /// <remarks>\WorldData\World 1\Data\20080101\</remarks> private string CurrentWorldDataDateDirectory { get { return GetPath(MainDirectory + DirectoryWorldDataString + "\\" + _currentWorld + "\\" + DirectoryDataString + "\\" + _currentData + "\\"); } } /// <summary> /// Gets the directory with the previously downloaded TW data /// </summary> private string PreviousWorldDataDateDirectory { get { if (string.IsNullOrEmpty(_previousData)) return null; return GetPath(MainDirectory + DirectoryWorldDataString + "\\" + _currentWorld + "\\" + DirectoryDataString + "\\" + _previousData + "\\"); } } #endregion #region Public Methods /// <summary> /// Get image url for a unit /// </summary> public string GetUnitImageUrl(UnitTypes type) { return string.Format(UnitGraphicsUrlFormat, type.ToString().ToLowerInvariant()); } /// <summary> /// Checks if a folder contains village, tribe and ally.txt /// </summary> public static bool IsValidDataPath(string path) { if (path.Length > 0 && Directory.Exists(path)) { if (File.Exists(path + @"\" + FileVillageString) && File.Exists(path + @"\" + FileTribeString) && File.Exists(path + @"\" + FilePlayerString)) return true; } return false; } #endregion #region TW Servers Information /// <summary> /// Gets all TW servers as defined in WorldTemplate /// </summary> public static IEnumerable<ServerInfo> GetAllServers() { var list = new List<ServerInfo>(); var xDoc = XDocument.Load(Path.Combine(WorldTemplateDirectory, "TribalWarsServers.xml")); foreach (var server in xDoc.Root.Elements()) { list.Add(new ServerInfo(server.Element("ServerUrl").Value, server.Element("TWStatsPrefix").Value)); } return list; } /// <summary> /// Get all available worlds on the server /// </summary> public static IEnumerable<string> GetWorlds(string serverName) { var file = Network.GetWebRequest(string.Format(AvailableWorlds, serverName)); var worldsObject = (Hashtable)new Serializer().Deserialize(file); string[] worldsPlayerCanStart = worldsObject.Keys.OfType<string>().OrderBy(x => x).ToArray(); return worldsPlayerCanStart; // The code below was to also add worlds a new player could NOT start // This was useful to look at a finished world to see how ended // This info is no longer available now because worlds are now archived // and no longer offer this info //var worldsPerWorldType = worldsPlayerCanStart.Select(SplitIntoServerPrefixAndWorldNumber).ToLookup(x => x.Key, x => x.Value); //var worlds = new List<string>(); //foreach (var worldType in worldsPerWorldType) //{ // IGrouping<string, int> fixedType = worldType; // if (fixedType.Max() != -1) // { // IEnumerable<string> allWorldsInType = Enumerable.Range(1, fixedType.Max()).Select(x => fixedType.Key + x); // worlds.AddRange(allWorldsInType); // } //} //return worlds.ToArray(); } /// <summary> /// Splits TW worlds like (en15, nl39) into the server prefix (en, nl) /// and world number (15, 39) /// </summary> private static KeyValuePair<string, int> SplitIntoServerPrefixAndWorldNumber(string world) { Match match = WorldSplitterRegex.Match(world); int worldNumber; if (int.TryParse(match.Groups[2].Value, out worldNumber)) { return new KeyValuePair<string, int>(match.Groups[1].Value, worldNumber); } else { return new KeyValuePair<string, int>(match.Groups[1].Value, -1); } } /// <summary> /// Simple holder class with server info /// that runs TribalWars /// </summary> public class ServerInfo { public string ServerUrl { get; private set; } public string TwStatsPrefix { get; private set; } public ServerInfo(string url, string twStatsPrefix) { ServerUrl = url; TwStatsPrefix = twStatsPrefix; } public override string ToString() { return string.Format("Url={0}, TWStats={1}", ServerUrl, TwStatsPrefix); } } #endregion #region Create New World /// <summary> /// Create required infrastructure for a new world /// </summary> public static void CreateWorld(string path, ServerInfo server) { var dir = new DirectoryInfo(path); string worldName = dir.Name; if (!dir.Exists) { dir.Create(); } // world.xml var worldInfo = WorldConfiguration.LoadFromFile(Path.Combine(WorldTemplateDirectory, WorldXmlTemplateString)); worldInfo.Name = worldName; if (server.TwStatsPrefix.ToLowerInvariant() != System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName) { using (var timeZoneSetter = new TimeZoneForm()) { if (timeZoneSetter.ShowDialog() == DialogResult.OK) { worldInfo.Offset = timeZoneSetter.ServerOffset.TotalSeconds.ToString(CultureInfo.InvariantCulture); } } } TwWorldSettings twWorldSettings = DownloadWorldSettings(worldName, server.ServerUrl); worldInfo.Speed = twWorldSettings.Speed.ToString(CultureInfo.InvariantCulture); worldInfo.UnitSpeed = twWorldSettings.UnitSpeed.ToString(CultureInfo.InvariantCulture); worldInfo.WorldDatScenery = ((int)twWorldSettings.MapScenery).ToString(CultureInfo.InvariantCulture); worldInfo.Church = twWorldSettings.Church ? "1" : "0"; // Fix URIs worldInfo.Server = ReplaceServerAndWorld(worldInfo.Server, worldName, server); worldInfo.DataVillage = ReplaceServerAndWorld(worldInfo.DataVillage, worldName, server); worldInfo.DataPlayer = ReplaceServerAndWorld(worldInfo.DataPlayer, worldName, server); worldInfo.DataTribe = ReplaceServerAndWorld(worldInfo.DataTribe, worldName, server); worldInfo.GameVillage = ReplaceServerAndWorld(worldInfo.GameVillage, worldName, server); worldInfo.GuestPlayer = ReplaceServerAndWorld(worldInfo.GuestPlayer, worldName, server); worldInfo.GuestTribe = ReplaceServerAndWorld(worldInfo.GuestTribe, worldName, server); worldInfo.TWStatsGeneral = ReplaceServerAndWorld(worldInfo.TWStatsGeneral, worldName, server); worldInfo.TWStatsPlayer = ReplaceServerAndWorld(worldInfo.TWStatsPlayer, worldName, server); worldInfo.TWStatsPlayerGraph = ReplaceServerAndWorld(worldInfo.TWStatsPlayerGraph, worldName, server); worldInfo.TWStatsTribe = ReplaceServerAndWorld(worldInfo.TWStatsTribe, worldName, server); worldInfo.TWStatsTribeGraph = ReplaceServerAndWorld(worldInfo.TWStatsTribeGraph, worldName, server); worldInfo.TWStatsVillage = ReplaceServerAndWorld(worldInfo.TWStatsVillage, worldName, server); worldInfo.Units.Clear(); worldInfo.Units.AddRange(GetWorldUnitSettings(worldName, server)); worldInfo.SaveToFile(Path.Combine(path, WorldXmlString)); // default.sets Directory.CreateDirectory(Path.Combine(path, DirectorySettingsString)); var settingsTemplatePath = Path.Combine(WorldTemplateDirectory, DefaultSettingsString); string targetPath = Path.Combine(path, DirectorySettingsString, DefaultSettingsString); File.Copy(settingsTemplatePath, targetPath); } #region TW World Information /// <summary> /// Downloads the global world settings and extracts the world speeds /// </summary> private static TwWorldSettings DownloadWorldSettings(string worldName, string worldServer) { // https://nl57.tribalwars.nl/interface.php?func=get_config var xdoc = Network.DownloadXml(string.Format(ServerSettingsUrl, worldName, worldServer, "get_config")); Debug.Assert(xdoc.Root != null, "xdoc.Root != null"); var worldSpeed = float.Parse(xdoc.Root.Element("speed").Value.Trim(), CultureInfo.InvariantCulture); var worldUnitSpeed = float.Parse(xdoc.Root.Element("unit_speed").Value.Trim(), CultureInfo.InvariantCulture); var coords = xdoc.Root.Element("coord"); bool isOldScenery = coords.Elements().Any(el => el.Name == "legacy_scenery") ? coords.Element("legacy_scenery").Value == "1" : false; bool hasChurch = xdoc.Root.Element("game").Element("church").Value == "1"; return new TwWorldSettings(worldSpeed, worldUnitSpeed, isOldScenery, hasChurch); } /// <summary> /// Useful world information from the TW API /// </summary> private class TwWorldSettings { public float Speed { get; private set; } public float UnitSpeed { get; private set; } public bool Church { get; private set; } /// <summary> /// Gets a value indicating which world.dat to use /// </summary> public IconDrawerFactory.Scenery MapScenery { get; private set; } public TwWorldSettings(float worldSpeed, float worldUnitSpeed, bool isOldScenery, bool hasChurch) { Speed = worldSpeed; UnitSpeed = worldUnitSpeed; MapScenery = isOldScenery ? IconDrawerFactory.Scenery.Old : IconDrawerFactory.Scenery.New; Church = hasChurch; } } /// <summary> /// Gets the unit information for this world /// and combines it with TWTactics data /// </summary> private static IEnumerable<WorldConfigurationUnitsUnit> GetWorldUnitSettings(string worldName, ServerInfo server) { List<TacticsUnit> twTacticsUnits = TacticsUnit.GetUnitsFromXml(Path.Combine(WorldTemplateDirectory, "TacticsUnits.xml")); IEnumerable<TwUnit> twUnits = DownloadWorldUnitSettings(worldName, server.ServerUrl); var list = new List<WorldConfigurationUnitsUnit>(); int position = 0; foreach (TwUnit twUnit in twUnits) { TacticsUnit tacticsUnit = twTacticsUnits.SingleOrDefault(x => x.Type == twUnit.Type); if (tacticsUnit != null) { list.Add(new WorldConfigurationUnitsUnit { Carry = twUnit.Carry.ToString(CultureInfo.InvariantCulture), CostClay = twUnit.Clay.ToString(CultureInfo.InvariantCulture), CostIron = twUnit.Iron.ToString(CultureInfo.InvariantCulture), CostWood = twUnit.Wood.ToString(CultureInfo.InvariantCulture), CostPeople = twUnit.Population.ToString(CultureInfo.InvariantCulture), Farmer = tacticsUnit.Farmer.ToString(), HideAttacker = tacticsUnit.HideAttacher.ToString(), Offense = tacticsUnit.Offense.ToString(), Name = tacticsUnit.Name, Short = tacticsUnit.ShortName, Speed = twUnit.Speed.ToString(CultureInfo.InvariantCulture), Type = twUnit.Type.ToString(), Position = position.ToString(CultureInfo.InvariantCulture) }); } position++; } return list; } private static IEnumerable<TwUnit> DownloadWorldUnitSettings(string worldName, string serverName) { // http://nl2.tribalwars.nl/interface.php?func=get_unit_info var xdoc = Network.DownloadXml(string.Format(ServerSettingsUrl, worldName, serverName, "get_unit_info")); var list = new List<TwUnit>(); foreach (var xmlUnit in xdoc.Root.Elements()) { UnitTypes type; if (Enum.TryParse(xmlUnit.Name.LocalName, true, out type)) { list.Add(new TwUnit { Type = type, //Wood = Convert.ToInt32(xmlUnit.Element("wood").Value), //Clay = Convert.ToInt32(xmlUnit.Element("stone").Value), //Iron = Convert.ToInt32(xmlUnit.Element("iron").Value), Population = Convert.ToInt32(xmlUnit.Element("pop").Value), Speed = Convert.ToSingle(xmlUnit.Element("speed").Value, CultureInfo.InvariantCulture), Carry = Convert.ToInt32(xmlUnit.Element("carry").Value) }); } } return list; } /// <summary> /// Holder class with data from TW API /// /// ATTN: Wood, Clay and Iron are no longer in the output /// (they remain at 0) /// Not really used in TW Tactics so ok? /// </summary> private class TwUnit { public UnitTypes Type { get; set; } public int Wood { get; set; } public int Clay { get; set; } public int Iron { get; set; } public int Population { get; set; } public float Speed { get; set; } public int Carry { get; set; } public override string ToString() { return string.Format("Type={0}, Speed={1}, Population={2}", Type, Speed, Population); } } #endregion #endregion #region Download Snapshot /// <summary> /// Downloads the latest Tribal Wars data /// </summary> public void DownloadNewTwSnapshot() { _previousData = _currentData; _currentData = Default.Settings.ServerTime.ToString("yyyyMMddHH", CultureInfo.InvariantCulture); string dirName = CurrentWorldDataDirectory + _currentData; if (Directory.Exists(dirName)) { MessageBox.Show(ControlsRes.InternalStructure_DownloadOnlyOncePerHour); } else { // Download data Directory.CreateDirectory(dirName); try { DownloadFile(DownloadVillage, dirName + "\\" + FileVillageString); DownloadFile(DownloadTribe, dirName + "\\" + FileTribeString); DownloadFile(DownloadPlayer, dirName + "\\" + FilePlayerString); } catch (Exception e) { MessageBox.Show(e.ToString(), "Something went horribly wrong"); Directory.Delete(dirName, true); } } // Keep statistics :) #if !DEBUG UpdateCounter(); #endif } private void UpdateCounter() { var data = new NameValueCollection(); data["server"] = Default.Settings.Server.Host; data["world"] = Default.Settings.Name; data["player"] = Default.You.Name; data["tribe"] = Default.You.HasTribe ? Default.You.Tribe.Tag : ""; Network.PostValues("http://sangu.be/api/twtacticsusage.php", data); } /// <summary> /// Downloads one TW file /// </summary> private void DownloadFile(string urlFile, string outputFile) { var client = Network.CreateWebRequest(urlFile); using (var response = client.GetResponse()) { var stream = response.GetResponseStream(); Debug.Assert(stream != null); using (var unzip = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress)) { using (var writer = new FileStream(outputFile, FileMode.Create)) { var block = new byte[4096]; int read; while ((read = unzip.Read(block, 0, block.Length)) != 0) { writer.Write(block, 0, read); } } } } } #endregion #region Load TW Snapshots /// <summary> /// Loads the village, player and tribe files into memory /// </summary> /// <param name="villages">Output villages dictionary</param> /// <param name="players">Output players dictionary</param> /// <param name="tribes">Output tribes dictionary</param> public void LoadCurrentAndPreviousTwSnapshot(out WorldVillagesCollection villages, out Dictionary<string, Player> players, out Dictionary<string, Tribe> tribes) { LoadTwSnapshot(CurrentWorldDataDateDirectory, out villages, out players, out tribes); LoadPreviousTwSnapshot(null, villages, players, tribes); } private void LoadTwSnapshot(string dataPath, out WorldVillagesCollection villages, out Dictionary<string, Player> players, out Dictionary<string, Tribe> tribes) { if (IsValidDataPath(dataPath)) { // load map files string[] readVillages = File.ReadAllLines(dataPath + FileVillageString); string[] readPlayers = File.ReadAllLines(dataPath + FilePlayerString); string[] readTribes = File.ReadAllLines(dataPath + FileTribeString); // Temporary dictionaries for mapping var tempPlayers = new Dictionary<int, string>(WorldPlayerCount); var tempTribes = new Dictionary<int, string>(WorldTribeCount); // Load tribes tribes = new Dictionary<string, Tribe>(readTribes.Length + 1); foreach (string tribeString in readTribes) { var tribe = new Tribe(tribeString.Split(',')); tribes.Add(tribe.Tag.ToUpper(), tribe); tempTribes.Add(tribe.Id, tribe.Tag.ToUpper()); } // Load players players = new Dictionary<string, Player>(readPlayers.Length + 1); foreach (string playerString in readPlayers) { var player = new Player(playerString.Split(',')); // Find tribe if (player.TribeId != 0 && tempTribes.ContainsKey(player.TribeId)) { Tribe tribe = tribes[tempTribes[player.TribeId]]; player.Tribe = tribe; tribes[tribe.Tag.ToUpper()].AddPlayer(player); } players.Add(player.Name.ToUpper(), player); tempPlayers.Add(player.Id, player.Name.ToUpper()); } // Load villages villages = new WorldVillagesCollection(readVillages.Length + 1); foreach (string villageString in readVillages) { var village = new Village(villageString.Split(',')); // links to and from players if (village.PlayerId != 0 && tempPlayers.ContainsKey(village.PlayerId)) { Player player = players[tempPlayers[village.PlayerId]]; village.Player = player; players[player.Name.ToUpper()].AddVillage(village); } if (village.Location.IsValidGameCoordinate()) { villages.Add(new Point(village.X, village.Y), village); } } } else { tribes = new Dictionary<string, Tribe>(); players = new Dictionary<string, Player>(); villages = new WorldVillagesCollection(); } } /// <summary> /// Load previous data async /// </summary> public void LoadPreviousTwSnapshot(string previousPath, WorldVillagesCollection villages, Dictionary<string, Player> players, Dictionary<string, Tribe> tribes) { bool load = true; if (previousPath != null) { string currentPath = PreviousWorldDataDateDirectory; _previousData = previousPath; if (currentPath == PreviousWorldDataDateDirectory) load = false; } if (load && PreviousWorldDataDateDirectory != null) { var wrapper = new DictionaryLoaderWrapper(); wrapper.Villages = villages; wrapper.Tribes = tribes; wrapper.Players = players; wrapper.Path = PreviousWorldDataDateDirectory; DictionaryLoader invoker = BeginDictionaryAsync; invoker.BeginInvoke(wrapper, EndDictionaryAsync, null); } } /// <summary> /// Async delegate for loading the previously download data /// </summary> private delegate void DictionaryLoader(DictionaryLoaderWrapper wrapper); /// <summary> /// Wrapper argument class for async dictionary loading /// </summary> private class DictionaryLoaderWrapper { public string Path; public WorldVillagesCollection Villages; public Dictionary<string, Player> Players; public Dictionary<string, Tribe> Tribes; } /// <summary> /// Starts filling the previous data of the villages, players and tribes /// </summary> /// <param name="wrapper">Wrapper object with path and current data</param> private void BeginDictionaryAsync(DictionaryLoaderWrapper wrapper) { // Load the data WorldVillagesCollection villages; Dictionary<string, Player> players; Dictionary<string, Tribe> tribes; LoadTwSnapshot(wrapper.Path, out villages, out players, out tribes); foreach (Village village in villages.Values) { if (wrapper.Villages.ContainsKey(village.Location)) { wrapper.Villages[village.Location].SetPreviousDetails(village); } } foreach (KeyValuePair<string, Player> pair in players) { if (wrapper.Players.ContainsKey(pair.Key)) { wrapper.Players[pair.Key].SetPreviousDetails(pair.Value); } } foreach (KeyValuePair<string, Tribe> pair in tribes) { if (wrapper.Tribes.ContainsKey(pair.Key)) { wrapper.Tribes[pair.Key].SetPreviousDetails(pair.Value); } } } /// <summary> /// Raise the Monitor event when loading the previous data has been loaded /// </summary> private void EndDictionaryAsync(IAsyncResult ar) { var result = (System.Runtime.Remoting.Messaging.AsyncResult)ar; var invoker = (DictionaryLoader)result.AsyncDelegate; invoker.EndInvoke(ar); Default.EventPublisher.InformMonitoringLoaded(null); } #endregion #region Private Implementation /// <summary> /// Returns the path and creates the directory if it does not yet exist /// </summary> private static string GetPath(string str) { if (!Directory.Exists(str)) Directory.CreateDirectory(str); return str; } /// <summary> /// Replace {WorldName} and {WorldServer} with the given values /// </summary> private static string ReplaceServerAndWorld(string str, string worldName, ServerInfo server) { return str .Replace("{WorldName}", worldName) .Replace("{ServerUrl}", server.ServerUrl) .Replace("{TWStatsPrefix}", server.TwStatsPrefix); } #endregion } } }
#region Apache Notice /***************************************************************************** * $Revision: 374175 $ * $LastChangedDate: 2006-10-30 12:09:11 -0700 (Mon, 30 Oct 2006) $ * $LastChangedBy: gbayon $ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System; namespace IBatisNet.DataMapper.Configuration.ParameterMapping { /// <summary> /// A ParameterProperty Collection. /// </summary> public class ParameterPropertyCollection { private const int DEFAULT_CAPACITY = 4; private const int CAPACITY_MULTIPLIER = 2; private int _count = 0; private ParameterProperty[] _innerList = null; /// <summary> /// Read-only property describing how many elements are in the Collection. /// </summary> public int Count { get { return _count; } } /// <summary> /// Constructs a ParameterProperty collection. The list is initially empty and has a capacity /// of zero. Upon adding the first element to the list the capacity is /// increased to 8, and then increased in multiples of two as required. /// </summary> public ParameterPropertyCollection() { _innerList = new ParameterProperty[DEFAULT_CAPACITY]; _count = 0; } /// <summary> /// Constructs a ParameterPropertyCollection with a given initial capacity. /// The list is initially empty, but will have room for the given number of elements /// before any reallocations are required. /// </summary> /// <param name="capacity">The initial capacity of the list</param> public ParameterPropertyCollection(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException("Capacity", "The size of the list must be >0."); } _innerList = new ParameterProperty[capacity]; } /// <summary> /// Length of the collection /// </summary> public int Length { get{ return _innerList.Length; } } /// <summary> /// Sets or Gets the ParameterProperty at the given index. /// </summary> public ParameterProperty this[int index] { get { if (index < 0 || index >= _count) { throw new ArgumentOutOfRangeException("index"); } return _innerList[index]; } set { if (index < 0 || index >= _count) { throw new ArgumentOutOfRangeException("index"); } _innerList[index] = value; } } /// <summary> /// Add an ParameterProperty /// </summary> /// <param name="value"></param> /// <returns>Index</returns> public int Add(ParameterProperty value) { Resize(_count + 1); int index = _count++; _innerList[index] = value; return index; } /// <summary> /// Add a list of ParameterProperty to the collection /// </summary> /// <param name="value"></param> public void AddRange(ParameterProperty[] value) { for (int i = 0; i < value.Length; i++) { Add(value[i]); } } /// <summary> /// Add a list of ParameterProperty to the collection /// </summary> /// <param name="value"></param> public void AddRange(ParameterPropertyCollection value) { for (int i = 0; i < value.Count; i++) { Add(value[i]); } } /// <summary> /// Indicate if a ParameterProperty is in the collection /// </summary> /// <param name="value">A ParameterProperty</param> /// <returns>True fi is in</returns> public bool Contains(ParameterProperty value) { for (int i = 0; i < _count; i++) { if(_innerList[i].PropertyName==value.PropertyName) { return true; } } return false; } /// <summary> /// Insert a ParameterProperty in the collection. /// </summary> /// <param name="index">Index where to insert.</param> /// <param name="value">A ParameterProperty</param> public void Insert(int index, ParameterProperty value) { if (index < 0 || index > _count) { throw new ArgumentOutOfRangeException("index"); } Resize(_count + 1); Array.Copy(_innerList, index, _innerList, index + 1, _count - index); _innerList[index] = value; _count++; } /// <summary> /// Remove a ParameterProperty of the collection. /// </summary> public void Remove(ParameterProperty value) { for(int i = 0; i < _count; i++) { if(_innerList[i].PropertyName==value.PropertyName) { RemoveAt(i); return; } } } /// <summary> /// Removes a ParameterProperty at the given index. The size of the list is /// decreased by one. /// </summary> /// <param name="index"></param> public void RemoveAt(int index) { if (index < 0 || index >= _count) { throw new ArgumentOutOfRangeException("index"); } int remaining = _count - index - 1; if (remaining > 0) { Array.Copy(_innerList, index + 1, _innerList, index, remaining); } _count--; _innerList[_count] = null; } /// <summary> /// Ensures that the capacity of this collection is at least the given minimum /// value. If the currect capacity of the list is less than min, the /// capacity is increased to twice the current capacity. /// </summary> /// <param name="minSize"></param> private void Resize(int minSize) { int oldSize = _innerList.Length; if (minSize > oldSize) { ParameterProperty[] oldEntries = _innerList; int newSize = oldEntries.Length * CAPACITY_MULTIPLIER; if (newSize < minSize) { newSize = minSize; } _innerList = new ParameterProperty[newSize]; Array.Copy(oldEntries, 0, _innerList, 0, _count); } } } }
/* * InformationMachineAPI.PCL * * */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using unirest_net.request; namespace InformationMachineAPI.PCL { public static class APIHelper { //DateTime format to use for parsing and converting dates public static string DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; /// <summary> /// JSON Serialization of a given object. /// </summary> /// <param name="obj">The object to serialize into JSON</param> /// <returns>The serialized Json string representation of the given object</returns> public static string JsonSerialize(object obj) { if (null == obj) return null; return JsonConvert.SerializeObject(obj, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = DateTimeFormat }); } /// <summary> /// JSON Deserialization of the given json string. /// </summary> /// <param name="json">The json string to deserialize</param> /// <typeparam name="T">The type of the object to desialize into</typeparam> /// <returns>The deserialized object</returns> public static T JsonDeserialize<T>(string json) { if (string.IsNullOrWhiteSpace(json)) return default(T); return JsonConvert.DeserializeObject<T>(json, new IsoDateTimeConverter() { DateTimeFormat = DateTimeFormat }); } /// <summary> /// Replaces template parameters in the given url /// </summary> /// <param name="queryUrl">The query url string to replace the template parameters</param> /// <param name="parameters">The parameters to replace in the url</param> public static void AppendUrlWithTemplateParameters (StringBuilder queryBuilder, IEnumerable<KeyValuePair<string, object>> parameters) { //perform parameter validation if (null == queryBuilder) throw new ArgumentNullException("queryBuilder"); if (null == parameters) return; //iterate and replace parameters foreach (KeyValuePair<string, object> pair in parameters) { string replaceValue = string.Empty; //load element value as string if (null == pair.Value) replaceValue = ""; else if (pair.Value is ICollection) replaceValue = flattenCollection(pair.Value as ICollection, "{0}{1}", '/', false); else if (pair.Value is DateTime) replaceValue = ((DateTime)pair.Value).ToString(DateTimeFormat); else replaceValue = pair.Value.ToString(); replaceValue = Uri.EscapeUriString(replaceValue); //find the template parameter and replace it with its value queryBuilder.Replace(string.Format("{{{0}}}", pair.Key), replaceValue); } } /// <summary> /// Appends the given set of parameters to the given query string /// </summary> /// <param name="queryUrl">The query url string to append the parameters</param> /// <param name="parameters">The parameters to append</param> public static void AppendUrlWithQueryParameters (StringBuilder queryBuilder, IEnumerable<KeyValuePair<string, object>> parameters) { //perform parameter validation if (null == queryBuilder) throw new ArgumentNullException("queryBuilder"); if (null == parameters) return; //does the query string already has parameters bool hasParams = (indexOf(queryBuilder, "?") > 0); //iterate and append parameters foreach (KeyValuePair<string, object> pair in parameters) { //ignore null values if (pair.Value == null) continue; //if already has parameters, use the &amp; to append new parameters queryBuilder.Append((hasParams) ? '&' : '?'); //indicate that now the query has some params hasParams = true; string paramKeyValPair; //load element value as string if (pair.Value is ICollection) paramKeyValPair = flattenCollection(pair.Value as ICollection, string.Format("{0}[]={{0}}{{1}}", pair.Key), '&', true); else if (pair.Value is DateTime) paramKeyValPair = string.Format("{0}={1}", Uri.EscapeDataString(pair.Key), ((DateTime)pair.Value).ToString(DateTimeFormat)); else paramKeyValPair = string.Format("{0}={1}", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value.ToString())); //append keyval pair for current parameter queryBuilder.Append(paramKeyValPair); } } /// <summary> /// StringBuilder extension method to implement IndexOf functionality. /// This does a StringComparison.Ordinal kind of comparison. /// </summary> /// <param name="stringBuilder">The string builder to find the index in</param> /// <param name="strCheck">The string to locate in the string builder</param> /// <returns>The index of string inside the string builder</returns> private static int indexOf(StringBuilder stringBuilder, string strCheck) { if (stringBuilder == null) throw new ArgumentNullException("stringBuilder"); if (strCheck == null) return 0; //iterate over the input for (int inputCounter = 0; inputCounter < stringBuilder.Length; inputCounter++) { int matchCounter; //attempt to locate a potential match for (matchCounter = 0; (matchCounter < strCheck.Length) && (inputCounter + matchCounter < stringBuilder.Length) && (stringBuilder[inputCounter + matchCounter] == strCheck[matchCounter]); matchCounter++) ; //verify the match if (matchCounter == strCheck.Length) return inputCounter; } return -1; } /// <summary> /// Validates and processes the given query Url to clean empty slashes /// </summary> /// <param name="queryBuilder">The given query Url to process</param> /// <returns>Clean Url as string</returns> public static string CleanUrl(StringBuilder queryBuilder) { //convert to immutable string string url = queryBuilder.ToString(); //ensure that the urls are absolute Match match = Regex.Match(url, "^https?://[^/]+"); if (!match.Success) throw new ArgumentException("Invalid Url format."); //remove redundant forward slashes int index = url.IndexOf('?'); string protocol = match.Value; string query = url.Substring(protocol.Length, (index == -1 ? url.Length : index) - protocol.Length); query = Regex.Replace(query, "//+", "/"); string parameters = index == -1 ? "" : url.Substring(index); //return process url return string.Concat(protocol, query, parameters);; } /// <summary> /// Used for flattening a collection of objects into a string /// </summary> /// <param name="array">Array of elements to flatten</param> /// <param name="fmt">Format string to use for array flattening</param> /// <param name="separator">Separator to use for string concat</param> /// <returns>Representative string made up of array elements</returns> private static string flattenCollection(ICollection array, string fmt, char separator, bool urlEncode) { StringBuilder builder = new StringBuilder(); //append all elements in the array into a string foreach (object element in array) { string elemValue = null; //replace null values with empty string to maintain index order if (null == element) elemValue = string.Empty; else if (element is DateTime) elemValue = ((DateTime)element).ToString(DateTimeFormat); else elemValue = element.ToString(); if (urlEncode) elemValue = Uri.EscapeDataString(elemValue); builder.AppendFormat(fmt, elemValue, separator); } //remove the last separator, if appended if ((builder.Length > 1) && (builder[builder.Length - 1] == separator)) builder.Length -= 1; return builder.ToString(); } /// <summary> /// Prepares the object as form fields using the provided name. /// </summary> /// <param name="name">root name for the variable</param> /// <param name="value">form field value</param> /// <param name="keys">Contains a flattend and form friendly values</param> /// <returns>Contains a flattend and form friendly values</returns> public static Dictionary<string, object> PrepareFormFieldsFromObject( string name, object value, Dictionary<string, object> keys = null) { keys = keys ?? new Dictionary<string, object>(); if (value == null) { return keys; } else if (value is Stream) { keys[name] = value; return keys; } else if (value is JObject) { var valueAccept = (value as Newtonsoft.Json.Linq.JObject); foreach (var property in valueAccept.Properties()) { string pKey = property.Name; object pValue = property.Value; var fullSubName = name + '[' + pKey + ']'; PrepareFormFieldsFromObject(fullSubName, pValue, keys); } } else if (value is IList) { int i = 0; var enumerator = ((IEnumerable)value).GetEnumerator(); while (enumerator.MoveNext()) { var subValue = enumerator.Current; if (subValue == null) continue; var fullSubName = name + '[' + i + ']'; PrepareFormFieldsFromObject(fullSubName, subValue, keys); i++; } } else if (value is JToken) { keys[name] = value.ToString(); } else if (value is Enum) { #if WINDOWS_UWP Assembly thisAssembly = typeof(APIHelper).GetTypeInfo().Assembly; #else Assembly thisAssembly = Assembly.GetExecutingAssembly(); #endif string enumTypeName = value.GetType().FullName; Type enumHelperType = thisAssembly.GetType(string.Format("{0}Helper", enumTypeName)); object enumValue = (int)value; if (enumHelperType != null) { //this enum has an associated helper, use that to load the value MethodInfo enumHelperMethod = enumHelperType.GetMethod("ToValue", new[] { value.GetType() }); if (enumHelperMethod != null) enumValue = enumHelperMethod.Invoke(null, new object[] { value }); } keys[name] = enumValue; } else if (value is IDictionary) { var obj = (IDictionary)value; foreach (var sName in obj.Keys) { var subName = sName.ToString(); var subValue = obj[subName]; string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']'; PrepareFormFieldsFromObject(fullSubName, subValue, keys); } } else if (!(value.GetType().Namespace.StartsWith("System"))) { //Custom object Iterate through its properties var enumerator = value.GetType().GetProperties().GetEnumerator(); PropertyInfo pInfo = null; var t = new JsonPropertyAttribute().GetType(); while (enumerator.MoveNext()) { pInfo = enumerator.Current as PropertyInfo; var jsonProperty = (JsonPropertyAttribute)pInfo.GetCustomAttributes(t, true).FirstOrDefault(); var subName = (jsonProperty != null) ? jsonProperty.PropertyName : pInfo.Name; string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']'; var subValue = pInfo.GetValue(value, null); PrepareFormFieldsFromObject(fullSubName, subValue, keys); } } else if (value is DateTime) { keys[name] = ((DateTime)value).ToString(DateTimeFormat); } else { keys[name] = value; } return keys; } /// <summary> /// Add/update entries with the new dictionary. /// </summary> /// <param name="dictionary"></param> /// <param name="dictionary2"></param> public static void Add(this Dictionary<string, object> dictionary, Dictionary<string, object> dictionary2) { foreach (var kvp in dictionary2) { dictionary[kvp.Key] = kvp.Value; } } } }
using System; using System.Collections.Generic; using System.Linq; using Ploeh.AutoFixture.Kernel; using Ploeh.AutoFixtureUnitTest.Kernel; using Xunit; using System.Collections; using Xunit.Extensions; namespace Ploeh.AutoFixtureUnitTest { public class RecursionGuardTest { [Fact] public void SutIsSpecimenBuilder() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); // Exercise system var sut = new DelegatingRecursionGuard(dummyBuilder); // Verify outcome Assert.IsAssignableFrom<ISpecimenBuilder>(sut); // Teardown } [Fact] public void SutIsNode() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); // Exercise system var sut = new DelegatingRecursionGuard(dummyBuilder); // Verify outcome Assert.IsAssignableFrom<ISpecimenBuilderNode>(sut); // Teardown } [Fact] public void InitializeWithNullBuilderThrows() { // Fixture setup // Exercise system and verify outcome Assert.Throws<ArgumentNullException>(() => new DelegatingRecursionGuard(null)); // Teardown } [Fact] public void InitializeWithNullEqualityComparerThrows() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); // Exercise system and verify outcome Assert.Throws<ArgumentNullException>(() => new DelegatingRecursionGuard(dummyBuilder, null)); // Teardown } [Fact] public void SutYieldsInjectedBuilder() { // Fixture setup var expected = new DelegatingSpecimenBuilder(); var sut = new DelegatingRecursionGuard(expected); // Exercise system // Verify outcome Assert.Equal(expected, sut.Single()); Assert.Equal(expected, ((System.Collections.IEnumerable)sut).Cast<object>().Single()); // Teardown } [Fact] public void ComparerIsCorrect() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var expected = new DelegatingEqualityComparer(); var sut = new DelegatingRecursionGuard(dummyBuilder, expected); // Exercise system IEqualityComparer actual = sut.Comparer; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void CreateWillUseEqualityComparer() { // Fixture setup var builder = new DelegatingSpecimenBuilder(); builder.OnCreate = (r, c) => c.Resolve(r); bool comparerUsed = false; var comparer = new DelegatingEqualityComparer { OnEquals = (x, y) => comparerUsed = true }; var sut = new DelegatingRecursionGuard(builder, comparer); sut.OnHandleRecursiveRequest = (obj) => { return null; }; var container = new DelegatingSpecimenContext(); container.OnResolve = (r) => sut.Create(r, container); // Exercise system sut.Create(Guid.NewGuid(), container); // Verify outcome Assert.True(comparerUsed); } [Fact] public void CreateWillNotTriggerHandlingOnFirstRequest() { // Fixture setup var sut = new DelegatingRecursionGuard(new DelegatingSpecimenBuilder()); bool handlingTriggered = false; sut.OnHandleRecursiveRequest = obj => handlingTriggered = true; // Exercise system sut.Create(Guid.NewGuid(), new DelegatingSpecimenContext()); // Verify outcome Assert.False(handlingTriggered); } [Fact] public void CreateWillNotTriggerHandlingOnSubsequentSimilarRequests() { // Fixture setup var sut = new DelegatingRecursionGuard(new DelegatingSpecimenBuilder()); bool handlingTriggered = false; object request = Guid.NewGuid(); sut.OnHandleRecursiveRequest = obj => handlingTriggered = true; // Exercise system sut.Create(request, new DelegatingSpecimenContext()); sut.Create(request, new DelegatingSpecimenContext()); // Verify outcome Assert.False(handlingTriggered); } [Fact] public void CreateWillTriggerHandlingOnRecursiveRequests() { // Fixture setup var builder = new DelegatingSpecimenBuilder(); builder.OnCreate = (r, c) => c.Resolve(r); var sut = new DelegatingRecursionGuard(builder); bool handlingTriggered = false; sut.OnHandleRecursiveRequest = obj => handlingTriggered = true; var container = new DelegatingSpecimenContext(); container.OnResolve = (r) => sut.Create(r, container); // Exercise system sut.Create(Guid.NewGuid(), container); // Verify outcome Assert.True(handlingTriggered); } [Fact] public void CreateWillNotTriggerHandlingOnSecondarySameRequestWhenDecoratedBuilderThrows() { // Fixture setup var builder = new DelegatingSpecimenBuilder { OnCreate = (r, c) => { throw new PrivateExpectedException("The decorated builder always throws."); }}; var sut = new DelegatingRecursionGuard(builder) { OnHandleRecursiveRequest = o => { throw new PrivateUnexpectedException("Recursive handling should not be triggered."); }}; var dummyContext = new DelegatingSpecimenContext(); var sameRequest = new object(); // Exercise system and verify outcome Assert.Throws<PrivateExpectedException>(() => sut.Create(sameRequest, dummyContext)); Assert.Empty(sut.UnprotectedRecordedRequests); Assert.Throws<PrivateExpectedException>(() => sut.Create(sameRequest, dummyContext)); Assert.Empty(sut.UnprotectedRecordedRequests); } class PrivateExpectedException : Exception { public PrivateExpectedException(string message) : base(message) { } } class PrivateUnexpectedException : Exception { public PrivateUnexpectedException(string message) : base(message) { } } [Fact] public void CreateWillTriggerHandlingOnSecondLevelRecursiveRequest() { // Fixture setup object subRequest1 = Guid.NewGuid(); object subRequest2 = Guid.NewGuid(); var requestScenario = new Stack<object>(new [] { subRequest1, subRequest2, subRequest1 }); var builder = new DelegatingSpecimenBuilder(); builder.OnCreate = (r, c) => c.Resolve(requestScenario.Pop()); var sut = new DelegatingRecursionGuard(builder); object recursiveRequest = null; sut.OnHandleRecursiveRequest = obj => recursiveRequest = obj; var container = new DelegatingSpecimenContext(); container.OnResolve = (r) => sut.Create(r, container); // Exercise system sut.Create(Guid.NewGuid(), container); // Verify outcome Assert.Same(subRequest1, recursiveRequest); } [Fact] public void CreateWillNotTriggerHandlingUntilDeeperThanRecursionDepth() { // Fixture setup var requestScenario = new Queue<int>(new[] { 1, 2, 1, 3, 1, 4 }); var builder = new DelegatingSpecimenBuilder(); builder.OnCreate = (r, c) => c.Resolve(requestScenario.Dequeue()); // By setting the depth to two we expect the handle to be triggered at the third "1" occurence. var sut = new DelegatingRecursionGuard(builder, 2); object recursiveRequest = null; sut.OnHandleRecursiveRequest = obj => recursiveRequest = obj; var container = new DelegatingSpecimenContext(); container.OnResolve = r => sut.Create(r, container); // Exercise system sut.Create(5, container); // Verify outcome // Check that recursion was actually detected as expected Assert.Equal(1, recursiveRequest); // Check that we passed the first recursion, but didn't go any further Assert.Equal(4, requestScenario.Dequeue()); } [Fact] public void ConstructWithBuilderAndRecursionHandlerHasCorrectHandler() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var expected = new DelegatingRecursionHandler(); var sut = new RecursionGuard(dummyBuilder, expected); // Exercise system IRecursionHandler actual = sut.RecursionHandler; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ConstructWithBuilderAndRecursionHandlerHasCorrectBuilder() { // Fixture setup var expected = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var sut = new RecursionGuard(expected, dummyHandler); // Exercise system var actual = sut.Builder; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ConstructWithBuilderAndRecursionHandlerHasCorrectComparer() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var sut = new RecursionGuard(dummyBuilder, dummyHandler); // Exercise system var actual = sut.Comparer; // Verify outcome Assert.Equal(EqualityComparer<object>.Default, actual); // Teardown } [Fact] public void ConstructWithNullBuilderAndRecursionHandlerThrows() { // Fixture setup var dummyHandler = new DelegatingRecursionHandler(); // Exercise system and verify outcome Assert.Throws<ArgumentNullException>( () => new RecursionGuard(null, dummyHandler)); // Teardown } [Fact] public void ConstructWithBuilderAndNullRecursionHandlerThrows() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); // Exercise system and verify outcome Assert.Throws<ArgumentNullException>( () => new RecursionGuard(dummyBuilder, (IRecursionHandler)null)); // Teardown } [Fact] public void ConstructWithBuilderAndHandlerAndComparerAndRecursionDepthHasCorrectBuilder() { // Fixture setup var expected = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); var dummyRecursionDepth = 2; var sut = new RecursionGuard(expected, dummyHandler, dummyComparer, dummyRecursionDepth); // Exercise system var actual = sut.Builder; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ConstructWithBuilderAndHandlerAndComparerAndRecursionDepthHasCorrectHandler() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var expected = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); var dummyRecursionDepth = 2; var sut = new RecursionGuard(dummyBuilder, expected, dummyComparer, dummyRecursionDepth); // Exercise system var actual = sut.RecursionHandler; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ConstructWithBuilderAndHandlerAndComparerAndRecursionDepthHasCorrectComparer() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var expected = new DelegatingEqualityComparer(); var dummyRecursionDepth = 2; var sut = new RecursionGuard(dummyBuilder, dummyHandler, expected, dummyRecursionDepth); // Exercise system var actual = sut.Comparer; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ConstructWithBuilderAndHandlerAndComparerAndRecursionDepthHasCorrectRecursionDepth() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); var expected = 2; var sut = new RecursionGuard(dummyBuilder, dummyHandler, dummyComparer, expected); // Exercise system var actual = sut.RecursionDepth; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ConstructWithNullBuilderAndHandlerAndComparerAndRecursionDepthThrows() { // Fixture setup var dummyHandler = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); var dummyRecursionDepth = 2; // Exercise system and verify outcome Assert.Throws<ArgumentNullException>( () => new RecursionGuard(null, dummyHandler, dummyComparer, dummyRecursionDepth)); // Teardown } [Fact] public void ConstructWithBuilderAndNullHandlerAndComparerAndRecursionDepthThrows() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyComparer = new DelegatingEqualityComparer(); var dummyRecursionDepth = 2; // Exercise system and verify outcome Assert.Throws<ArgumentNullException>( () => new RecursionGuard(dummyBuilder, null, dummyComparer, dummyRecursionDepth)); // Teardown } [Fact] public void ConstructWithBuilderAndHandlerAndNullComparerAndRecursionDepthThrows() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var dummyRecursionDepth = 2; // Exercise system and verify outcome Assert.Throws<ArgumentNullException>( () => new RecursionGuard(dummyBuilder, dummyHandler, null, dummyRecursionDepth)); // Teardown } [Fact] public void ConstructWithBuilderSetsRecursionDepthCorrectly() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); // Exercise system #pragma warning disable 618 var sut = new RecursionGuard(dummyBuilder); #pragma warning restore 618 // Verify outcome Assert.Equal(1, sut.RecursionDepth); } [Fact] public void ConstructWithBuilderAndHandlerSetsRecursionDepthCorrectly() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); // Exercise system var sut = new RecursionGuard(dummyBuilder, dummyHandler); // Verify outcome Assert.Equal(1, sut.RecursionDepth); } [Fact] public void ConstructWithBuilderAndHandlerAndComparerHasCorrectBuilder() { // Fixture setup var expected = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); #pragma warning disable 618 var sut = new RecursionGuard(expected, dummyHandler, dummyComparer); #pragma warning restore 618 // Exercise system var actual = sut.Builder; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ConstructWithBuilderAndHandlerAndComparerHasCorrectHandler() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var expected = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); #pragma warning disable 618 var sut = new RecursionGuard(dummyBuilder, expected, dummyComparer); #pragma warning restore 618 // Exercise system var actual = sut.RecursionHandler; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ConstructWithBuilderAndHandlerAndComparerHasCorrectComparer() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var expected = new DelegatingEqualityComparer(); #pragma warning disable 618 var sut = new RecursionGuard(dummyBuilder, dummyHandler, expected); #pragma warning restore 618 // Exercise system var actual = sut.Comparer; // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ConstructWithBuilderAndHandlerAndRecursionDepthSetsRecursionDepthCorrectly() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); const int explicitRecursionDepth = 2; // Exercise system var sut = new RecursionGuard(dummyBuilder, dummyHandler, explicitRecursionDepth); // Verify outcome Assert.Equal(explicitRecursionDepth, sut.RecursionDepth); } [Fact] public void CreateReturnsResultFromInjectedHandlerWhenRequestIsMatched() { // Fixture setup var builder = new DelegatingSpecimenBuilder() { OnCreate = (r, ctx) => ctx.Resolve(r) }; var request = new object(); var expected = new object(); var handlerStub = new DelegatingRecursionHandler { OnHandleRecursiveRequest = (r, rs) => { Assert.Equal(request, r); Assert.NotNull(rs); return expected; } }; var comparer = new DelegatingEqualityComparer { OnEquals = (x, y) => true }; var sut = new RecursionGuard(builder, handlerStub, comparer, 1); var context = new DelegatingSpecimenContext(); context.OnResolve = r => sut.Create(r, context); // Exercise system var actual = sut.Create(request, context); // Verify outcome Assert.Equal(expected, actual); // Teardown } [Fact] public void ComposeReturnsCorrectResult() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); const int dummyRecursionDepth = 2; var sut = new RecursionGuard(dummyBuilder, dummyHandler, dummyComparer, dummyRecursionDepth); // Exercise system var expectedBuilders = new[] { new DelegatingSpecimenBuilder(), new DelegatingSpecimenBuilder(), new DelegatingSpecimenBuilder() }; var actual = sut.Compose(expectedBuilders); // Verify outcome var rg = Assert.IsAssignableFrom<RecursionGuard>(actual); var composite = Assert.IsAssignableFrom<CompositeSpecimenBuilder>(rg.Builder); Assert.True(expectedBuilders.SequenceEqual(composite)); // Teardown } [Fact] public void ComposeSingleItemReturnsCorrectResult() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); int dummyRecursionDepth = 2; var sut = new RecursionGuard(dummyBuilder, dummyHandler, dummyComparer, dummyRecursionDepth); // Exercise system var expected = new DelegatingSpecimenBuilder(); var actual = sut.Compose(new[] { expected }); // Verify outcome var rg = Assert.IsAssignableFrom<RecursionGuard>(actual); Assert.Equal(expected, rg.Builder); // Teardown } [Fact] public void ComposeRetainsHandler() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var expected = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); int dummyRecursionDepth = 2; var sut = new RecursionGuard(dummyBuilder, expected, dummyComparer, dummyRecursionDepth); // Exercise system var actual = sut.Compose(new ISpecimenBuilder[0]); // Verify outcome var rg = Assert.IsAssignableFrom<RecursionGuard>(actual); Assert.Equal(expected, rg.RecursionHandler); // Teardown } [Fact] public void ComposeRetainsComparer() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var expected = new DelegatingEqualityComparer(); int dummyRecursionDepth = 2; var sut = new RecursionGuard(dummyBuilder, dummyHandler, expected, dummyRecursionDepth); // Exercise system var actual = sut.Compose(new ISpecimenBuilder[0]); // Verify outcome var rg = Assert.IsAssignableFrom<RecursionGuard>(actual); Assert.Equal(expected, rg.Comparer); // Teardown } [Fact] public void ComposeRetainsRecursionDepth() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); int expected = 2; var sut = new RecursionGuard(dummyBuilder, dummyHandler, dummyComparer, expected); // Exercise system var actual = sut.Compose(new ISpecimenBuilder[0]); // Verify outcome var rg = Assert.IsAssignableFrom<RecursionGuard>(actual); Assert.Equal(expected, rg.RecursionDepth); // Teardown } [Fact] public void CreateOnMultipleThreadsConcurrentlyWorks() { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder { OnCreate = (r, ctx) => ctx.Resolve(r) }; var dummyHandler = new DelegatingRecursionHandler(); var sut = new RecursionGuard(dummyBuilder, dummyHandler); var dummyContext = new DelegatingSpecimenContext() { OnResolve = (r) => 99 }; // Exercise system int[] specimens = Enumerable.Range(0, 1000) .AsParallel() .WithDegreeOfParallelism(8) .WithExecutionMode(ParallelExecutionMode.ForceParallelism) .Select(x => (int)sut.Create(typeof(int), dummyContext)) .ToArray(); // Verify outcome Assert.Equal(1000, specimens.Length); Assert.True(specimens.All(s => s == 99)); // Teardown } [Theory] [InlineData(0)] [InlineData(-7)] [InlineData(-42)] public void ConstructorWithRecusionDepthLowerThanOneThrows(int recursionDepth) { // Fixture setup var dummyBuilder = new DelegatingSpecimenBuilder(); var dummyHandler = new DelegatingRecursionHandler(); var dummyComparer = new DelegatingEqualityComparer(); // Exercise system and verify outcome Assert.Throws<ArgumentOutOfRangeException>(() => new RecursionGuard(dummyBuilder, dummyHandler, dummyComparer, recursionDepth)); // Teardown } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Threading; using Android.App; using Android.Content; using Android.Content.PM; using Android.Net; using Android.OS; using Android.Provider; using Android.Speech; using Android.Support.V4.Content; using Android.Widget; using Newtonsoft.Json; using SensusService; using Xamarin; using SensusService.Probes.Location; using SensusService.Probes; using SensusService.Probes.Movement; using System.Linq; using ZXing.Mobile; using Android.Graphics; using Android.Media; using System.Threading.Tasks; using Plugin.Permissions.Abstractions; using SensusService.Exceptions; namespace Sensus.Android { public class AndroidSensusServiceHelper : SensusServiceHelper { private AndroidSensusService _service; private ConnectivityManager _connectivityManager; private NotificationManager _notificationManager; private string _deviceId; private AndroidMainActivity _focusedMainActivity; private readonly object _focusedMainActivityLocker = new object(); private AndroidTextToSpeech _textToSpeech; private PowerManager.WakeLock _wakeLock; private int _wakeLockAcquisitionCount; private List<Action<AndroidMainActivity>> _actionsToRunUsingMainActivity; private Dictionary<string, PendingIntent> _callbackIdPendingIntent; [JsonIgnore] public AndroidSensusService Service { get { return _service; } } public override string DeviceId { get { return _deviceId; } } public override bool WiFiConnected { get { // https://github.com/predictive-technology-laboratory/sensus/wiki/Backwards-Compatibility #if __ANDROID_23__ if (Build.VERSION.SdkInt >= BuildVersionCodes.M) return _connectivityManager.GetAllNetworks().Select(network => _connectivityManager.GetNetworkInfo(network)).Any(networkInfo => networkInfo.Type == ConnectivityType.Wifi && networkInfo.IsConnected); // API level 23 else #endif { // ignore deprecation warning #pragma warning disable 618 return _connectivityManager.GetNetworkInfo(ConnectivityType.Wifi).IsConnected; #pragma warning restore 618 } } } public override bool IsCharging { get { IntentFilter filter = new IntentFilter(Intent.ActionBatteryChanged); BatteryStatus status = (BatteryStatus)_service.RegisterReceiver(null, filter).GetIntExtra(BatteryManager.ExtraStatus, -1); return status == BatteryStatus.Charging || status == BatteryStatus.Full; } } public override string OperatingSystem { get { return "Android " + Build.VERSION.SdkInt; } } protected override bool IsOnMainThread { get { // we should always have a service. if we do not, assume the worst -- that we're on the main thread. this will hopefully // produce an error report back at xamarin insights. if (_service == null) return true; // if we have a service, compare the current thread's looper to the main thread's looper else return Looper.MyLooper() == _service.MainLooper; } } [JsonIgnore] public int WakeLockAcquisitionCount { get { return _wakeLockAcquisitionCount; } } public AndroidSensusServiceHelper() { _actionsToRunUsingMainActivity = new List<Action<AndroidMainActivity>>(); _callbackIdPendingIntent = new Dictionary<string, PendingIntent>(); } public void SetService(AndroidSensusService service) { _service = service; if (_service == null) { if (_connectivityManager != null) _connectivityManager.Dispose(); if (_notificationManager != null) _notificationManager.Dispose(); if (_textToSpeech != null) _textToSpeech.Dispose(); if (_wakeLock != null) _wakeLock.Dispose(); } else { _connectivityManager = _service.GetSystemService(Context.ConnectivityService) as ConnectivityManager; _notificationManager = _service.GetSystemService(Context.NotificationService) as NotificationManager; _textToSpeech = new AndroidTextToSpeech(_service); _wakeLock = (_service.GetSystemService(Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS"); _wakeLockAcquisitionCount = 0; _deviceId = Settings.Secure.GetString(_service.ContentResolver, Settings.Secure.AndroidId); // must initialize after _deviceId is set if (Insights.IsInitialized) Insights.Identify(_deviceId, "Device ID", _deviceId); } } #region main activity /// <summary> /// Runs an action using main activity, optionally bringing the main activity into focus if it is not already focused. /// </summary> /// <param name="action">Action to run.</param> /// <param name="startMainActivityIfNotFocused">Whether or not to start the main activity if it is not currently focused.</param> /// <param name="holdActionIfNoActivity">If the main activity is not focused and we're not starting a new one to refocus it, whether /// or not to hold the action for later when the activity is refocused.</param> public void RunActionUsingMainActivityAsync(Action<AndroidMainActivity> action, bool startMainActivityIfNotFocused, bool holdActionIfNoActivity) { // this must be done asynchronously because it blocks waiting for the activity to start. calling this method from the UI would create deadlocks. new Thread(() => { lock (_focusedMainActivityLocker) { // run actions now only if the main activity is focused. this is a stronger requirement than merely started/resumed since it // implies that the user interface is up. this is important because if certain actions (e.g., speech recognition) are run // after the activity is resumed but before the window is up, the appearance of the activity's window can hide/cancel the // action's window. if (_focusedMainActivity == null) { if (startMainActivityIfNotFocused) { // we'll run the action when the activity is focused lock (_actionsToRunUsingMainActivity) _actionsToRunUsingMainActivity.Add(action); Logger.Log("Starting main activity to run action.", LoggingLevel.Normal, GetType()); // start the activity. when it starts, it will call back to SetFocusedMainActivity indicating readiness. once // this happens, we'll be ready to run the action that was just passed in as well as any others that need to be run. Intent intent = new Intent(_service, typeof(AndroidMainActivity)); intent.AddFlags(ActivityFlags.FromBackground | ActivityFlags.NewTask); _service.StartActivity(intent); } else if (holdActionIfNoActivity) { // we'll run the action the next time the activity is focused lock (_actionsToRunUsingMainActivity) _actionsToRunUsingMainActivity.Add(action); } } else { // we'll run the action now lock (_actionsToRunUsingMainActivity) _actionsToRunUsingMainActivity.Add(action); RunActionsUsingMainActivity(); } } }).Start(); } public void SetFocusedMainActivity(AndroidMainActivity focusedMainActivity) { lock (_focusedMainActivityLocker) { _focusedMainActivity = focusedMainActivity; if (_focusedMainActivity == null) Logger.Log("Main activity not focused.", LoggingLevel.Normal, GetType()); else { Logger.Log("Main activity focused.", LoggingLevel.Normal, GetType()); RunActionsUsingMainActivity(); } } } private void RunActionsUsingMainActivity() { lock (_focusedMainActivityLocker) { lock (_actionsToRunUsingMainActivity) { Logger.Log("Running " + _actionsToRunUsingMainActivity.Count + " actions using main activity.", LoggingLevel.Debug, GetType()); foreach (Action<AndroidMainActivity> action in _actionsToRunUsingMainActivity) action(_focusedMainActivity); _actionsToRunUsingMainActivity.Clear(); } } } #endregion #region miscellaneous platform-specific functions protected override void InitializeXamarinInsights() { Insights.Initialize(XAMARIN_INSIGHTS_APP_KEY, Application.Context); // can't reference _service here since this method is called from the base class constructor, before the service is set. } public override void PromptForAndReadTextFileAsync(string promptTitle, Action<string> callback) { new Thread(() => { try { Intent intent = new Intent(Intent.ActionGetContent); intent.SetType("*/*"); intent.AddCategory(Intent.CategoryOpenable); RunActionUsingMainActivityAsync(mainActivity => { mainActivity.GetActivityResultAsync(intent, AndroidActivityResultRequestCode.PromptForFile, result => { if (result != null && result.Item1 == Result.Ok) try { using (StreamReader file = new StreamReader(_service.ContentResolver.OpenInputStream(result.Item2.Data))) { callback(file.ReadToEnd()); } } catch (Exception ex) { FlashNotificationAsync("Error reading text file: " + ex.Message); } }); }, true, false); } catch (ActivityNotFoundException) { FlashNotificationAsync("Please install a file manager from the Apps store."); } catch (Exception ex) { FlashNotificationAsync("Something went wrong while prompting you for a file to read: " + ex.Message); } }).Start(); } public override void ShareFileAsync(string path, string subject, string mimeType) { new Thread(() => { try { Intent intent = new Intent(Intent.ActionSend); intent.SetType(mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); if (!string.IsNullOrWhiteSpace(subject)) intent.PutExtra(Intent.ExtraSubject, subject); Java.IO.File file = new Java.IO.File(path); global::Android.Net.Uri uri = FileProvider.GetUriForFile(_service, "edu.virginia.sie.ptl.sensus.fileprovider", file); intent.PutExtra(Intent.ExtraStream, uri); // run from main activity to get a smoother transition back to sensus RunActionUsingMainActivityAsync(mainActivity => { mainActivity.StartActivity(intent); }, true, false); } catch (Exception ex) { Logger.Log("Failed to start intent to share file \"" + path + "\": " + ex.Message, LoggingLevel.Normal, GetType()); } }).Start(); } public override void SendEmailAsync(string toAddress, string subject, string message) { RunActionUsingMainActivityAsync(mainActivity => { Intent emailIntent = new Intent(Intent.ActionSend); emailIntent.PutExtra(Intent.ExtraEmail, new string[] { toAddress }); emailIntent.PutExtra(Intent.ExtraSubject, subject); emailIntent.PutExtra(Intent.ExtraText, message); emailIntent.SetType("text/plain"); mainActivity.StartActivity(emailIntent); }, true, false); } public override void TextToSpeechAsync(string text, Action callback) { _textToSpeech.SpeakAsync(text, callback); } public override void RunVoicePromptAsync(string prompt, Action postDisplayCallback, Action<string> callback) { new Thread(() => { string input = null; ManualResetEvent dialogDismissWait = new ManualResetEvent(false); RunActionUsingMainActivityAsync(mainActivity => { mainActivity.RunOnUiThread(() => { #region set up dialog TextView promptView = new TextView(mainActivity) { Text = prompt, TextSize = 20 }; EditText inputEdit = new EditText(mainActivity) { TextSize = 20 }; LinearLayout scrollLayout = new LinearLayout(mainActivity){ Orientation = global::Android.Widget.Orientation.Vertical }; scrollLayout.AddView(promptView); scrollLayout.AddView(inputEdit); ScrollView scrollView = new ScrollView(mainActivity); scrollView.AddView(scrollLayout); AlertDialog dialog = new AlertDialog.Builder(mainActivity) .SetTitle("Sensus is requesting input...") .SetView(scrollView) .SetPositiveButton("OK", (o, e) => { input = inputEdit.Text; }) .SetNegativeButton("Cancel", (o, e) => { }) .Create(); dialog.DismissEvent += (o, e) => { dialogDismissWait.Set(); }; ManualResetEvent dialogShowWait = new ManualResetEvent(false); dialog.ShowEvent += (o, e) => { dialogShowWait.Set(); if (postDisplayCallback != null) postDisplayCallback(); }; // dismiss the keyguard when dialog appears dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.DismissKeyguard); dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.ShowWhenLocked); dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.TurnScreenOn); dialog.Window.SetSoftInputMode(global::Android.Views.SoftInput.AdjustResize | global::Android.Views.SoftInput.StateAlwaysHidden); // dim whatever is behind the dialog dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.DimBehind); dialog.Window.Attributes.DimAmount = 0.75f; dialog.Show(); #endregion #region voice recognizer new Thread(() => { // wait for the dialog to be shown so it doesn't hide our speech recognizer activity dialogShowWait.WaitOne(); // there's a slight race condition between the dialog showing and speech recognition showing. pause here to prevent the dialog from hiding the speech recognizer. Thread.Sleep(1000); Intent intent = new Intent(RecognizerIntent.ActionRecognizeSpeech); intent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm); intent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500); intent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500); intent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000); intent.PutExtra(RecognizerIntent.ExtraMaxResults, 1); intent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default); intent.PutExtra(RecognizerIntent.ExtraPrompt, prompt); mainActivity.GetActivityResultAsync(intent, AndroidActivityResultRequestCode.RecognizeSpeech, result => { if (result != null && result.Item1 == Result.Ok) { IList<string> matches = result.Item2.GetStringArrayListExtra(RecognizerIntent.ExtraResults); if (matches != null && matches.Count > 0) mainActivity.RunOnUiThread(() => { inputEdit.Text = matches[0]; }); } }); }).Start(); #endregion }); }, true, false); dialogDismissWait.WaitOne(); callback(input); }).Start(); } #endregion #region notifications public override void IssueNotificationAsync(string message, string id) { IssueNotificationAsync("Sensus", message, true, false, id); } public void IssueNotificationAsync(string title, string message, bool autoCancel, bool ongoing, string id) { if (_notificationManager != null) { new Thread(() => { if (message == null) _notificationManager.Cancel(id, 0); else { Intent activityIntent = new Intent(_service, typeof(AndroidMainActivity)); PendingIntent pendingIntent = PendingIntent.GetActivity(_service, 0, activityIntent, PendingIntentFlags.UpdateCurrent); Notification notification = new Notification.Builder(_service) .SetContentTitle(title) .SetContentText(message) .SetSmallIcon(Resource.Drawable.ic_launcher) .SetContentIntent(pendingIntent) .SetAutoCancel(autoCancel) .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification)) .SetVibrate(new long[] { 0, 250, 50, 250 }) .SetOngoing(ongoing).Build(); _notificationManager.Notify(id, 0, notification); } }).Start(); } } protected override void ProtectedFlashNotificationAsync(string message, bool flashLaterIfNotVisible, Action callback) { new Thread(() => { RunActionUsingMainActivityAsync(mainActivity => { mainActivity.RunOnUiThread(() => { Toast.MakeText(mainActivity, message, ToastLength.Long).Show(); if (callback != null) callback(); }); }, false, flashLaterIfNotVisible); }).Start(); } public override bool EnableProbeWhenEnablingAll(Probe probe) { // listening for locations doesn't work very well in android, since it conflicts with polling and uses more power. don't enable probes that need location listening by default. return !(probe is ListeningLocationProbe) && !(probe is ListeningSpeedProbe) && !(probe is ListeningPointsOfInterestProximityProbe); } public override Xamarin.Forms.ImageSource GetQrCodeImageSource(string contents) { return Xamarin.Forms.ImageSource.FromStream(() => { Bitmap bitmap = BarcodeWriter.Write(contents); MemoryStream ms = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 100, ms); ms.Seek(0, SeekOrigin.Begin); return ms; }); } #endregion #region callback scheduling protected override void ScheduleRepeatingCallback(string callbackId, int initialDelayMS, int repeatDelayMS, bool repeatLag) { DateTime callbackTime = DateTime.Now.AddMilliseconds(initialDelayMS); Logger.Log("Callback " + callbackId + " scheduled for " + callbackTime + " (repeating).", LoggingLevel.Normal, GetType()); ScheduleCallbackAlarm(CreateCallbackIntent(callbackId, true, repeatDelayMS, repeatLag), callbackTime); } protected override void ScheduleOneTimeCallback(string callbackId, int delayMS) { DateTime callbackTime = DateTime.Now.AddMilliseconds(delayMS); Logger.Log("Callback " + callbackId + " scheduled for " + callbackTime + " (one-time).", LoggingLevel.Normal, GetType()); ScheduleCallbackAlarm(CreateCallbackIntent(callbackId, false, 0, false), callbackTime); } private PendingIntent CreateCallbackIntent(string callbackId, bool repeating, int repeatDelayMS, bool repeatLag) { Intent callbackIntent = new Intent(_service, typeof(AndroidSensusService)); callbackIntent.PutExtra(SENSUS_CALLBACK_KEY, true); callbackIntent.PutExtra(SENSUS_CALLBACK_ID_KEY, callbackId); callbackIntent.PutExtra(SENSUS_CALLBACK_REPEATING_KEY, repeating); callbackIntent.PutExtra(SENSUS_CALLBACK_REPEAT_DELAY_KEY, repeatDelayMS); callbackIntent.PutExtra(SENSUS_CALLBACK_REPEAT_LAG_KEY, repeatLag); PendingIntent callbackPendingIntent = PendingIntent.GetService(_service, callbackId.GetHashCode(), callbackIntent, PendingIntentFlags.CancelCurrent); // upon hash collisions on the request code, the previous intent will simply be canceled. lock (_callbackIdPendingIntent) _callbackIdPendingIntent.Add(callbackId, callbackPendingIntent); return callbackPendingIntent; } public void ScheduleCallbackAlarm(PendingIntent callbackPendingIntent, DateTime callbackTime) { AlarmManager alarmManager = _service.GetSystemService(Context.AlarmService) as AlarmManager; long delayMS = (long)(callbackTime - DateTime.Now).TotalMilliseconds; long callbackTimeMS = Java.Lang.JavaSystem.CurrentTimeMillis() + delayMS; // https://github.com/predictive-technology-laboratory/sensus/wiki/Backwards-Compatibility #if __ANDROID_23__ if (Build.VERSION.SdkInt >= BuildVersionCodes.M) alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent); // API level 23 added "while idle" option, making things even tighter. else if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat) alarmManager.SetExact(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent); // API level 19 differentiated Set (loose) from SetExact (tight) else #endif { alarmManager.Set(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent); // API 1-18 treats Set as a tight alarm } } protected override void UnscheduleCallbackPlatformSpecific(string callbackId) { lock (_callbackIdPendingIntent) { PendingIntent callbackPendingIntent; if (_callbackIdPendingIntent.TryGetValue(callbackId, out callbackPendingIntent)) { AlarmManager alarmManager = _service.GetSystemService(Context.AlarmService) as AlarmManager; alarmManager.Cancel(callbackPendingIntent); _callbackIdPendingIntent.Remove(callbackId); } } } #endregion #region device awake / sleep public override void KeepDeviceAwake() { lock (_wakeLock) { _wakeLock.Acquire(); Logger.Log("Wake lock acquisition count: " + ++_wakeLockAcquisitionCount, LoggingLevel.Normal, GetType()); } } public override void LetDeviceSleep() { lock (_wakeLock) { _wakeLock.Release(); Logger.Log("Wake lock acquisition count: " + --_wakeLockAcquisitionCount, LoggingLevel.Normal, GetType()); } } public override void BringToForeground() { ManualResetEvent foregroundWait = new ManualResetEvent(false); RunActionUsingMainActivityAsync(mainActivity => { foregroundWait.Set(); }, true, false); foregroundWait.WaitOne(); } #endregion public override void Stop() { // stop protocols and clean up base.Stop(); if (_service != null) _service.Stop(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using SafeCurlHandle = Interop.libcurl.SafeCurlHandle; using SafeCurlMultiHandle = Interop.libcurl.SafeCurlMultiHandle; using SafeCurlSlistHandle = Interop.libcurl.SafeCurlSlistHandle; using CURLoption = Interop.libcurl.CURLoption; using CURLMoption = Interop.libcurl.CURLMoption; using CURLcode = Interop.libcurl.CURLcode; using CURLMcode = Interop.libcurl.CURLMcode; using CURLINFO = Interop.libcurl.CURLINFO; using CURLAUTH = Interop.libcurl.CURLAUTH; using CurlVersionInfoData = Interop.libcurl.curl_version_info_data; using CurlFeatures = Interop.libcurl.CURL_VERSION_Features; using CURLProxyType = Interop.libcurl.curl_proxytype; using size_t = System.IntPtr; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { #region Constants private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private readonly static string[] AuthenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes private readonly static ulong[] AuthSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic }; private static readonly string[] s_headerDelimiters = new string[] { "\r\n" }; private const int s_requestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private readonly static CurlVersionInfoData curlVersionInfoData; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private static readonly bool _supportsAutomaticDecompression; private static readonly bool _supportsSSL; private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy; private DecompressionMethods _automaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; private SafeCurlMultiHandle _multiHandle; private GCHandle _multiHandlePtr = new GCHandle(); private bool _preAuthenticate = false; private CredentialCache _credentialCache = null; private CookieContainer _cookieContainer = null; private bool _useCookie = false; private bool _automaticRedirection = true; private int _maxAutomaticRedirections = 50; #endregion static CurlHandler() { int result = Interop.libcurl.curl_global_init(Interop.libcurl.CurlGlobalFlags.CURL_GLOBAL_ALL); if (result != CURLcode.CURLE_OK) { throw new InvalidOperationException("Cannot use libcurl in this process"); } curlVersionInfoData = Marshal.PtrToStructure<CurlVersionInfoData>(Interop.libcurl.curl_version_info(CurlAge)); if (curlVersionInfoData.age < MinCurlAge) { throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old); } _supportsSSL = (CurlFeatures.CURL_VERSION_SSL & curlVersionInfoData.features) != 0; _supportsAutomaticDecompression = (CurlFeatures.CURL_VERSION_LIBZ & curlVersionInfoData.features) != 0; } internal CurlHandler() { _multiHandle = Interop.libcurl.curl_multi_init(); if (_multiHandle.IsInvalid) { throw new HttpRequestException(SR.net_http_client_execution_error); } _multiHandle.Timer = new Timer(CurlTimerElapsed, _multiHandle, Timeout.Infinite, Timeout.Infinite); SetCurlMultiOptions(); } #region Properties internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy { get { return true; } } internal bool UseProxy { get { return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy; } set { CheckDisposedOrStarted(); if (value) { _proxyPolicy = ProxyUsePolicy.UseCustomProxy; } else { _proxyPolicy = ProxyUsePolicy.DoNotUseProxy; } } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return ClientCertificateOption.Manual; } set { if (ClientCertificateOption.Manual != value) { throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option); } } } internal bool SupportsAutomaticDecompression { get { return _supportsAutomaticDecompression; } } internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( "value", value, string.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } #endregion protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_multiHandlePtr.IsAllocated) { _multiHandlePtr.Free(); } _multiHandle = null; } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request", SR.net_http_handler_norequest); } if ((request.RequestUri.Scheme != UriSchemeHttp) && (request.RequestUri.Scheme != UriSchemeHttps)) { throw NotImplemented.ByDesignWithMessage(SR.net_http_client_http_baseaddress_required); } if (request.RequestUri.Scheme == UriSchemeHttps && !_supportsSSL) { throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } // TODO: Check that SendAsync is not being called again for same request object. // Probably fix is needed in WinHttpHandler as well CheckDisposed(); SetOperationStarted(); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create RequestCompletionSource object and save current values of handler settings. RequestCompletionSource state = new RequestCompletionSource(this, cancellationToken, request); BeginRequest(state); return state.Task; } #region Private methods private async void BeginRequest(RequestCompletionSource state) { SafeCurlHandle requestHandle = new SafeCurlHandle(); GCHandle stateHandle = new GCHandle(); bool needCleanup = false; try { // Prepare context objects state.ResponseMessage = new CurlResponseMessage(state.RequestMessage); stateHandle = GCHandle.Alloc(state); requestHandle = CreateRequestHandle(state, stateHandle); state.RequestHandle = requestHandle; needCleanup = true; if (state.CancellationToken.IsCancellationRequested) { state.TrySetCanceled(state.CancellationToken); return; } if (state.RequestMessage.Content != null) { Stream requestContentStream = await state.RequestMessage.Content.ReadAsStreamAsync().ConfigureAwait(false); if (state.CancellationToken.IsCancellationRequested) { state.TrySetCanceled(state.CancellationToken); return; } state.RequestContentStream = requestContentStream; state.RequestContentBuffer = new byte[s_requestBufferSize]; } AddEasyHandle(state); needCleanup = false; } catch (Exception ex) { HandleAsyncException(state, ex); } finally { if (needCleanup) { RemoveEasyHandle(_multiHandle, stateHandle, false); } else if (state.Task.IsCompleted) { if (stateHandle.IsAllocated) { stateHandle.Free(); } if (!requestHandle.IsInvalid) { SafeCurlHandle.DisposeAndClearHandle(ref requestHandle); } } } } private static void EndRequest(SafeCurlMultiHandle multiHandle, IntPtr statePtr, int result) { GCHandle stateHandle = GCHandle.FromIntPtr(statePtr); RequestCompletionSource state = (RequestCompletionSource)stateHandle.Target; try { // No more callbacks so no more data state.ResponseMessage.ContentStream.SignalComplete(); if (CURLcode.CURLE_OK == result) { state.TrySetResult(state.ResponseMessage); } else { state.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result))); } if (state.ResponseMessage.StatusCode != HttpStatusCode.Unauthorized && state.Handler.PreAuthenticate) { ulong availedAuth; if (Interop.libcurl.curl_easy_getinfo(state.RequestHandle, CURLINFO.CURLINFO_HTTPAUTH_AVAIL, out availedAuth) == CURLcode.CURLE_OK) { state.Handler.AddCredentialToCache(state.RequestMessage.RequestUri, availedAuth, state.NetworkCredential); } // ignoring the exception in this case. // There is no point in killing the request for the sake of putting the credentials into the cache } } catch (Exception ex) { HandleAsyncException(state, ex); } finally { RemoveEasyHandle(multiHandle, stateHandle, true); } } private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private SafeCurlHandle CreateRequestHandle(RequestCompletionSource state, GCHandle stateHandle) { // TODO: If this impacts perf, optimize using a handle pool SafeCurlHandle requestHandle = Interop.libcurl.curl_easy_init(); if (requestHandle.IsInvalid) { throw new HttpRequestException(SR.net_http_client_execution_error); } SetCurlOption(requestHandle, CURLoption.CURLOPT_URL, state.RequestMessage.RequestUri.AbsoluteUri); if (_automaticRedirection) { SetCurlOption(requestHandle, CURLoption.CURLOPT_FOLLOWLOCATION, 1L); // Set maximum automatic redirection option SetCurlOption(requestHandle, CURLoption.CURLOPT_MAXREDIRS, _maxAutomaticRedirections); } if (state.RequestMessage.Method == HttpMethod.Put) { SetCurlOption(requestHandle, CURLoption.CURLOPT_UPLOAD, 1L); } else if (state.RequestMessage.Method == HttpMethod.Head) { SetCurlOption(requestHandle, CURLoption.CURLOPT_NOBODY, 1L); } else if (state.RequestMessage.Method == HttpMethod.Post) { SetCurlOption(requestHandle, CURLoption.CURLOPT_POST, 1L); if (state.RequestMessage.Content == null) { SetCurlOption(requestHandle, CURLoption.CURLOPT_POSTFIELDSIZE, 0L); SetCurlOption(requestHandle, CURLoption.CURLOPT_POSTFIELDS, ""); } } IntPtr statePtr = GCHandle.ToIntPtr(stateHandle); SetCurlOption(requestHandle, CURLoption.CURLOPT_PRIVATE, statePtr); SetCurlCallbacks(requestHandle, state.RequestMessage, statePtr); if (_supportsAutomaticDecompression) { SetRequestHandleDecompressionOptions(requestHandle); } SetProxyOptions(requestHandle, state.RequestMessage.RequestUri); SetRequestHandleCredentialsOptions(requestHandle, state); SetCookieOption(requestHandle, state.RequestMessage.RequestUri); state.RequestHeaderHandle = SetRequestHeaders(requestHandle, state.RequestMessage); return requestHandle; } private void SetRequestHandleDecompressionOptions(SafeCurlHandle requestHandle) { bool gzip = (AutomaticDecompression & DecompressionMethods.GZip) != 0; bool deflate = (AutomaticDecompression & DecompressionMethods.Deflate) != 0; if (gzip || deflate) { string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate : gzip ? EncodingNameGzip : EncodingNameDeflate ; SetCurlOption(requestHandle, CURLoption.CURLOPT_ACCEPTENCODING, encoding); } } private void SetProxyOptions(SafeCurlHandle requestHandle, Uri requestUri) { if (_proxyPolicy == ProxyUsePolicy.DoNotUseProxy) { SetCurlOption(requestHandle, CURLoption.CURLOPT_PROXY, string.Empty); return; } if ((_proxyPolicy == ProxyUsePolicy.UseDefaultProxy) || (Proxy == null)) { return; } Debug.Assert( (Proxy != null) && (_proxyPolicy == ProxyUsePolicy.UseCustomProxy)); if (Proxy.IsBypassed(requestUri)) { SetCurlOption(requestHandle, CURLoption.CURLOPT_PROXY, string.Empty); return; } var proxyUri = Proxy.GetProxy(requestUri); if (proxyUri == null) { return; } SetCurlOption(requestHandle, CURLoption.CURLOPT_PROXYTYPE, CURLProxyType.CURLPROXY_HTTP); SetCurlOption(requestHandle, CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri); SetCurlOption(requestHandle, CURLoption.CURLOPT_PROXYPORT, proxyUri.Port); NetworkCredential credentials = GetCredentials(Proxy.Credentials, requestUri); if (credentials != null) { if (string.IsNullOrEmpty(credentials.UserName)) { throw new ArgumentException(SR.net_http_argument_empty_string, "UserName"); } string credentialText; if (string.IsNullOrEmpty(credentials.Domain)) { credentialText = string.Format("{0}:{1}", credentials.UserName, credentials.Password); } else { credentialText = string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain); } SetCurlOption(requestHandle, CURLoption.CURLOPT_PROXYUSERPWD, credentialText); } } private void SetRequestHandleCredentialsOptions(SafeCurlHandle requestHandle, RequestCompletionSource state) { NetworkCredential credentials = GetNetworkCredentials(state.Handler._serverCredentials, state.RequestMessage.RequestUri); if (credentials != null) { string userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : string.Format("{0}\\{1}", credentials.Domain, credentials.UserName); SetCurlOption(requestHandle, CURLoption.CURLOPT_USERNAME, userName); SetCurlOption(requestHandle, CURLoption.CURLOPT_HTTPAUTH, CURLAUTH.AuthAny); if (credentials.Password != null) { SetCurlOption(requestHandle, CURLoption.CURLOPT_PASSWORD, credentials.Password); } state.NetworkCredential = credentials; } } private NetworkCredential GetNetworkCredentials(ICredentials credentials, Uri requestUri) { if (_preAuthenticate) { NetworkCredential nc = null; lock (_multiHandle) { nc = GetCredentials(_credentialCache, requestUri); } if (nc != null) { return nc; } } return GetCredentials(credentials, requestUri); } private void SetCookieOption(SafeCurlHandle requestHandle, Uri requestUri) { if (!_useCookie) { return; } else if (_cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } string cookieValues = _cookieContainer.GetCookieHeader(requestUri); if (cookieValues != null) { SetCurlOption(requestHandle, CURLoption.CURLOPT_COOKIE, cookieValues); } } private void AddCredentialToCache(Uri serverUri, ulong authAvail, NetworkCredential nc) { lock (_multiHandle) { for (int i=0; i < AuthSchemePriorityOrder.Length; i++) { if ((authAvail & AuthSchemePriorityOrder[i]) != 0 ) { _credentialCache.Add(serverUri, AuthenticationSchemes[i], nc); } } } } private static NetworkCredential GetCredentials(ICredentials credentials, Uri requestUri) { if (credentials == null) { return null; } foreach (var authScheme in AuthenticationSchemes) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, authScheme); if (networkCredential != null) { return networkCredential; } } return null; } private static void HandleAsyncException(RequestCompletionSource state, Exception ex) { if ((null == ex) && state.CancellationToken.IsCancellationRequested) { state.TrySetCanceled(state.CancellationToken); } if (null == ex) { return; } var oce = (ex as OperationCanceledException); if (oce != null) { // If the exception was due to the cancellation token being canceled, throw cancellation exception. Debug.Assert(state.CancellationToken.IsCancellationRequested); state.TrySetCanceled(oce.CancellationToken); } else if (ex is HttpRequestException) { state.TrySetException(ex); } else { state.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex)); } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static string GetCurlErrorString(int code, bool isMulti = false) { IntPtr ptr = isMulti ? Interop.libcurl.curl_multi_strerror(code) : Interop.libcurl.curl_easy_strerror(code); return Marshal.PtrToStringAnsi(ptr); } private static Exception GetCurlException(int code, bool isMulti = false) { return new Exception(GetCurlErrorString(code, isMulti)); } private void SetCurlCallbacks(SafeCurlHandle requestHandle, HttpRequestMessage request, IntPtr stateHandle) { SetCurlOption(requestHandle, CURLoption.CURLOPT_HEADERDATA, stateHandle); SetCurlOption(requestHandle, CURLoption.CURLOPT_HEADERFUNCTION, s_receiveHeadersCallback); if (request.Method != HttpMethod.Head) { SetCurlOption(requestHandle, CURLoption.CURLOPT_WRITEDATA, stateHandle); unsafe { SetCurlOption(requestHandle, CURLoption.CURLOPT_WRITEFUNCTION, s_receiveBodyCallback); } } if (request.Content != null) { SetCurlOption(requestHandle, CURLoption.CURLOPT_READDATA, stateHandle); SetCurlOption(requestHandle, CURLoption.CURLOPT_READFUNCTION, s_sendCallback); SetCurlOption(requestHandle, CURLoption.CURLOPT_IOCTLDATA, stateHandle); SetCurlOption(requestHandle, CURLoption.CURLOPT_IOCTLFUNCTION, s_sendIoCtlCallback); } } private void SetCurlOption(SafeCurlHandle handle, int option, string value) { int result = Interop.libcurl.curl_easy_setopt(handle, option, value); if (result != CURLcode.CURLE_OK) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } } private void SetCurlOption(SafeCurlHandle handle, int option, long value) { int result = Interop.libcurl.curl_easy_setopt(handle, option, value); if (result != CURLcode.CURLE_OK) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } } private void SetCurlOption(SafeCurlHandle handle, int option, ulong value) { int result = Interop.libcurl.curl_easy_setopt(handle, option, value); if (result != CURLcode.CURLE_OK) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } } private void SetCurlOption(SafeCurlHandle handle, int option, Interop.libcurl.curl_readwrite_callback value) { int result = Interop.libcurl.curl_easy_setopt(handle, option, value); if (result != CURLcode.CURLE_OK) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } } private unsafe void SetCurlOption(SafeCurlHandle handle, int option, Interop.libcurl.curl_unsafe_write_callback value) { int result = Interop.libcurl.curl_easy_setopt(handle, option, value); if (result != CURLcode.CURLE_OK) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } } private void SetCurlOption(SafeCurlHandle handle, int option, Interop.libcurl.curl_ioctl_callback value) { int result = Interop.libcurl.curl_easy_setopt(handle, option, value); if (result != CURLcode.CURLE_OK) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } } private void SetCurlOption(SafeCurlHandle handle, int option, IntPtr value) { int result = Interop.libcurl.curl_easy_setopt(handle, option, value); if (result != CURLcode.CURLE_OK) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } } private void SetCurlMultiOptions() { _multiHandlePtr = GCHandle.Alloc(_multiHandle); IntPtr callbackContext = GCHandle.ToIntPtr(_multiHandlePtr); int result = Interop.libcurl.curl_multi_setopt(_multiHandle, CURLMoption.CURLMOPT_SOCKETFUNCTION, s_socketCallback); if (result == CURLMcode.CURLM_OK) { result = Interop.libcurl.curl_multi_setopt(_multiHandle, CURLMoption.CURLMOPT_TIMERFUNCTION, s_multiTimerCallback); } if (result == CURLMcode.CURLM_OK) { result = Interop.libcurl.curl_multi_setopt(_multiHandle, CURLMoption.CURLMOPT_TIMERDATA, callbackContext); } if (result != CURLMcode.CURLM_OK) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result, true)); } } private SafeCurlSlistHandle SetRequestHeaders(SafeCurlHandle handle, HttpRequestMessage request) { SafeCurlSlistHandle retVal = new SafeCurlSlistHandle(); if (request.Headers == null) { return retVal; } HttpHeaders contentHeaders = null; if (request.Content != null) { SetChunkedModeForSend(request); // TODO: Content-Length header isn't getting correctly placed using ToString() // This is a bug in HttpContentHeaders that needs to be fixed. if (request.Content.Headers.ContentLength.HasValue) { long contentLength = request.Content.Headers.ContentLength.Value; request.Content.Headers.ContentLength = null; request.Content.Headers.ContentLength = contentLength; } contentHeaders = request.Content.Headers; } string[] allHeaders = HeaderUtilities.DumpHeaders(request.Headers, contentHeaders) .Split(s_headerDelimiters, StringSplitOptions.RemoveEmptyEntries); bool gotReference = false; try { retVal.DangerousAddRef(ref gotReference); IntPtr rawHandle = IntPtr.Zero; for (int i = 0; i < allHeaders.Length; i++) { string header = allHeaders[i].Trim(); if (header.Equals("{") || header.Equals("}")) { continue; } rawHandle = Interop.libcurl.curl_slist_append(rawHandle, header); retVal.SetHandle(rawHandle); } // Since libcurl always adds a Transfer-Encoding header, we need to explicitly block // it if caller specifically does not want to set the header if (request.Headers.TransferEncodingChunked.HasValue && !request.Headers.TransferEncodingChunked.Value) { rawHandle = Interop.libcurl.curl_slist_append(rawHandle, NoTransferEncoding); retVal.SetHandle(rawHandle); } if (!retVal.IsInvalid) { SetCurlOption(handle, CURLoption.CURLOPT_HTTPHEADER, rawHandle); } } finally { if (gotReference) { retVal.DangerousRelease(); } } return retVal; } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Tranfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } } private void AddEasyHandle(RequestCompletionSource state) { bool gotReference = false; SafeCurlHandle requestHandle = state.RequestHandle; try { requestHandle.DangerousAddRef(ref gotReference); lock (_multiHandle) { int result = Interop.libcurl.curl_multi_add_handle(_multiHandle, requestHandle); if (result != CURLcode.CURLE_OK) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result, true)); } state.SessionHandle = _multiHandle; _multiHandle.RequestCount = _multiHandle.RequestCount + 1; if (_multiHandle.PollCancelled) { // TODO: Create single polling thread for all HttpClientHandler objects Task.Factory.StartNew(s => PollFunction(((CurlHandler)s)._multiHandle), this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); _multiHandle.PollCancelled = false; } } // Note that we are deliberately not decreasing the ref counts of // the multi and easy handles since that will be done in RemoveEasyHandle // when the request is completed and the handles are used in an // unmanaged context till then // TODO: Investigate if SafeCurlHandle is really useful since we are not // avoiding any leaks due to the ref count increment } catch (Exception) { if (gotReference) { requestHandle.DangerousRelease(); } throw; } } private static void RemoveEasyHandle(SafeCurlMultiHandle multiHandle, GCHandle stateHandle, bool onMultiStack) { RequestCompletionSource state = (RequestCompletionSource)stateHandle.Target; SafeCurlHandle requestHandle = state.RequestHandle; if (onMultiStack) { lock (multiHandle) { Interop.libcurl.curl_multi_remove_handle(multiHandle, requestHandle); multiHandle.RequestCount = multiHandle.RequestCount - 1; } state.SessionHandle = null; requestHandle.DangerousRelease(); } if (!state.RequestHeaderHandle.IsInvalid) { SafeCurlSlistHandle headerHandle = state.RequestHeaderHandle; SafeCurlSlistHandle.DisposeAndClearHandle(ref headerHandle); } SafeCurlHandle.DisposeAndClearHandle(ref requestHandle); stateHandle.Free(); } #endregion private sealed class RequestCompletionSource : TaskCompletionSource<HttpResponseMessage> { private readonly CurlHandler _handler; private readonly CancellationToken _cancellationToken; private readonly HttpRequestMessage _requestMessage; // TODO: The task completion can sometimes happen under a lock. So we need to ensure // that arbitrary blocking code cannot run when the task is marked for completion // So we are using RunContinuationsAsynchronously to force a diff. thread public RequestCompletionSource( CurlHandler handler, CancellationToken cancellationToken, HttpRequestMessage request) : base(TaskCreationOptions.RunContinuationsAsynchronously) { this._handler = handler; this._cancellationToken = cancellationToken; this._requestMessage = request; } public CurlResponseMessage ResponseMessage { get; set; } public SafeCurlMultiHandle SessionHandle { get; set; } public SafeCurlHandle RequestHandle { get; set; } public SafeCurlSlistHandle RequestHeaderHandle { get; set; } public Stream RequestContentStream { get; set; } public byte[] RequestContentBuffer { get; set; } public NetworkCredential NetworkCredential {get; set;} public CurlHandler Handler { get { return _handler; } } public CancellationToken CancellationToken { get { return _cancellationToken; } } public HttpRequestMessage RequestMessage { get { return _requestMessage; } } } private enum ProxyUsePolicy { DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment. UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any. UseCustomProxy = 2 // Use The proxy specified by the user. } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndInt16() { var test = new SimpleBinaryOpTest__AndInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndInt16 testClass) { var result = Sse2.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndInt16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.And( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__AndInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.And( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.And( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.And( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = Sse2.And( Sse2.LoadVector128((Int16*)(pClsVar1)), Sse2.LoadVector128((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndInt16(); var result = Sse2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndInt16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = Sse2.And( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.And( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.And( Sse2.LoadVector128((Int16*)(&test._fld1)), Sse2.LoadVector128((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.And)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// 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.Data.Common; using System.Diagnostics; namespace System.Data.SqlClient.ManualTesting.Tests { internal sealed class SqlVarBinaryTypeInfo : SqlRandomTypeInfo { private const int MaxDefinedSize = 8000; private const string TypePrefix = "varbinary"; private const int DefaultSize = 1; internal SqlVarBinaryTypeInfo() : base(SqlDbType.VarBinary) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return LargeVarDataRowUsage; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { string sizeSuffix; if (!columnInfo.StorageSize.HasValue) { sizeSuffix = DefaultSize.ToString(); } else { int size = columnInfo.StorageSize.Value; if (size > MaxDefinedSize) { sizeSuffix = "max"; } else { Debug.Assert(size > 0, "wrong size"); sizeSuffix = size.ToString(); } } return string.Format("{0}({1})", TypePrefix, sizeSuffix); } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { int size = rand.NextAllocationSizeBytes(1); return new SqlRandomTableColumn(this, options, size); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultSize; return rand.NextByteArray(0, size); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadByteArray(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareByteArray(expected, actual, allowIncomplete: false); } } internal sealed class SqlVarCharTypeInfo : SqlRandomTypeInfo { private const int MaxDefinedCharSize = 8000; private const string TypePrefix = "varchar"; private const int DefaultCharSize = 1; internal SqlVarCharTypeInfo() : base(SqlDbType.VarChar) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return LargeVarDataRowUsage; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { string sizeSuffix; if (!columnInfo.StorageSize.HasValue) { sizeSuffix = DefaultCharSize.ToString(); } else { int size = columnInfo.StorageSize.Value; if (size > MaxDefinedCharSize) { sizeSuffix = "max"; } else { Debug.Assert(size > 0, "wrong size"); sizeSuffix = size.ToString(); } } return string.Format("{0}({1})", TypePrefix, sizeSuffix); } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { int size = rand.NextAllocationSizeBytes(1); return new SqlRandomTableColumn(this, options, size); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultCharSize; return rand.NextAnsiArray(0, size); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadCharData(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareCharArray(expected, actual, allowIncomplete: false); } } internal sealed class SqlNVarCharTypeInfo : SqlRandomTypeInfo { private const int MaxDefinedCharSize = 4000; private const string TypePrefix = "nvarchar"; private const int DefaultCharSize = 1; internal SqlNVarCharTypeInfo() : base(SqlDbType.NVarChar) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return LargeVarDataRowUsage; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { string sizeSuffix; if (!columnInfo.StorageSize.HasValue) { sizeSuffix = DefaultCharSize.ToString(); } else { int charSize = columnInfo.StorageSize.Value / 2; if (charSize > MaxDefinedCharSize) { sizeSuffix = "max"; } else { Debug.Assert(charSize > 0, "wrong size"); sizeSuffix = charSize.ToString(); } } return string.Format("{0}({1})", TypePrefix, sizeSuffix); } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { int size = rand.NextAllocationSizeBytes(2); size = size & 0xFFFE; // clean last bit to make it even return new SqlRandomTableColumn(this, options, storageSize: size); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { int storageSize = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultCharSize * 2; return rand.NextUcs2Array(0, storageSize); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadCharData(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareCharArray(expected, actual, allowIncomplete: false); } } internal sealed class SqlBigIntTypeInfo : SqlRandomTypeInfo { private const string TypeTSqlName = "bigint"; private const int StorageSize = 8; public SqlBigIntTypeInfo() : base(SqlDbType.BigInt) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return StorageSize; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TypeTSqlName; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextBigInt(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(Int64), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetInt64(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<Int64>(expected, actual); } } internal sealed class SqlIntTypeInfo : SqlRandomTypeInfo { private const string TypeTSqlName = "int"; private const int StorageSize = 4; public SqlIntTypeInfo() : base(SqlDbType.Int) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return StorageSize; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TypeTSqlName; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextIntInclusive(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(int), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetInt32(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<Int32>(expected, actual); } } internal sealed class SqlSmallIntTypeInfo : SqlRandomTypeInfo { private const string TypeTSqlName = "smallint"; private const int StorageSize = 2; public SqlSmallIntTypeInfo() : base(SqlDbType.SmallInt) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return StorageSize; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TypeTSqlName; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextSmallInt(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(short), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetInt16(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<Int16>(expected, actual); } } internal sealed class SqlTinyIntTypeInfo : SqlRandomTypeInfo { private const string TypeTSqlName = "tinyint"; private const int StorageSize = 1; public SqlTinyIntTypeInfo() : base(SqlDbType.TinyInt) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return StorageSize; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TypeTSqlName; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextTinyInt(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(byte), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetByte(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<byte>(expected, actual); } } internal sealed class SqlTextTypeInfo : SqlRandomTypeInfo { private const string TypeTSqlName = "text"; public SqlTextTypeInfo() : base(SqlDbType.Text) { } public override bool CanBeSparseColumn { get { return false; } } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return LargeDataRowUsage; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TypeTSqlName; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextAnsiArray(0, columnInfo.StorageSize); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadCharData(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareCharArray(expected, actual, allowIncomplete: false); } } internal sealed class SqlNTextTypeInfo : SqlRandomTypeInfo { private const string TypeTSqlName = "ntext"; public SqlNTextTypeInfo() : base(SqlDbType.NText) { } public override bool CanBeSparseColumn { get { return false; } } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return LargeDataRowUsage; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TypeTSqlName; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextUcs2Array(0, columnInfo.StorageSize); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadCharData(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareCharArray(expected, actual, allowIncomplete: false); } } internal sealed class SqlImageTypeInfo : SqlRandomTypeInfo { private const string TypeTSqlName = "image"; public SqlImageTypeInfo() : base(SqlDbType.Image) { } public override bool CanBeSparseColumn { get { return false; } } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return LargeDataRowUsage; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TypeTSqlName; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextByteArray(0, columnInfo.StorageSize); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadByteArray(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareByteArray(expected, actual, allowIncomplete: false); } } internal sealed class SqlBinaryTypeInfo : SqlRandomTypeInfo { private const int MaxStorageSize = 8000; private const string TypePrefix = "binary"; private const int DefaultSize = 1; public SqlBinaryTypeInfo() : base(SqlDbType.Binary) { } private int GetSize(SqlRandomTableColumn columnInfo) { ValidateColumnInfo(columnInfo); int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultSize; if (size < 1 || size > MaxStorageSize) throw new NotSupportedException("wrong size"); return size; } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return GetSize(columnInfo); } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return string.Format("{0}({1})", TypePrefix, GetSize(columnInfo)); } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { int size = rand.NextAllocationSizeBytes(1, MaxStorageSize); return new SqlRandomTableColumn(this, options, size); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultSize; return rand.NextByteArray(0, size); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadByteArray(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareByteArray(expected, actual, allowIncomplete: true); } } internal sealed class SqlCharTypeInfo : SqlRandomTypeInfo { private const int MaxCharSize = 8000; private const string TypePrefix = "char"; private const int DefaultCharSize = 1; public SqlCharTypeInfo() : base(SqlDbType.Char) { } private int GetCharSize(SqlRandomTableColumn columnInfo) { ValidateColumnInfo(columnInfo); int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultCharSize; if (size < 1 || size > MaxCharSize) throw new NotSupportedException("wrong size"); return size; } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return GetCharSize(columnInfo); } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return string.Format("{0}({1})", TypePrefix, GetCharSize(columnInfo)); } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { int size = rand.NextAllocationSizeBytes(1, MaxCharSize); return new SqlRandomTableColumn(this, options, size); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultCharSize; return rand.NextAnsiArray(0, size); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadCharData(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareCharArray(expected, actual, allowIncomplete: true); } } internal sealed class SqlNCharTypeInfo : SqlRandomTypeInfo { private const int MaxCharSize = 4000; private const string TypePrefix = "nchar"; private const int DefaultCharSize = 1; public SqlNCharTypeInfo() : base(SqlDbType.NChar) { } private int GetCharSize(SqlRandomTableColumn columnInfo) { ValidateColumnInfo(columnInfo); int charSize = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value / 2 : DefaultCharSize; if (charSize < 1 || charSize > MaxCharSize) throw new NotSupportedException("wrong size"); return charSize; } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return GetCharSize(columnInfo) * 2; // nchar is not stored in row } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return string.Format("{0}({1})", TypePrefix, GetCharSize(columnInfo)); } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { int size = rand.NextAllocationSizeBytes(2, MaxCharSize * 2); size = size & 0xFFFE; // clean last bit to make it even return new SqlRandomTableColumn(this, options, size); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { int storageSize = GetCharSize(columnInfo) * 2; return rand.NextUcs2Array(0, storageSize); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadCharData(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareCharArray(expected, actual, allowIncomplete: true); } } internal sealed class SqlBitTypeInfo : SqlRandomTypeInfo { public SqlBitTypeInfo() : base(SqlDbType.Bit) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return 0.125; // 8 bits => 1 byte } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "bit"; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextBit(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(Boolean), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetBoolean(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<Boolean>(expected, actual); } } internal sealed class SqlDecimalTypeInfo : SqlRandomTypeInfo { private int _defaultPrecision = 18; public SqlDecimalTypeInfo() : base(SqlDbType.Decimal) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { int precision = columnInfo.Precision.HasValue ? columnInfo.Precision.Value : _defaultPrecision; if (precision < 1 || precision > 38) { throw new ArgumentOutOfRangeException("wrong precision"); } if (precision < 10) { return 5; } else if (precision < 20) { return 9; } else if (precision < 28) { return 13; } else { return 17; } } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "decimal"; } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { return CreateDefaultColumn(options); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return (decimal)Math.Round(rand.NextDouble()); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(decimal), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetDecimal(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<decimal>(expected, actual); } } internal sealed class SqlMoneyTypeInfo : SqlRandomTypeInfo { private const string TypeTSqlName = "money"; private const int StorageSize = 8; public SqlMoneyTypeInfo() : base(SqlDbType.Money) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return StorageSize; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TypeTSqlName; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextMoney(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(decimal), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetDecimal(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<decimal>(expected, actual); } } internal sealed class SqlSmallMoneyTypeInfo : SqlRandomTypeInfo { private const string TypeTSqlName = "smallmoney"; private const int StorageSize = 4; public SqlSmallMoneyTypeInfo() : base(SqlDbType.SmallMoney) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return StorageSize; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TypeTSqlName; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextSmallMoney(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(decimal), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetDecimal(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<decimal>(expected, actual); } } internal sealed class SqRealTypeInfo : SqlRandomTypeInfo { // simplify to double-precision or real only private const int RealPrecision = 7; private const int RealMantissaBits = 24; private const string TSqlTypeName = "real"; public SqRealTypeInfo() : base(SqlDbType.Real) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return 4; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return TSqlTypeName; } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { return CreateDefaultColumn(options); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextReal(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(float), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetFloat(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<Single>(expected, actual); } } internal sealed class SqFloatTypeInfo : SqlRandomTypeInfo { // simplify to double-precision or real only private const int MaxFloatMantissaBits = 53; private const int MaxFloatPrecision = 15; private const int RealPrecision = 7; private const int RealMantissaBits = 24; private const string TypePrefix = "float"; public SqFloatTypeInfo() : base(SqlDbType.Float) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { // float if (!columnInfo.Precision.HasValue) { return 8; } else { int precision = columnInfo.Precision.Value; if (precision != RealPrecision && precision != MaxFloatPrecision) throw new ArgumentException("wrong precision"); return (precision <= RealPrecision) ? 4 : 8; } } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { int precision = columnInfo.Precision.HasValue ? columnInfo.Precision.Value : MaxFloatPrecision; if (precision != RealPrecision && precision != MaxFloatPrecision) throw new ArgumentException("wrong precision"); int mantissaBits = (precision <= RealPrecision) ? 24 : 53; return string.Format("{0}({1})", TypePrefix, mantissaBits); } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { return CreateDefaultColumn(options); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { int precision = columnInfo.Precision.HasValue ? columnInfo.Precision.Value : MaxFloatPrecision; if (precision <= RealPrecision) return rand.NextDouble(float.MinValue, float.MaxValue, precision); else return rand.NextDouble(double.MinValue, double.MaxValue, precision); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(double), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetDouble(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<Double>(expected, actual); } } internal sealed class SqlRowVersionTypeInfo : SqlRandomTypeInfo { public SqlRowVersionTypeInfo() : base(SqlDbType.Timestamp) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return 8; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "rowversion"; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextRowVersion(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadByteArray(reader, ordinal, asType); } public override bool CanBeSparseColumn { get { return false; } } public override bool CanCompareValues(SqlRandomTableColumn columnInfo) { // completely ignore TIMESTAMP value comparison return false; } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { throw new InvalidOperationException("should not be used for timestamp - use CanCompareValues before calling this method"); } } internal sealed class SqlUniqueIdentifierTypeInfo : SqlRandomTypeInfo { public SqlUniqueIdentifierTypeInfo() : base(SqlDbType.UniqueIdentifier) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return 16; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "uniqueidentifier"; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { // this method does not use Guid.NewGuid since it is not based on the given rand object return rand.NextUniqueIdentifier(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(Guid), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return reader.GetGuid(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<Guid>(expected, actual); } } internal sealed class SqlDateTypeInfo : SqlRandomTypeInfo { public SqlDateTypeInfo() : base(SqlDbType.Date) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return 3; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "date"; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextDate(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadDateTime(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<DateTime>(expected, actual); } } internal sealed class SqlDateTimeTypeInfo : SqlRandomTypeInfo { public SqlDateTimeTypeInfo() : base(SqlDbType.DateTime) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return 8; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "datetime"; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextDateTime(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadDateTime(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<DateTime>(expected, actual); } } internal sealed class SqlDateTime2TypeInfo : SqlRandomTypeInfo { private const int DefaultPrecision = 7; public SqlDateTime2TypeInfo() : base(SqlDbType.DateTime2) { } private static int GetPrecision(SqlRandomTableColumn columnInfo) { int precision; if (columnInfo.Precision.HasValue) { precision = columnInfo.Precision.Value; if (precision < 0 || precision > 7) throw new ArgumentOutOfRangeException("columnInfo.Precision"); } else { precision = DefaultPrecision; } return precision; } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { int precision = GetPrecision(columnInfo); if (precision < 3) return 6; else if (precision < 5) return 7; else return 8; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { int precision = GetPrecision(columnInfo); if (precision == DefaultPrecision) return "datetime2"; else { Debug.Assert(precision > 0, "wrong precision"); return string.Format("datetime2({0})", precision); } } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { return CreateDefaultColumn(options); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextDateTime2(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadDateTime(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<DateTime>(expected, actual); } } internal sealed class SqlDateTimeOffsetTypeInfo : SqlRandomTypeInfo { public SqlDateTimeOffsetTypeInfo() : base(SqlDbType.DateTimeOffset) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return 10; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "datetimeoffset"; } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { return CreateDefaultColumn(options); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextDateTimeOffset(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(DateTimeOffset), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return ((System.Data.SqlClient.SqlDataReader)reader).GetDateTimeOffset(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<DateTimeOffset>(expected, actual); } } internal sealed class SqlSmallDateTimeTypeInfo : SqlRandomTypeInfo { public SqlSmallDateTimeTypeInfo() : base(SqlDbType.SmallDateTime) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return 4; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "smalldatetime"; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextSmallDateTime(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadDateTime(reader, ordinal, asType); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<DateTime>(expected, actual); } } internal sealed class SqlTimeTypeInfo : SqlRandomTypeInfo { public SqlTimeTypeInfo() : base(SqlDbType.Time) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return 5; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "time "; } public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options) { return CreateDefaultColumn(options); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { return rand.NextTime(); } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { ValidateReadType(typeof(TimeSpan), asType); if (reader.IsDBNull(ordinal)) return DBNull.Value; return ((System.Data.SqlClient.SqlDataReader)reader).GetTimeSpan(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { return CompareValues<TimeSpan>(expected, actual); } } internal sealed class SqlVariantTypeInfo : SqlRandomTypeInfo { private static readonly SqlRandomTypeInfo[] s_variantSubTypes = { // var types new SqlVarBinaryTypeInfo(), new SqlVarCharTypeInfo(), new SqlNVarCharTypeInfo(), // integer data types new SqlBigIntTypeInfo(), new SqlIntTypeInfo(), new SqlSmallIntTypeInfo(), new SqlTinyIntTypeInfo(), // fixed length blobs new SqlCharTypeInfo(), new SqlNCharTypeInfo(), new SqlBinaryTypeInfo(), // large blobs new SqlTextTypeInfo(), new SqlNTextTypeInfo(), new SqlImageTypeInfo(), // bit new SqlBitTypeInfo(), // decimal new SqlDecimalTypeInfo(), // money types new SqlMoneyTypeInfo(), new SqlSmallMoneyTypeInfo(), // float types new SqRealTypeInfo(), new SqFloatTypeInfo(), // unique identifier (== guid) new SqlUniqueIdentifierTypeInfo(), // date/time types new SqlDateTimeTypeInfo(), new SqlSmallDateTimeTypeInfo(), }; public SqlVariantTypeInfo() : base(SqlDbType.Variant) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return VariantRowUsage; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "sql_variant"; } private static bool IsUnicodeType(SqlDbType t) { return (t == SqlDbType.NChar || t == SqlDbType.NText || t == SqlDbType.NVarChar); } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { SqlRandomTypeInfo subType = s_variantSubTypes[rand.NextIntInclusive(0, maxValueInclusive: s_variantSubTypes.Length - 1)]; object val = subType.CreateRandomValue(rand, new SqlRandomTableColumn(subType, SqlRandomColumnOptions.None, 8000)); char[] cval = val as char[]; if (cval != null) { int maxLength = IsUnicodeType(subType.Type) ? 4000 : 8000; Debug.Assert(cval.Length < maxLength, "char array length cannot be greater than " + maxLength); // cannot insert char[] into variant val = new string((char[])val); } else { byte[] bval = val as byte[]; if (bval != null) Debug.Assert(bval.Length < 8000, "byte array length cannot be greater than 8000"); } return val; } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return reader.GetValue(ordinal); } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { bool bothDbNull; if (!CompareDbNullAndType(null, expected, actual, out bothDbNull) || bothDbNull) return bothDbNull; Type expectedType = expected.GetType(); if (expectedType == typeof(byte[])) { return CompareByteArray(expected, actual, allowIncomplete: false); } else if (expectedType == typeof(char[])) { return CompareCharArray(expected, actual, allowIncomplete: false); } else if (expectedType == typeof(string)) { // special handling for strings, only in variant if (actual.GetType() == typeof(string)) return string.Equals((string)expected, (string)actual, StringComparison.Ordinal); else return false; } else { return expected.Equals(actual); } } } internal sealed class SqlXmlTypeInfo : SqlRandomTypeInfo { public SqlXmlTypeInfo() : base(SqlDbType.Xml) { } protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo) { return XmlRowUsage; } protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo) { return "xml"; } protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo) { if ((columnInfo.Options & SqlRandomColumnOptions.ColumnSet) != 0) { // use the sparse columns themselves to insert values // testing column set column correctness is not a goal for the stress test throw new NotImplementedException("should not use this method for column set columns"); } int charSize = rand.NextAllocationSizeBytes(0, columnInfo.StorageSize); const string prefix = "<x>"; const string suffix = "</x>"; if (charSize > (prefix.Length + suffix.Length)) { string randValue = new string('a', charSize - (prefix.Length + suffix.Length)); return string.Format("<x>{0}</x>", randValue).ToCharArray(); } else { // for accurate comparison, use the short form return "<x />".ToCharArray(); } } protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType) { return ReadCharData(reader, ordinal, asType); } public override bool CanCompareValues(SqlRandomTableColumn columnInfo) { return (columnInfo.Options & SqlRandomColumnOptions.ColumnSet) == 0; } protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual) { if ((columnInfo.Options & SqlRandomColumnOptions.ColumnSet) != 0) { throw new InvalidOperationException("should not be used for ColumnSet columns - use CanCompareValues before calling this method"); } return CompareCharArray(expected, actual, allowIncomplete: false); } } }
// Authors: Robert Scheller, Melissa Lucash using Landis.Utilities; using Landis.Core; using Landis.SpatialModeling; using System.Collections.Generic; using Landis.Library.LeafBiomassCohorts; using System; namespace Landis.Extension.Succession.NECN { /// <summary> /// Calculations for an individual cohort's biomass. /// </summary> public class CohortBiomass : Landis.Library.LeafBiomassCohorts.ICalculator { /// <summary> /// The single instance of the biomass calculations that is used by /// the plug-in. /// </summary> public static CohortBiomass Calculator; // Ecoregion where the cohort's site is located private IEcoregion ecoregion; private double defoliation; private double defoliatedLeafBiomass; //--------------------------------------------------------------------- public CohortBiomass() { } //--------------------------------------------------------------------- /// <summary> /// Computes the change in a cohort's biomass due to Annual Net Primary /// Productivity (ANPP), age-related mortality (M_AGE), and development- /// related mortality (M_BIO). /// </summary> public float[] ComputeChange(ICohort cohort, ActiveSite site) { ecoregion = PlugIn.ModelCore.Ecoregion[site]; // First call to the Calibrate Log: if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode) { CalibrateLog.year = PlugIn.ModelCore.CurrentTime; CalibrateLog.month = Main.Month + 1; CalibrateLog.climateRegionIndex = ecoregion.Index; CalibrateLog.speciesName = cohort.Species.Name; CalibrateLog.cohortAge = cohort.Age; CalibrateLog.cohortWoodB = cohort.WoodBiomass; CalibrateLog.cohortLeafB = cohort.LeafBiomass; //Outputs.CalibrateLog.Write("{0},{1},{2},{3},{4},{5:0.0},{6:0.0},", PlugIn.ModelCore.CurrentTime, Main.Month + 1, ecoregion.Index, cohort.Species.Name, cohort.Age, cohort.WoodBiomass, cohort.LeafBiomass); } double siteBiomass = Main.ComputeLivingBiomass(SiteVars.Cohorts[site]); if(siteBiomass < 0) throw new ApplicationException("Error: Site biomass < 0"); // ****** Mortality ******* // Age-related mortality includes woody and standing leaf biomass. double[] mortalityAge = ComputeAgeMortality(cohort, site); // ****** Growth ******* double[] actualANPP = ComputeActualANPP(cohort, site, siteBiomass, mortalityAge); // Growth-related mortality double[] mortalityGrowth = ComputeGrowthMortality(cohort, site, siteBiomass, actualANPP); double[] totalMortality = new double[2]{Math.Min(cohort.WoodBiomass, mortalityAge[0] + mortalityGrowth[0]), Math.Min(cohort.LeafBiomass, mortalityAge[1] + mortalityGrowth[1])}; double nonDisturbanceLeafFall = totalMortality[1]; double scorch = 0.0; defoliatedLeafBiomass = 0.0; if (Main.Month == 6) //July = 6 { if (SiteVars.FireSeverity != null && SiteVars.FireSeverity[site] > 0) scorch = FireEffects.CrownScorching(cohort, SiteVars.FireSeverity[site]); if (scorch > 0.0) // NEED TO DOUBLE CHECK WHAT CROWN SCORCHING RETURNS totalMortality[1] = Math.Min(cohort.LeafBiomass, scorch + totalMortality[1]); // Defoliation (index) ranges from 1.0 (total) to none (0.0). if (PlugIn.ModelCore.CurrentTime > 0) //Skip this during initialization { //defoliation = Landis.Library.LeafBiomassCohorts.CohortDefoliation.Compute(cohort, site, (int)siteBiomass); int cohortBiomass = (int)(cohort.LeafBiomass + cohort.WoodBiomass); defoliation = Landis.Library.Biomass.CohortDefoliation.Compute(site, cohort.Species, cohortBiomass, (int)siteBiomass); } if (defoliation > 1.0) defoliation = 1.0; if (defoliation > 0.0) { defoliatedLeafBiomass = (cohort.LeafBiomass) * defoliation; if (totalMortality[1] + defoliatedLeafBiomass - cohort.LeafBiomass > 0.001) defoliatedLeafBiomass = cohort.LeafBiomass - totalMortality[1]; //PlugIn.ModelCore.UI.WriteLine("Defoliation.Month={0:0.0}, LeafBiomass={1:0.00}, DefoliatedLeafBiomass={2:0.00}, TotalLeafMort={2:0.00}", Main.Month, cohort.LeafBiomass, defoliatedLeafBiomass , mortalityAge[1]); ForestFloor.AddFrassLitter(defoliatedLeafBiomass, cohort.Species, site); } } else { defoliation = 0.0; defoliatedLeafBiomass = 0.0; } if (totalMortality[0] <= 0.0 || cohort.WoodBiomass <= 0.0) totalMortality[0] = 0.0; if (totalMortality[1] <= 0.0 || cohort.LeafBiomass <= 0.0) totalMortality[1] = 0.0; if ((totalMortality[0]) > cohort.WoodBiomass) { PlugIn.ModelCore.UI.WriteLine("Warning: WOOD Mortality exceeds cohort wood biomass. M={0:0.0}, B={1:0.0}", (totalMortality[0]), cohort.WoodBiomass); PlugIn.ModelCore.UI.WriteLine("Warning: If M>B, then list mortality. Mage={0:0.0}, Mgrow={1:0.0},", mortalityAge[0], mortalityGrowth[0]); throw new ApplicationException("Error: WOOD Mortality exceeds cohort biomass"); } if ((totalMortality[1] + defoliatedLeafBiomass - cohort.LeafBiomass) > 0.01) { PlugIn.ModelCore.UI.WriteLine("Warning: LEAF Mortality exceeds cohort biomass. Mortality={0:0.000}, Leafbiomass={1:0.000}", (totalMortality[1] + defoliatedLeafBiomass), cohort.LeafBiomass); PlugIn.ModelCore.UI.WriteLine("Warning: If M>B, then list mortality. Mage={0:0.00}, Mgrow={1:0.00}, Mdefo={2:0.000},", mortalityAge[1], mortalityGrowth[1], defoliatedLeafBiomass); throw new ApplicationException("Error: LEAF Mortality exceeds cohort biomass"); } float deltaWood = (float)(actualANPP[0] - totalMortality[0]); float deltaLeaf = (float)(actualANPP[1] - totalMortality[1] - defoliatedLeafBiomass); float[] deltas = new float[2] { deltaWood, deltaLeaf }; //if((totalMortality[1] + defoliatedLeafBiomass) > cohort.LeafBiomass) // PlugIn.ModelCore.UI.WriteLine("Warning: Leaf Mortality exceeds cohort leaf biomass. M={0:0.0}, B={1:0.0}, DefoLeafBiomass={2:0.0}, defoliationIndex={3:0.0}", totalMortality[1], cohort.LeafBiomass, defoliatedLeafBiomass, defoliation); UpdateDeadBiomass(cohort, site, totalMortality); CalculateNPPcarbon(site, cohort, actualANPP); AvailableN.AdjustAvailableN(cohort, site, actualANPP); if (OtherData.CalibrateMode && PlugIn.ModelCore.CurrentTime > 0) { CalibrateLog.deltaLeaf = deltaLeaf; CalibrateLog.deltaWood = deltaWood; CalibrateLog.WriteLogFile(); //Outputs.CalibrateLog.WriteLine("{0:0.00},{1:0.00},{2:0.00},{3:0.00},", deltaWood, deltaLeaf, totalMortality[0], totalMortality[1]); } return deltas; } //--------------------------------------------------------------------- private double[] ComputeActualANPP(ICohort cohort, ActiveSite site, double siteBiomass, double[] mortalityAge) { double leafFractionNPP = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].FractionANPPtoLeaf; double maxBiomass = SpeciesData.Max_Biomass[cohort.Species]; double sitelai = SiteVars.LAI[site]; double maxNPP = SpeciesData.Max_ANPP[cohort.Species]; double limitT = calculateTemp_Limit(site, cohort.Species); double limitH20 = calculateWater_Limit(site, ecoregion, cohort.Species); double limitLAI = calculateLAI_Limit(cohort, site); // RMS 03/2016: Testing alternative more similar to how Biomass Succession operates: REMOVE FOR NEXT RELEASE //double limitCapacity = 1.0 - Math.Min(1.0, Math.Exp(siteBiomass / maxBiomass * 5.0) / Math.Exp(5.0)); double competition_limit = calculate_LAI_Competition(cohort, site); double potentialNPP = maxNPP * limitLAI * limitH20 * limitT * competition_limit; double limitN = calculateN_Limit(site, cohort, potentialNPP, leafFractionNPP); potentialNPP *= limitN; //if (Double.IsNaN(limitT) || Double.IsNaN(limitH20) || Double.IsNaN(limitLAI) || Double.IsNaN(limitCapacity) || Double.IsNaN(limitN)) //{ // PlugIn.ModelCore.UI.WriteLine(" A limit = NaN! Will set to zero."); // PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. GROWTH LIMITS: LAI={2:0.00}, H20={3:0.00}, N={4:0.00}, T={5:0.00}, Capacity={6:0.0}", PlugIn.ModelCore.CurrentTime, month + 1, limitLAI, limitH20, limitN, limitT, limitCapacity); // PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. Other Information: MaxB={2}, Bsite={3}, Bcohort={4:0.0}, SoilT={5:0.0}.", PlugIn.ModelCore.CurrentTime, month + 1, maxBiomass, (int)siteBiomass, (cohort.WoodBiomass + cohort.LeafBiomass), SiteVars.SoilTemperature[site]); //} // Age mortality is discounted from ANPP to prevent the over- // estimation of growth. ANPP cannot be negative. double actualANPP = Math.Max(0.0, potentialNPP - mortalityAge[0] - mortalityAge[1]); // Growth can be reduced by another extension via this method. // To date, no extension has been written to utilize this hook. double growthReduction = CohortGrowthReduction.Compute(cohort, site); if (growthReduction > 0.0) { actualANPP *= (1.0 - growthReduction); } double leafNPP = actualANPP * leafFractionNPP; double woodNPP = actualANPP * (1.0 - leafFractionNPP); if (Double.IsNaN(leafNPP) || Double.IsNaN(woodNPP)) { PlugIn.ModelCore.UI.WriteLine(" EITHER WOOD or LEAF NPP = NaN! Will set to zero."); PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. Other Information: MaxB={2}, Bsite={3}, Bcohort={4:0.0}, SoilT={5:0.0}.", PlugIn.ModelCore.CurrentTime, Main.Month + 1, maxBiomass, (int)siteBiomass, (cohort.WoodBiomass + cohort.LeafBiomass), SiteVars.SoilTemperature[site]); PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. WoodNPP={2:0.00}, LeafNPP={3:0.00}.", PlugIn.ModelCore.CurrentTime, Main.Month + 1, woodNPP, leafNPP); if (Double.IsNaN(leafNPP)) leafNPP = 0.0; if (Double.IsNaN(woodNPP)) woodNPP = 0.0; } if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode) { CalibrateLog.limitLAI = limitLAI; CalibrateLog.limitH20 = limitH20; CalibrateLog.limitT = limitT; CalibrateLog.limitN = limitN; CalibrateLog.limitLAIcompetition = competition_limit; // Chihiro, 2021.03.26: added CalibrateLog.maxNPP = maxNPP; CalibrateLog.maxB = maxBiomass; CalibrateLog.siteB = siteBiomass; CalibrateLog.cohortB = (cohort.WoodBiomass + cohort.LeafBiomass); CalibrateLog.soilTemp = SiteVars.SoilTemperature[site]; CalibrateLog.actualWoodNPP = woodNPP; CalibrateLog.actualLeafNPP = leafNPP; //Outputs.CalibrateLog.Write("{0:0.00},{1:0.00},{2:0.00},{3:0.00},", limitLAI, limitH20, limitT, limitN); //Outputs.CalibrateLog.Write("{0},{1},{2},{3:0.0},{4:0.0},", maxNPP, maxBiomass, (int)siteBiomass, (cohort.WoodBiomass + cohort.LeafBiomass), SiteVars.SoilTemperature[site]); //Outputs.CalibrateLog.Write("{0:0.00},{1:0.00},", woodNPP, leafNPP); } return new double[2]{woodNPP, leafNPP}; } //--------------------------------------------------------------------- /// <summary> /// Computes M_AGE_ij: the mortality caused by the aging of the cohort. /// See equation 6 in Scheller and Mladenoff, 2004. /// </summary> private double[] ComputeAgeMortality(ICohort cohort, ActiveSite site) { double monthAdjust = 1.0 / 12.0; double totalBiomass = (double) (cohort.WoodBiomass + cohort.LeafBiomass); double max_age = (double) cohort.Species.Longevity; double d = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].LongevityMortalityShape; double M_AGE_wood = cohort.WoodBiomass * monthAdjust * Math.Exp((double) cohort.Age / max_age * d) / Math.Exp(d); double M_AGE_leaf = cohort.LeafBiomass * monthAdjust * Math.Exp((double) cohort.Age / max_age * d) / Math.Exp(d); //if (PlugIn.ModelCore.CurrentTime <= 0 && SpinupMortalityFraction > 0.0) //{ // M_AGE_wood += cohort.Biomass * SpinupMortalityFraction; // M_AGE_leaf += cohort.Biomass * SpinupMortalityFraction; //} M_AGE_wood = Math.Min(M_AGE_wood, cohort.WoodBiomass); M_AGE_leaf = Math.Min(M_AGE_leaf, cohort.LeafBiomass); double[] M_AGE = new double[2]{M_AGE_wood, M_AGE_leaf}; SiteVars.WoodMortality[site] += (M_AGE_wood); if(M_AGE_wood < 0.0 || M_AGE_leaf < 0.0) { PlugIn.ModelCore.UI.WriteLine("Mwood={0}, Mleaf={1}.", M_AGE_wood, M_AGE_leaf); throw new ApplicationException("Error: Woody or Leaf Age Mortality is < 0"); } if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode) { CalibrateLog.mortalityAGEleaf = M_AGE_leaf; CalibrateLog.mortalityAGEwood = M_AGE_wood; //Outputs.CalibrateLog.Write("{0:0.00},{1:0.00},", M_AGE_wood, M_AGE_leaf); } return M_AGE; } //--------------------------------------------------------------------- /// <summary> /// Monthly mortality as a function of standing leaf and wood biomass. /// </summary> private double[] ComputeGrowthMortality(ICohort cohort, ActiveSite site, double siteBiomass, double[] AGNPP) { double maxBiomass = SpeciesData.Max_Biomass[cohort.Species]; double NPPwood = (double)AGNPP[0]; double M_wood_fixed = cohort.WoodBiomass * FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].MonthlyWoodMortality; double M_leaf = 0.0; double relativeBiomass = siteBiomass / maxBiomass; double M_constant = 5.0; //This constant controls the rate of change of mortality with NPP //Functon which calculates an adjustment factor for mortality that ranges from 0 to 1 and exponentially increases with relative biomass. double M_wood_NPP = Math.Max(0.0, (Math.Exp(M_constant * relativeBiomass) - 1.0) / (Math.Exp(M_constant) - 1.0)); M_wood_NPP = Math.Min(M_wood_NPP, 1.0); //PlugIn.ModelCore.UI.WriteLine("relativeBiomass={0}, siteBiomass={1}.", relativeBiomass, siteBiomass); //This function calculates mortality as a function of NPP double M_wood = (NPPwood * M_wood_NPP) + M_wood_fixed; //PlugIn.ModelCore.UI.WriteLine("Mwood={0}, M_wood_relative={1}, NPPwood={2}, Spp={3}, Age={4}.", M_wood, M_wood_NPP, NPPwood, cohort.Species.Name, cohort.Age); // Leaves and Needles dropped. if (SpeciesData.LeafLongevity[cohort.Species] > 1.0) { M_leaf = cohort.LeafBiomass / (double) SpeciesData.LeafLongevity[cohort.Species] / 12.0; //Needle deposit spread across the year. } else { if(Main.Month +1 == FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].FoliageDropMonth) { M_leaf = cohort.LeafBiomass / 2.0; //spread across 2 months } if (Main.Month +2 > FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].FoliageDropMonth) { M_leaf = cohort.LeafBiomass; //drop the remainder } } double[] M_BIO = new double[2]{M_wood, M_leaf}; if(M_wood < 0.0 || M_leaf < 0.0) { PlugIn.ModelCore.UI.WriteLine("Mwood={0}, Mleaf={1}.", M_wood, M_leaf); throw new ApplicationException("Error: Wood or Leaf Growth Mortality is < 0"); } if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode) { CalibrateLog.mortalityBIOwood = M_wood; CalibrateLog.mortalityBIOleaf = M_leaf; //Outputs.CalibrateLog.Write("{0:0.00},{1:0.00},", M_wood, M_leaf); } SiteVars.WoodMortality[site] += (M_wood); return M_BIO; } //--------------------------------------------------------------------- private void UpdateDeadBiomass(ICohort cohort, ActiveSite site, double[] totalMortality) { double mortality_wood = (double) totalMortality[0]; double mortality_nonwood = (double)totalMortality[1]; // Add mortality to dead biomass pools. // Coarse root mortality is assumed proportional to aboveground woody mortality // mass is assumed 25% of aboveground wood (White et al. 2000, Niklas & Enquist 2002) if(mortality_wood > 0.0) { ForestFloor.AddWoodLitter(mortality_wood, cohort.Species, site); Roots.AddCoarseRootLitter(mortality_wood, cohort, cohort.Species, site); } if(mortality_nonwood > 0.0) { AvailableN.AddResorbedN(cohort, totalMortality[1], site); //ignoring input from scorching, which is rare, but not resorbed. ForestFloor.AddResorbedFoliageLitter(mortality_nonwood, cohort.Species, site); Roots.AddFineRootLitter(mortality_nonwood, cohort, cohort.Species, site); } return; } //--------------------------------------------------------------------- /// <summary> /// Computes the initial biomass for a cohort at a site. /// </summary> public static float[] InitialBiomass(ISpecies species, ISiteCohorts siteCohorts, ActiveSite site) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site]; double leafFrac = FunctionalType.Table[SpeciesData.FuncType[species]].FractionANPPtoLeaf; double B_ACT = SiteVars.ActualSiteBiomass(site); double B_MAX = SpeciesData.Max_Biomass[species]; // B_MAX_Spp[species][ecoregion]; // Initial biomass exponentially declines in response to // competition. double initialBiomass = 0.002 * B_MAX * Math.Exp(-1.6 * B_ACT / B_MAX); initialBiomass = Math.Max(initialBiomass, 5.0); double initialLeafB = initialBiomass * leafFrac; double initialWoodB = initialBiomass - initialLeafB; double[] initialB = new double[2] { initialWoodB, initialLeafB }; float[] initialWoodLeafBiomass = new float[2] { (float)initialB[0], (float)initialB[1] }; return initialWoodLeafBiomass; } //--------------------------------------------------------------------- /// <summary> /// Summarize NPP /// </summary> private static void CalculateNPPcarbon(ActiveSite site, ICohort cohort, double[] AGNPP) { double NPPwood = (double) AGNPP[0] * 0.47; double NPPleaf = (double) AGNPP[1] * 0.47; double NPPcoarseRoot = Roots.CalculateCoarseRoot(cohort, NPPwood); double NPPfineRoot = Roots.CalculateFineRoot(cohort, NPPleaf); if (Double.IsNaN(NPPwood) || Double.IsNaN(NPPleaf) || Double.IsNaN(NPPcoarseRoot) || Double.IsNaN(NPPfineRoot)) { PlugIn.ModelCore.UI.WriteLine(" EITHER WOOD or LEAF NPP or COARSE ROOT or FINE ROOT = NaN! Will set to zero."); PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. WoodNPP={0}, LeafNPP={1}, CRootNPP={2}, FRootNPP={3}.", NPPwood, NPPleaf, NPPcoarseRoot, NPPfineRoot); if (Double.IsNaN(NPPleaf)) NPPleaf = 0.0; if (Double.IsNaN(NPPwood)) NPPwood = 0.0; if (Double.IsNaN(NPPcoarseRoot)) NPPcoarseRoot = 0.0; if (Double.IsNaN(NPPfineRoot)) NPPfineRoot = 0.0; } SiteVars.AGNPPcarbon[site] += NPPwood + NPPleaf; SiteVars.BGNPPcarbon[site] += NPPcoarseRoot + NPPfineRoot; SiteVars.MonthlyAGNPPcarbon[site][Main.Month] += NPPwood + NPPleaf; SiteVars.MonthlyBGNPPcarbon[site][Main.Month] += NPPcoarseRoot + NPPfineRoot; SiteVars.MonthlySoilResp[site][Main.Month] += (NPPcoarseRoot + NPPfineRoot) * 0.53/0.47; //if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode) //{ // Outputs.CalibrateLog.Write("{0:0.00},{1:0.00},", NPPwood, NPPleaf); //} } //-------------------------------------------------------------------------- //N limit is actual demand divided by maximum uptake. private double calculateN_Limit(ActiveSite site, ICohort cohort, double NPP, double leafFractionNPP) { //Get Cohort Mineral and Resorbed N allocation. double mineralNallocation = AvailableN.GetMineralNallocation(cohort); double resorbedNallocation = AvailableN.GetResorbedNallocation(cohort, site); //double LeafNPP = Math.Max(NPP * leafFractionNPP, 0.002 * cohort.WoodBiomass); This allowed for Ndemand in winter when there was no leaf NPP double LeafNPP = (NPP * leafFractionNPP); double WoodNPP = NPP * (1.0 - leafFractionNPP); double limitN = 0.0; if (SpeciesData.NFixer[cohort.Species]) limitN = 1.0; // No limit for N-fixing shrubs else { // Divide allocation N by N demand here: //PlugIn.ModelCore.UI.WriteLine(" WoodNPP={0:0.00}, LeafNPP={1:0.00}, FineRootNPP={2:0.00}, CoarseRootNPP={3:0.00}.", WoodNPP, LeafNPP); double Ndemand = (AvailableN.CalculateCohortNDemand(cohort.Species, site, cohort, new double[] { WoodNPP, LeafNPP})); if (Ndemand > 0.0) { limitN = Math.Min(1.0, (mineralNallocation + resorbedNallocation) / Ndemand); //PlugIn.ModelCore.UI.WriteLine("mineralN={0}, resorbedN={1}, Ndemand={2}", mineralNallocation, resorbedNallocation, Ndemand); } else limitN = 1.0; // No demand means that it is a new or very small cohort. Will allow it to grow anyways. } if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode) { CalibrateLog.mineralNalloc = mineralNallocation; CalibrateLog.resorbedNalloc = resorbedNallocation; //Outputs.CalibrateLog.Write("{0:0.00},{1:0.00},", mineralNallocation, resorbedNallocation); } return Math.Max(limitN, 0.0); } //-------------------------------------------------------------------------- // Originally from lacalc.f of CENTURY model private static double calculateLAI_Limit(ICohort cohort, ActiveSite site) { //...Calculate true LAI using leaf biomass and a biomass-to-LAI // conversion parameter which is the slope of a regression // line derived from LAI vs Foliar Mass for Slash Pine. //...Calculate theoretical LAI as a function of large wood mass. // There is no strong consensus on the true nature of the relationship // between LAI and stemwood mass. Many sutdies have cited as "general" // an increase of LAI up to a maximum, then a decrease to a plateau value // (e.g. Switzer et al. 1968, Gholz and Fisher 1982). However, this // response is not general, and seems to mostly be a feature of young // pine plantations. Northern hardwoods have shown a monotonic increase // to a plateau (e.g. Switzer et al. 1968). Pacific Northwest conifers // have shown a steady increase in LAI with no plateau evident (e.g. // Gholz 1982). In this version, we use a simple saturation fucntion in // which LAI increases linearly against large wood mass initially, then // approaches a plateau value. The plateau value can be set very large to // give a response of steadily increasing LAI with stemwood. // References: // 1) Switzer, G.L., L.E. Nelson and W.H. Smith 1968. // The mineral cycle in forest stands. 'Forest // Fertilization: Theory and Practice'. pp 1-9 // Tenn. Valley Auth., Muscle Shoals, AL. // // 2) Gholz, H.L., and F.R. Fisher 1982. Organic matter // production and distribution in slash pine (Pinus // elliotii) plantations. Ecology 63(6): 1827-1839. // // 3) Gholz, H.L. 1982. Environmental limits on aboveground // net primary production and biomass in vegetation zones of // the Pacific Northwest. Ecology 63:469-481. //...Local variables double leafC = (double) cohort.LeafBiomass * 0.47; double woodC = (double) cohort.WoodBiomass * 0.47; double lai = 0.0; double lai_to_growth = -0.47; // This is the value given for all biomes in the tree.100 file. double btolai = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].BiomassToLAI; double klai = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].KLAI; double maxlai = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].MaxLAI; double k = -0.14; // This is the value given for all temperature ecosystems. double monthly_cumulative_LAI = SiteVars.MonthlyLAI[site][Main.Month]; /// The competition limit is the relationship of the individual to the total amount of LAI /// As the LAI increase the individual contributes less, limiting the amount of leaf area of the /// The younger cohorts as it reaches the species max. double competition_limit = Math.Max(0.0, Math.Exp(k * monthly_cumulative_LAI)); double maxBiomass = SpeciesData.Max_Biomass[cohort.Species]; maxlai = maxlai*competition_limit; // NewFunction for site biomass; // adjust for leaf on/off double seasonal_adjustment = 1.0; if (SpeciesData.LeafLongevity[cohort.Species] <= 1.0) { seasonal_adjustment = (Math.Max(0.0, 1.0 - Math.Exp(btolai * leafC))); } // The cohort LAI given wood Carbon double base_lai = maxlai * woodC/(klai + woodC); //...Choose the LAI reducer on production. lai = base_lai * seasonal_adjustment; // This will allow us to set MAXLAI to zero such that LAI is completely dependent upon // foliar carbon, which may be necessary for simulating defoliation events. if(base_lai <= 0.0) lai = seasonal_adjustment; // The minimum LAI to calculate effect is 0.1. if (lai < 0.1) lai = 0.1; double LAI_Growth_limit = Math.Max(0.0, 1.0 - Math.Exp(lai_to_growth * lai)); //This allows LAI to go to zero for deciduous trees. if (SpeciesData.LeafLongevity[cohort.Species] <= 1.0 && (Main.Month > FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].FoliageDropMonth || Main.Month < 3)) { lai = 0.0; LAI_Growth_limit = 0.0; } if (Main.Month == 6) SiteVars.LAI[site] += lai; //Tracking LAI. SiteVars.MonthlyLAI[site][Main.Month] += lai; // Chihiro 2021.02.23 // Tracking Tree species LAI above grasses if (!SpeciesData.Grass[cohort.Species]) SiteVars.MonthlyLAI_Trees[site][Main.Month] += lai; else SiteVars.MonthlyLAI_Grasses[site][Main.Month] += lai; // Chihiro, 2021.03.30: tentative if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode) { CalibrateLog.actual_LAI = lai; if (!SpeciesData.Grass[cohort.Species]) CalibrateLog.actual_LAI_tree = lai; else CalibrateLog.actual_LAI_tree = 0; CalibrateLog.base_lai = base_lai; CalibrateLog.seasonal_adjustment = seasonal_adjustment; CalibrateLog.siteLAI = SiteVars.MonthlyLAI[site][Main.Month]; // Chihiro, 2021.03.26: added //Outputs.CalibrateLog.Write("{0:0.00},{1:0.00},{2:0.00},", lai, base_lai, seasonal_adjustment); } return LAI_Growth_limit; } private static double calculate_LAI_Competition(ICohort cohort, ActiveSite site) { double k = -0.14; // This is the value given for all temperature ecosystems. I started with 0.1 //double monthly_cumulative_LAI = SiteVars.MonthlyLAI[site][Main.Month]; //double competition_limit = Math.Max(0.0, Math.Exp(k * monthly_cumulative_LAI)); // Chihiro 2020.01.22 // Competition between cohorts considering understory and overstory interactions // If the biomass of tree cohort is larger than total grass biomass on the site, // monthly_cummulative_LAI should ignore grass LAI. // // Added GrassThresholdMultiplier (W.Hotta 2020.07.07) // grassThresholdMultiplier: User defined parameter to adjust relationships between AGB and Hight of the cohort // default = 1.0 // // if (the cohort is tree species) and (biomass_of_tree_cohort > total_grass_biomass_on_the_site * threshold_multiplier): // monthly_cummulative_LAI = Monthly_LAI_of_tree_species // else: // monthly_cummulative_LAI = Monthly_LAI_of_tree_& grass_species // double monthly_cumulative_LAI = 0.0; double grassThresholdMultiplier = PlugIn.Parameters.GrassThresholdMultiplier; // PlugIn.ModelCore.UI.WriteLine("TreeLAI={0},TreeLAI={0}", SiteVars.MonthlyLAITree[site][Main.Month], SiteVars.MonthlyLAI[site][Main.Month]); // added (W.Hotta 2020.07.07) // PlugIn.ModelCore.UI.WriteLine("Spp={0},Time={1},Mo={2},cohortBiomass={3},grassBiomass={4},LAI={5}", cohort.Species.Name, PlugIn.ModelCore.CurrentTime, Main.Month + 1, cohort.Biomass, Main.ComputeGrassBiomass(site), monthly_cumulative_LAI); // added (W.Hotta 2020.07.07) if (!SpeciesData.Grass[cohort.Species] && cohort.Biomass > ComputeGrassBiomass(site) * grassThresholdMultiplier) { monthly_cumulative_LAI = SiteVars.MonthlyLAI_Trees[site][Main.Month]; // PlugIn.ModelCore.UI.WriteLine("Higher than Sasa"); // added (W.Hotta 2020.07.07) } else { // monthly_cumulative_LAI = SiteVars.MonthlyLAI[site][Main.Month]; monthly_cumulative_LAI = SiteVars.MonthlyLAI_Trees[site][Main.Month] + SiteVars.MonthlyLAI_GrassesLastMonth[site]; // Chihiro, 2021.03.30: tentative. trees + grass layer } double competition_limit = Math.Max(0.0, Math.Exp(k * monthly_cumulative_LAI)); return competition_limit; } //--------------------------------------------------------------------------- //... Originally from pprdwc(wc,x,pprpts) of CENTURY //...This funtion returns a value for potential plant production // due to water content. Basically you have an equation of a // line with a moveable y-intercept depending on the soil type. // The value passed in for x is ((avh2o(1) + prcurr(month) + irract)/pet) // pprpts(1): The minimum ratio of available water to pet which // would completely limit production assuming wc=0. // pprpts(2): The effect of wc on the intercept, allows the // user to increase the value of the intercept and // thereby increase the slope of the line. // pprpts(3): The lowest ratio of available water to pet at which // there is no restriction on production. private static double calculateWater_Limit(ActiveSite site, IEcoregion ecoregion, ISpecies species) { // Ratio_AvailWaterToPET used to be pptprd and WaterLimit used to be pprdwc double Ratio_AvailWaterToPET = 0.0; double waterContent = SiteVars.SoilFieldCapacity[site] - SiteVars.SoilWiltingPoint[site]; double tmin = ClimateRegionData.AnnualWeather[ecoregion].MonthlyMinTemp[Main.Month]; double H2Oinputs = ClimateRegionData.AnnualWeather[ecoregion].MonthlyPrecip[Main.Month]; //rain + irract; double pet = ClimateRegionData.AnnualWeather[ecoregion].MonthlyPET[Main.Month]; if (pet >= 0.01) { Ratio_AvailWaterToPET = (SiteVars.AvailableWater[site] / pet); //Modified by ML so that we weren't double-counting precip as in above equation } else Ratio_AvailWaterToPET = 0.01; //...The equation for the y-intercept (intcpt) is A+B*WC. A and B // determine the effect of soil texture on plant production based // on moisture. //PPRPTS naming convention is imported from orginal Century model. Now replaced with 'MoistureCurve' to be more intuitive //...New way (with updated naming convention): double moisturecurve1 = 0.0; // OtherData.MoistureCurve1; double moisturecurve2 = FunctionalType.Table[SpeciesData.FuncType[species]].MoistureCurve2; double moisturecurve3 = FunctionalType.Table[SpeciesData.FuncType[species]].MoistureCurve3; double intcpt = moisturecurve1 + (moisturecurve2 * waterContent); double slope = 1.0 / (moisturecurve3 - intcpt); double WaterLimit = 1.0 + slope * (Ratio_AvailWaterToPET - moisturecurve3); if (WaterLimit > 1.0) WaterLimit = 1.0; if (WaterLimit < 0.01) WaterLimit = 0.01; //PlugIn.ModelCore.UI.WriteLine("Intercept={0}, Slope={1}, WaterLimit={2}.", intcpt, slope, WaterLimit); if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode) { CalibrateLog.availableWater = SiteVars.AvailableWater[site]; //Outputs.CalibrateLog.Write("{0:0.00},", SiteVars.AvailableWater[site]); } return WaterLimit; } //----------- private double calculateTemp_Limit(ActiveSite site, ISpecies species) { //Originally from gpdf.f of CENTURY model //It calculates the limitation of soil temperature on aboveground forest potential production. //...This routine is functionally equivalent to the routine of the // same name, described in the publication: // Some Graphs and their Functional Forms // Technical Report No. 153 // William Parton and George Innis (1972) // Natural Resource Ecology Lab. // Colorado State University // Fort collins, Colorado 80523 double A1 = SiteVars.SoilTemperature[site]; double A2 = FunctionalType.Table[SpeciesData.FuncType[species]].TempCurve1; double A3 = FunctionalType.Table[SpeciesData.FuncType[species]].TempCurve2; double A4 = FunctionalType.Table[SpeciesData.FuncType[species]].TempCurve3; double A5 = FunctionalType.Table[SpeciesData.FuncType[species]].TempCurve4; double frac = (A3-A1) / (A3-A2); double U1 = 0.0; if (frac > 0.0) U1 = Math.Exp(A4 / A5 * (1.0 - Math.Pow(frac, A5))) * Math.Pow(frac, A4); //PlugIn.ModelCore.UI.WriteLine(" TEMPERATURE Limits: Month={0}, Soil Temp={1:0.00}, Temp Limit={2:0.00}. [PPDF1={3:0.0},PPDF2={4:0.0},PPDF3={5:0.0},PPDF4={6:0.0}]", month+1, A1, U1,A2,A3,A4,A5); return U1; } //--------------------------------------------------------------------- // Chihiro 2020.01.22 public static double ComputeGrassBiomass(ActiveSite site) { double grassTotal = 0; if (SiteVars.Cohorts[site] != null) foreach (ISpeciesCohorts speciesCohorts in SiteVars.Cohorts[site]) foreach (ICohort cohort in speciesCohorts) if (SpeciesData.Grass[cohort.Species]) grassTotal += cohort.WoodBiomass; return grassTotal; } } }
// 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.CustomerInsights { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ConnectorsOperations operations. /// </summary> public partial interface IConnectorsOperations { /// <summary> /// Creates a connector or updates an existing connector in the hub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='connectorName'> /// The name of the connector. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate Connector operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectorResourceFormat>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, ConnectorResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a connector in the hub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='connectorName'> /// The name of the connector. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectorResourceFormat>> GetWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a connector in the hub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='connectorName'> /// The name of the connector. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the connectors in the specified hub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ConnectorResourceFormat>>> ListByHubWithHttpMessagesAsync(string resourceGroupName, string hubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a connector or updates an existing connector in the hub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='connectorName'> /// The name of the connector. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate Connector operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectorResourceFormat>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, ConnectorResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a connector in the hub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='connectorName'> /// The name of the connector. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the connectors in the specified hub. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ConnectorResourceFormat>>> ListByHubNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// PagingOperations operations. /// </summary> public partial interface IPagingOperations { /// <summary> /// A paging operation that finishes on the first call without a /// nextlink /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='clientRequestId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that fails on the first call with 500 and then /// retries and then get a response including a nextLink that has 10 /// pages /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetryFirstWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of /// which the 2nd call fails first with 500. The client should retry /// and finish all 10 pages eventually. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetrySecondWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureUriWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that finishes on the first call without a /// nextlink /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that fails on the first call with 500 and then /// retries and then get a response including a nextLink that has 10 /// pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of /// which the 2nd call fails first with 500. The client should retry /// and finish all 10 pages eventually. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesFailureNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureUriNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
#region License // // OutputDocument.cs July 2006 // // Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net> // // 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 Using directives using System; #endregion namespace SimpleFramework.Xml.Stream { /// <summary> /// The <c>OutputDocument</c> object is used to represent the /// root of an XML document. This does not actually represent anything /// that will be written to the generated document. It is used as a /// way to create the root document element. Once the root element has /// been created it can be committed by using this object. /// </summary> class OutputDocument : OutputNode { /// <summary> /// Represents a dummy output node map for the attributes. /// </summary> private OutputNodeMap table; /// <summary> /// Represents the writer that is used to create the element. /// </summary> private NodeWriter writer; /// <summary> /// This is the output stack used by the node writer object. /// </summary> private OutputStack stack; /// <summary> /// This represents the namespace reference used by this. /// </summary> private String reference; /// <summary> /// This is the comment that is to be written for the node. /// </summary> private String comment; /// <summary> /// Represents the value that has been set on this document. /// </summary> private String value; /// <summary> /// This is the output mode of this output document object. /// </summary> private Mode mode; /// <summary> /// Constructor for the <c>OutputDocument</c> object. This /// is used to create an empty output node object that can be /// used to create a root element for the generated document. /// </summary> /// <param name="writer"> /// This is the node writer to write the node to. /// </param> /// <param name="stack"> /// This is the stack that contains the open nodes. /// </param> public OutputDocument(NodeWriter writer, OutputStack stack) { this.table = new OutputNodeMap(this); this.mode = Mode.Inherit; this.writer = writer; this.stack = stack; } /// <summary> /// The default for the <c>OutputDocument</c> is null as it /// does not require a namespace. A null prefix is always used by /// the document as it represents a virtual node that does not /// exist and will not form any part of the resulting XML. /// </summary> /// <returns> /// This returns a null prefix for the output document. /// </returns> public String GetPrefix() { return null; } /// The default for the <c>OutputDocument</c> is null as it /// does not require a namespace. A null prefix is always used by /// the document as it represents a virtual node that does not /// exist and will not form any part of the resulting XML. /// </summary> /// <param name="inherit"> /// If there is no explicit prefix then inherit. /// </param> /// <returns> /// This returns a null prefix for the output document. /// </returns> public String GetPrefix(bool inherit) { return null; } /// <summary> /// This is used to acquire the reference that has been set on /// this output node. Typically this should be null as this node /// does not represent anything that actually exists. However /// if a namespace reference is set it can be acquired. /// </summary> /// <returns> /// This returns the namespace reference for this node /// </returns> public String Reference { get { return reference; } set { this.reference = value; } } /// This returns the <c>NamespaceMap</c> for the document. /// The namespace map for the document must be null as this will /// signify the end of the resolution process for a prefix if /// given a namespace reference. /// </summary> /// <returns> /// This will return a null namespace map object. /// </returns> public NamespaceMap Namespaces { get { return null; } } /// This is used to acquire the <c>Node</c> that is the /// parent of this node. This will return the node that is /// the direct parent of this node and allows for siblings to /// make use of nodes with their parents if required. /// </summary> /// <returns> /// This will always return null for this output. /// </returns> public OutputNode Parent { get { return null; } } /// To signify that this is the document element this method will /// return null. Any object with a handle on an output node that /// has been created can check the name to determine its type. /// </summary> /// <returns> /// This returns null for the name of the node. /// </returns> public String Name { get { return null; } } /// This returns the value that has been set for this document. /// The value returned is essentially a dummy value as this node /// is never written to the resulting XML document. /// </summary> /// <returns> /// The value that has been set with this document. /// </returns> public String Value { get { return value; } set { this.value = value; } } /// This is used to get the text comment for the element. This can /// be null if no comment has been set. If no comment is set on /// the node then no comment will be written to the resulting XML. /// </summary> /// <returns> /// This is the comment associated with this element. /// </returns> public String Comment { get { return comment; } set { this.comment = value; } } /// This method is used to determine if this node is the root /// node for the XML document. The root node is the first node /// in the document and has no sibling nodes. This will return /// true although the document node is not strictly the root. /// </summary> /// <returns> /// Returns true although this is not really a root. /// </returns> public bool IsRoot() { return true; } /// <summary> /// The <c>Mode</c> is used to indicate the output mode /// of this node. Three modes are possible, each determines /// how a value, if specified, is written to the resulting XML /// document. This is determined by the <c>setData</c> /// method which will set the output to be CDATA or escaped, /// if neither is specified the mode is inherited. /// </summary> /// <returns> /// This returns the mode of this output node object. /// </returns> public Mode Mode { get { return mode; } set { this.mode = value; } } /// This method is used for convenience to add an attribute node /// to the attribute <c>NodeMap</c>. The attribute added /// can be removed from the element by using the node map. /// </summary> /// <param name="name"> /// This is the name of the attribute to be added. /// </param> /// <param name="value"> /// This is the value of the node to be added. /// </param> /// <returns> /// This returns the node that has just been added. /// </returns> public OutputNode SetAttribute(String name, String value) { return table.Put(name, value); } /// <summary> /// This returns a <c>NodeMap</c> which can be used to add /// nodes to this node. The node map returned by this is a dummy /// map, as this output node is never written to the XML document. /// </summary> /// <returns> /// Returns the node map used to manipulate attributes. /// </returns> public NodeMap<OutputNode> Attributes { get { return table; } } /// This is used to set the output mode of this node to either /// be CDATA or escaped. If this is set to true the any value /// specified will be written in a CDATA block, if this is set /// to false the values is escaped. If however this method is /// never invoked then the mode is inherited from the parent. /// </summary> /// <param name="data"> /// If true the value is written as a CDATA block. /// </param> public bool Data { set { if(value) { mode = Mode.Data; } else { mode = Mode.Escape; } } } /// This is used to create a child element within the element that /// this object represents. When a new child is created with this /// method then the previous child is committed to the document. /// The created <c>OutputNode</c> object can be used to add /// attributes to the child element as well as other elements. /// </summary> /// <param name="name"> /// This is the name of the child element to create. /// </param> public OutputNode GetChild(String name) { return writer.WriteElement(this, name); } /// <summary> /// This is used to remove any uncommitted changes. Removal of an /// output node can only be done if it has no siblings and has /// not yet been committed. If the node is committed then this /// will throw an exception to indicate that it cannot be removed. /// </summary> public void Remove() { if(stack.IsEmpty()) { throw new NodeException("No root node"); } stack.Bottom().Remove(); } /// <summary> /// This will commit this element and any uncommitted elements /// elements that are decendents of this node. For instance if /// any child or grand child remains open under this element /// then those elements will be closed before this is closed. /// </summary> public void Commit() { if(stack.IsEmpty()) { throw new NodeException("No root node"); } stack.Bottom().Commit(); } /// <summary> /// This is used to determine whether this node has been committed. /// This will return true if no root element has been created or /// if the root element for the document has already been commited. /// </summary> /// <returns> /// Irue if the node is committed or has not been created. /// </returns> public bool IsCommitted() { return stack.IsEmpty(); } } }
using System; using System.Runtime.InteropServices; using System.Reflection; using System.Threading; using System.Windows.Forms; using System.ComponentModel; namespace Wordy { /// <summary> /// This class allows you to tap keyboard and mouse and / or to detect their activity even when an /// application runes in background or does not have any user interface at all. This class raises /// common .NET events with KeyEventArgs and MouseEventArgs so you can easily retrive any information you need. /// </summary> public class UserActivityHook { #region Windows structure definitions /// <summary> /// The POINT structure defines the x- and y- coordinates of a point. /// </summary> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/rectangl_0tiq.asp /// </remarks> [StructLayout(LayoutKind.Sequential)] private class POINT { /// <summary> /// Specifies the x-coordinate of the point. /// </summary> public int x; /// <summary> /// Specifies the y-coordinate of the point. /// </summary> public int y; } /// <summary> /// The MOUSEHOOKSTRUCT structure contains information about a mouse event passed to a WH_MOUSE hook procedure, MouseProc. /// </summary> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp /// </remarks> [StructLayout(LayoutKind.Sequential)] private class MouseHookStruct { /// <summary> /// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates. /// </summary> public POINT pt; /// <summary> /// Handle to the window that will receive the mouse message corresponding to the mouse event. /// </summary> public int hwnd; /// <summary> /// Specifies the hit-test value. For a list of hit-test values, see the description of the WM_NCHITTEST message. /// </summary> public int wHitTestCode; /// <summary> /// Specifies extra information associated with the message. /// </summary> public int dwExtraInfo; } /// <summary> /// The MSLLHOOKSTRUCT structure contains information about a low-level keyboard input event. /// </summary> [StructLayout(LayoutKind.Sequential)] private class MouseLLHookStruct { /// <summary> /// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates. /// </summary> public POINT pt; /// <summary> /// If the message is WM_MOUSEWHEEL, the high-order word of this member is the wheel delta. /// The low-order word is reserved. A positive value indicates that the wheel was rotated forward, /// away from the user; a negative value indicates that the wheel was rotated backward, toward the user. /// One wheel click is defined as WHEEL_DELTA, which is 120. ///If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP, /// or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released, /// and the low-order word is reserved. This value can be one or more of the following values. Otherwise, mouseData is not used. ///XBUTTON1 ///The first X button was pressed or released. ///XBUTTON2 ///The second X button was pressed or released. /// </summary> public int mouseData; /// <summary> /// Specifies the event-injected flag. An application can use the following value to test the mouse flags. Value Purpose ///LLMHF_INJECTED Test the event-injected flag. ///0 ///Specifies whether the event was injected. The value is 1 if the event was injected; otherwise, it is 0. ///1-15 ///Reserved. /// </summary> public int flags; /// <summary> /// Specifies the time stamp for this message. /// </summary> public int time; /// <summary> /// Specifies extra information associated with the message. /// </summary> public int dwExtraInfo; } /// <summary> /// The KBDLLHOOKSTRUCT structure contains information about a low-level keyboard input event. /// </summary> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp /// </remarks> [StructLayout(LayoutKind.Sequential)] private class KeyboardHookStruct { /// <summary> /// Specifies a virtual-key code. The code must be a value in the range 1 to 254. /// </summary> public int vkCode; /// <summary> /// Specifies a hardware scan code for the key. /// </summary> public int scanCode; /// <summary> /// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag. /// </summary> public int flags; /// <summary> /// Specifies the time stamp for this message. /// </summary> public int time; /// <summary> /// Specifies extra information associated with the message. /// </summary> public int dwExtraInfo; } #endregion #region Windows function imports /// <summary> /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain. /// You would install a hook procedure to monitor the system for certain types of events. These events /// are associated either with a specific thread or with all threads in the same desktop as the calling thread. /// </summary> /// <param name="idHook"> /// [in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values. /// </param> /// <param name="lpfn"> /// [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a /// thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link /// library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process. /// </param> /// <param name="hMod"> /// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter. /// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by /// the current process and if the hook procedure is within the code associated with the current process. /// </param> /// <param name="dwThreadId"> /// [in] Specifies the identifier of the thread with which the hook procedure is to be associated. /// If this parameter is zero, the hook procedure is associated with all existing threads running in the /// same desktop as the calling thread. /// </param> /// <returns> /// If the function succeeds, the return value is the handle to the hook procedure. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp /// </remarks> [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] private static extern int SetWindowsHookEx( int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId); /// <summary> /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function. /// </summary> /// <param name="idHook"> /// [in] Handle to the hook to be removed. This parameter is a hook handle obtained by a previous call to SetWindowsHookEx. /// </param> /// <returns> /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp /// </remarks> [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] private static extern int UnhookWindowsHookEx(int idHook); /// <summary> /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain. /// A hook procedure can call this function either before or after processing the hook information. /// </summary> /// <param name="idHook">Ignored.</param> /// <param name="nCode"> /// [in] Specifies the hook code passed to the current hook procedure. /// The next hook procedure uses this code to determine how to process the hook information. /// </param> /// <param name="wParam"> /// [in] Specifies the wParam value passed to the current hook procedure. /// The meaning of this parameter depends on the type of hook associated with the current hook chain. /// </param> /// <param name="lParam"> /// [in] Specifies the lParam value passed to the current hook procedure. /// The meaning of this parameter depends on the type of hook associated with the current hook chain. /// </param> /// <returns> /// This value is returned by the next hook procedure in the chain. /// The current hook procedure must also return this value. The meaning of the return value depends on the hook type. /// For more information, see the descriptions of the individual hook procedures. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp /// </remarks> [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] private static extern int CallNextHookEx( int idHook, int nCode, int wParam, IntPtr lParam); /// <summary> /// The CallWndProc hook procedure is an application-defined or library-defined callback /// function used with the SetWindowsHookEx function. The HOOKPROC type defines a pointer /// to this callback function. CallWndProc is a placeholder for the application-defined /// or library-defined function name. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/callwndproc.asp /// </remarks> private delegate int HookProc(int nCode, int wParam, IntPtr lParam); /// <summary> /// The ToAscii function translates the specified virtual-key code and keyboard /// state to the corresponding character or characters. The function translates the code /// using the input language and physical keyboard layout identified by the keyboard layout handle. /// </summary> /// <param name="uVirtKey"> /// [in] Specifies the virtual-key code to be translated. /// </param> /// <param name="uScanCode"> /// [in] Specifies the hardware scan code of the key to be translated. /// The high-order bit of this value is set if the key is up (not pressed). /// </param> /// <param name="lpbKeyState"> /// [in] Pointer to a 256-byte array that contains the current keyboard state. /// Each element (byte) in the array contains the state of one key. /// If the high-order bit of a byte is set, the key is down (pressed). /// The low bit, if set, indicates that the key is toggled on. In this function, /// only the toggle bit of the CAPS LOCK key is relevant. The toggle state /// of the NUM LOCK and SCROLL LOCK keys is ignored. /// </param> /// <param name="lpwTransKey"> /// [out] Pointer to the buffer that receives the translated character or characters. /// </param> /// <param name="fuState"> /// [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise. /// </param> /// <returns> /// If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values. /// Value Meaning /// 0 The specified virtual key has no translation for the current state of the keyboard. /// 1 One character was copied to the buffer. /// 2 Two characters were copied to the buffer. This usually happens when a dead-key character /// (accent or diacritic) stored in the keyboard layout cannot be composed with the specified /// virtual key to form a single character. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp /// </remarks> [DllImport("user32")] private static extern int ToAscii( int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState); /// <summary> /// The GetKeyboardState function copies the status of the 256 virtual keys to the /// specified buffer. /// </summary> /// <param name="pbKeyState"> /// [in] Pointer to a 256-byte array that contains keyboard key states. /// </param> /// <returns> /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp /// </remarks> [DllImport("user32")] private static extern int GetKeyboardState(byte[] pbKeyState); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] private static extern short GetKeyState(int vKey); [DllImport("kernel32.dll")] public static extern IntPtr GetModuleHandle(string name); #endregion #region Windows constants //values from Winuser.h in Microsoft SDK. /// <summary> /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events. /// </summary> private const int WH_MOUSE_LL = 14; /// <summary> /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events. /// </summary> private const int WH_KEYBOARD_LL = 13; /// <summary> /// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure. /// </summary> private const int WH_MOUSE = 7; /// <summary> /// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure. /// </summary> private const int WH_KEYBOARD = 2; /// <summary> /// The WM_MOUSEMOVE message is posted to a window when the cursor moves. /// </summary> private const int WM_MOUSEMOVE = 0x200; /// <summary> /// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button /// </summary> private const int WM_LBUTTONDOWN = 0x201; /// <summary> /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button /// </summary> private const int WM_RBUTTONDOWN = 0x204; /// <summary> /// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button /// </summary> private const int WM_MBUTTONDOWN = 0x207; /// <summary> /// The WM_LBUTTONUP message is posted when the user releases the left mouse button /// </summary> private const int WM_LBUTTONUP = 0x202; /// <summary> /// The WM_RBUTTONUP message is posted when the user releases the right mouse button /// </summary> private const int WM_RBUTTONUP = 0x205; /// <summary> /// The WM_MBUTTONUP message is posted when the user releases the middle mouse button /// </summary> private const int WM_MBUTTONUP = 0x208; /// <summary> /// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button /// </summary> private const int WM_LBUTTONDBLCLK = 0x203; /// <summary> /// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button /// </summary> private const int WM_RBUTTONDBLCLK = 0x206; /// <summary> /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button /// </summary> private const int WM_MBUTTONDBLCLK = 0x209; /// <summary> /// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel. /// </summary> private const int WM_MOUSEWHEEL = 0x020A; /// <summary> /// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem /// key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed. /// </summary> private const int WM_KEYDOWN = 0x100; /// <summary> /// The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem /// key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed, /// or a keyboard key that is pressed when a window has the keyboard focus. /// </summary> private const int WM_KEYUP = 0x101; /// <summary> /// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user /// presses the F10 key (which activates the menu bar) or holds down the ALT key and then /// presses another key. It also occurs when no window currently has the keyboard focus; /// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that /// receives the message can distinguish between these two contexts by checking the context /// code in the lParam parameter. /// </summary> private const int WM_SYSKEYDOWN = 0x104; /// <summary> /// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user /// releases a key that was pressed while the ALT key was held down. It also occurs when no /// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent /// to the active window. The window that receives the message can distinguish between /// these two contexts by checking the context code in the lParam parameter. /// </summary> private const int WM_SYSKEYUP = 0x105; private const byte VK_SHIFT = 0x10; private const byte VK_CAPITAL = 0x14; private const byte VK_NUMLOCK = 0x90; #endregion /// <summary> /// Creates an instance of UserActivityHook object and sets mouse and keyboard hooks. /// </summary> /// <exception cref="Win32Exception">Any windows problem.</exception> public UserActivityHook() { Start(); } /// <summary> /// Creates an instance of UserActivityHook object and installs both or one of mouse and/or keyboard hooks and starts rasing events /// </summary> /// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param> /// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param> /// <exception cref="Win32Exception">Any windows problem.</exception> /// <remarks> /// To create an instance without installing hooks call new UserActivityHook(false, false) /// </remarks> public UserActivityHook(bool InstallMouseHook, bool InstallKeyboardHook) { Start(InstallMouseHook, InstallKeyboardHook); } /// <summary> /// Destruction. /// </summary> ~UserActivityHook() { //uninstall hooks and do not throw exceptions Stop(true, true, false); } /// <summary> /// Occurs when the user moves the mouse, presses any mouse button or scrolls the wheel /// </summary> public event MouseEventHandler OnMouseActivity; /// <summary> /// Occurs when the user presses a key /// </summary> public event KeyEventHandler KeyDown; /// <summary> /// Occurs when the user presses and releases /// </summary> public event KeyPressEventHandler KeyPress; /// <summary> /// Occurs when the user releases a key /// </summary> public event KeyEventHandler KeyUp; /// <summary> /// Stores the handle to the mouse hook procedure. /// </summary> private int hMouseHook = 0; /// <summary> /// Stores the handle to the keyboard hook procedure. /// </summary> private int hKeyboardHook = 0; /// <summary> /// Declare MouseHookProcedure as HookProc type. /// </summary> private static HookProc MouseHookProcedure; /// <summary> /// Declare KeyboardHookProcedure as HookProc type. /// </summary> private static HookProc KeyboardHookProcedure; /// <summary> /// Installs both mouse and keyboard hooks and starts rasing events /// </summary> /// <exception cref="Win32Exception">Any windows problem.</exception> public void Start() { this.Start(true, true); } /// <summary> /// Installs both or one of mouse and/or keyboard hooks and starts rasing events /// </summary> /// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param> /// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param> /// <exception cref="Win32Exception">Any windows problem.</exception> public void Start(bool InstallMouseHook, bool InstallKeyboardHook) { // install Mouse hook only if it is not installed and must be installed if (hMouseHook == 0 && InstallMouseHook) { // Create an instance of HookProc. MouseHookProcedure = new HookProc(MouseHookProc); //install hook hMouseHook = SetWindowsHookEx( WH_MOUSE_LL, MouseHookProcedure, GetModuleHandle(System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName), 0); //If SetWindowsHookEx fails. if (hMouseHook == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //do cleanup Stop(true, false, false); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } // install Keyboard hook only if it is not installed and must be installed if (hKeyboardHook == 0 && InstallKeyboardHook) { // Create an instance of HookProc. KeyboardHookProcedure = new HookProc(KeyboardHookProc); //install hook hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, KeyboardHookProcedure, GetModuleHandle(System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName), 0); //If SetWindowsHookEx fails. if (hKeyboardHook == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //do cleanup Stop(false, true, false); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } } /// <summary> /// Stops monitoring both mouse and keyboard events and rasing events. /// </summary> /// <exception cref="Win32Exception">Any windows problem.</exception> public void Stop() { this.Stop(true, true, true); } /// <summary> /// Stops monitoring both or one of mouse and/or keyboard events and rasing events. /// </summary> /// <param name="UninstallMouseHook"><b>true</b> if mouse hook must be uninstalled</param> /// <param name="UninstallKeyboardHook"><b>true</b> if keyboard hook must be uninstalled</param> /// <param name="ThrowExceptions"><b>true</b> if exceptions which occured during uninstalling must be thrown</param> /// <exception cref="Win32Exception">Any windows problem.</exception> public void Stop(bool UninstallMouseHook, bool UninstallKeyboardHook, bool ThrowExceptions) { //if mouse hook set and must be uninstalled if (hMouseHook != 0 && UninstallMouseHook) { //uninstall hook int retMouse = UnhookWindowsHookEx(hMouseHook); //reset invalid handle hMouseHook = 0; //if failed and exception must be thrown if (retMouse == 0 && ThrowExceptions) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } //if keyboard hook set and must be uninstalled if (hKeyboardHook != 0 && UninstallKeyboardHook) { //uninstall hook int retKeyboard = UnhookWindowsHookEx(hKeyboardHook); //reset invalid handle hKeyboardHook = 0; //if failed and exception must be thrown if (retKeyboard == 0 && ThrowExceptions) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } } /// <summary> /// A callback function which will be called every time a mouse activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> private int MouseHookProc(int nCode, int wParam, IntPtr lParam) { // if ok and someone listens to our events if ((nCode >= 0) && (OnMouseActivity != null)) { //Marshall the data from callback. MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct)); //detect button clicked MouseButtons button = MouseButtons.None; bool buttonUp = false; short mouseDelta = 0; switch (wParam) { case WM_LBUTTONDOWN: //case WM_LBUTTONUP: //case WM_LBUTTONDBLCLK: button = MouseButtons.Left; break; case WM_LBUTTONUP: //Adjutant need to detect mouse button up event so it knows when to stop resizing itself in pad mode button = MouseButtons.Left; buttonUp = true; break; case WM_RBUTTONDOWN: //case WM_RBUTTONUP: //case WM_RBUTTONDBLCLK: button = MouseButtons.Right; break; case WM_MOUSEWHEEL: //If the message is WM_MOUSEWHEEL, the high-order word of mouseData member is the wheel delta. //One wheel click is defined as WHEEL_DELTA, which is 120. //(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff); //TODO: X BUTTONS (I havent them so was unable to test) //If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP, //or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released, //and the low-order word is reserved. This value can be one or more of the following values. //Otherwise, mouseData is not used. break; } //double clicks int clickCount = 0; if (button != MouseButtons.None) if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2; else clickCount = 1; if (buttonUp) { //MouseEventArgs doesn't indicate if a button has been depressed so we need to send that information through mouseDelta mouseDelta = Misc.MOUSE_UP_CODE; } //generate event MouseEventArgs e = new MouseEventArgs( button, clickCount, mouseHookStruct.pt.x, mouseHookStruct.pt.y, mouseDelta); //raise it OnMouseActivity(this, e); } //call next hook return CallNextHookEx(hMouseHook, nCode, wParam, lParam); } /// <summary> /// A callback function which will be called every time a keyboard activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { //indicates if any of underlaing events set e.Handled flag bool handled = false; //it was ok and someone listens to events if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null)) { //read structure KeyboardHookStruct at lParam KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //raise KeyDown if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyDown(this, e); handled = handled || e.Handled; } // raise KeyPress if (KeyPress != null && wParam == WM_KEYDOWN) { bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false); bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false); byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1) { char key = (char)inBuffer[0]; if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key); KeyPressEventArgs e = new KeyPressEventArgs(key); KeyPress(this, e); handled = handled || e.Handled; } } // raise KeyUp if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyUp(this, e); handled = handled || e.Handled; } } //if event handled in application do not handoff to other listeners if (handled) return 1; else return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam); } } }
// 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.Globalization; using System.Xml.Schema; using System.Xml.XPath; using System.Xml.Xsl.Qil; //#define StopMaskOptimisation namespace System.Xml.Xsl.XPath { using FunctionInfo = XPathBuilder.FunctionInfo<XPathBuilder.FuncId>; using T = XmlQueryTypeFactory; internal class XPathBuilder : IXPathBuilder<QilNode>, IXPathEnvironment { private XPathQilFactory _f; private IXPathEnvironment _environment; private bool _inTheBuild; // Singleton nodes used as fixup markers protected QilNode fixupCurrent, fixupPosition, fixupLast; // Number of unresolved fixup nodes protected int numFixupCurrent, numFixupPosition, numFixupLast; private FixupVisitor _fixupVisitor; /* ---------------------------------------------------------------------------- IXPathEnvironment interface */ QilNode IFocus.GetCurrent() { return GetCurrentNode(); } QilNode IFocus.GetPosition() { return GetCurrentPosition(); } QilNode IFocus.GetLast() { return GetLastPosition(); } XPathQilFactory IXPathEnvironment.Factory { get { return _f; } } QilNode IXPathEnvironment.ResolveVariable(string prefix, string name) { return Variable(prefix, name); } QilNode IXPathEnvironment.ResolveFunction(string prefix, string name, IList<QilNode> args, IFocus env) { Debug.Fail("Must not be called"); return null; } string IXPathEnvironment.ResolvePrefix(string prefix) { return _environment.ResolvePrefix(prefix); } // ---------------------------------------------------------------------------- public XPathBuilder(IXPathEnvironment environment) { _environment = environment; _f = _environment.Factory; this.fixupCurrent = _f.Unknown(T.NodeNotRtf); this.fixupPosition = _f.Unknown(T.DoubleX); this.fixupLast = _f.Unknown(T.DoubleX); _fixupVisitor = new FixupVisitor(_f, fixupCurrent, fixupPosition, fixupLast); } public virtual void StartBuild() { Debug.Assert(!_inTheBuild, "XPathBuilder is busy!"); _inTheBuild = true; numFixupCurrent = numFixupPosition = numFixupLast = 0; } public virtual QilNode EndBuild(QilNode result) { if (result == null) { // special door to clean builder state in exception handlers _inTheBuild = false; return result; } Debug.Assert(_inTheBuild, "StartBuild() wasn't called"); if (result.XmlType.MaybeMany && result.XmlType.IsNode && result.XmlType.IsNotRtf) { result = _f.DocOrderDistinct(result); } result = _fixupVisitor.Fixup(result, /*environment:*/_environment); numFixupCurrent -= _fixupVisitor.numCurrent; numFixupPosition -= _fixupVisitor.numPosition; numFixupLast -= _fixupVisitor.numLast; // All these variables will be positive for "false() and (. = position() + last())" // since QilPatternFactory eliminates the right operand of 'and' Debug.Assert(numFixupCurrent >= 0, "Context fixup error"); Debug.Assert(numFixupPosition >= 0, "Context fixup error"); Debug.Assert(numFixupLast >= 0, "Context fixup error"); _inTheBuild = false; return result; } private QilNode GetCurrentNode() { numFixupCurrent++; return fixupCurrent; } private QilNode GetCurrentPosition() { numFixupPosition++; return fixupPosition; } private QilNode GetLastPosition() { numFixupLast++; return fixupLast; } public virtual QilNode String(string value) { return _f.String(value); } public virtual QilNode Number(double value) { return _f.Double(value); } public virtual QilNode Operator(XPathOperator op, QilNode left, QilNode right) { Debug.Assert(op != XPathOperator.Unknown); switch (s_operatorGroup[(int)op]) { case XPathOperatorGroup.Logical: return LogicalOperator(op, left, right); case XPathOperatorGroup.Equality: return EqualityOperator(op, left, right); case XPathOperatorGroup.Relational: return RelationalOperator(op, left, right); case XPathOperatorGroup.Arithmetic: return ArithmeticOperator(op, left, right); case XPathOperatorGroup.Negate: return NegateOperator(op, left, right); case XPathOperatorGroup.Union: return UnionOperator(op, left, right); default: Debug.Fail(op + " is not a valid XPathOperator"); return null; } } private QilNode LogicalOperator(XPathOperator op, QilNode left, QilNode right) { Debug.Assert(op == XPathOperator.Or || op == XPathOperator.And); left = _f.ConvertToBoolean(left); right = _f.ConvertToBoolean(right); return ( op == XPathOperator.Or ? _f.Or(left, right) : /*default*/ _f.And(left, right) ); } private QilNode CompareValues(XPathOperator op, QilNode left, QilNode right, XmlTypeCode compType) { Debug.Assert(compType == XmlTypeCode.Boolean || compType == XmlTypeCode.Double || compType == XmlTypeCode.String); Debug.Assert(compType == XmlTypeCode.Boolean || left.XmlType.IsSingleton && right.XmlType.IsSingleton, "Both comparison operands must be singletons"); left = _f.ConvertToType(compType, left); right = _f.ConvertToType(compType, right); switch (op) { case XPathOperator.Eq: return _f.Eq(left, right); case XPathOperator.Ne: return _f.Ne(left, right); case XPathOperator.Lt: return _f.Lt(left, right); case XPathOperator.Le: return _f.Le(left, right); case XPathOperator.Gt: return _f.Gt(left, right); case XPathOperator.Ge: return _f.Ge(left, right); default: Debug.Fail("Wrong operator type"); return null; } } private QilNode CompareNodeSetAndValue(XPathOperator op, QilNode nodeset, QilNode val, XmlTypeCode compType) { _f.CheckNodeSet(nodeset); Debug.Assert(val.XmlType.IsSingleton); Debug.Assert(compType == XmlTypeCode.Boolean || compType == XmlTypeCode.Double || compType == XmlTypeCode.String, "I don't know what to do with RTF here"); if (compType == XmlTypeCode.Boolean || nodeset.XmlType.IsSingleton) { return CompareValues(op, nodeset, val, compType); } else { QilIterator it = _f.For(nodeset); return _f.Not(_f.IsEmpty(_f.Filter(it, CompareValues(op, _f.XPathNodeValue(it), val, compType)))); } } // Inverts relational operator in order to swap operands of the comparison private static XPathOperator InvertOp(XPathOperator op) { return ( op == XPathOperator.Lt ? XPathOperator.Gt : // '<' --> '>' op == XPathOperator.Le ? XPathOperator.Ge : // '<=' --> '>=' op == XPathOperator.Gt ? XPathOperator.Lt : // '>' --> '<' op == XPathOperator.Ge ? XPathOperator.Le : // '>=' --> '<=' /*default:*/ op ); } private QilNode CompareNodeSetAndNodeSet(XPathOperator op, QilNode left, QilNode right, XmlTypeCode compType) { _f.CheckNodeSet(left); _f.CheckNodeSet(right); if (right.XmlType.IsSingleton) { return CompareNodeSetAndValue(op, /*nodeset:*/left, /*value:*/right, compType); } if (left.XmlType.IsSingleton) { op = InvertOp(op); return CompareNodeSetAndValue(op, /*nodeset:*/right, /*value:*/left, compType); } QilIterator leftEnd = _f.For(left); QilIterator rightEnd = _f.For(right); return _f.Not(_f.IsEmpty(_f.Loop(leftEnd, _f.Filter(rightEnd, CompareValues(op, _f.XPathNodeValue(leftEnd), _f.XPathNodeValue(rightEnd), compType))))); } private QilNode EqualityOperator(XPathOperator op, QilNode left, QilNode right) { Debug.Assert(op == XPathOperator.Eq || op == XPathOperator.Ne); XmlQueryType leftType = left.XmlType; XmlQueryType rightType = right.XmlType; if (_f.IsAnyType(left) || _f.IsAnyType(right)) { return _f.InvokeEqualityOperator(s_qilOperator[(int)op], left, right); } else if (leftType.IsNode && rightType.IsNode) { return CompareNodeSetAndNodeSet(op, left, right, XmlTypeCode.String); } else if (leftType.IsNode) { return CompareNodeSetAndValue(op, /*nodeset:*/left, /*val:*/right, rightType.TypeCode); } else if (rightType.IsNode) { return CompareNodeSetAndValue(op, /*nodeset:*/right, /*val:*/left, leftType.TypeCode); } else { XmlTypeCode compType = ( leftType.TypeCode == XmlTypeCode.Boolean || rightType.TypeCode == XmlTypeCode.Boolean ? XmlTypeCode.Boolean : leftType.TypeCode == XmlTypeCode.Double || rightType.TypeCode == XmlTypeCode.Double ? XmlTypeCode.Double : /*default:*/ XmlTypeCode.String ); return CompareValues(op, left, right, compType); } } private QilNode RelationalOperator(XPathOperator op, QilNode left, QilNode right) { Debug.Assert(op == XPathOperator.Lt || op == XPathOperator.Le || op == XPathOperator.Gt || op == XPathOperator.Ge); XmlQueryType leftType = left.XmlType; XmlQueryType rightType = right.XmlType; if (_f.IsAnyType(left) || _f.IsAnyType(right)) { return _f.InvokeRelationalOperator(s_qilOperator[(int)op], left, right); } else if (leftType.IsNode && rightType.IsNode) { return CompareNodeSetAndNodeSet(op, left, right, XmlTypeCode.Double); } else if (leftType.IsNode) { XmlTypeCode compType = rightType.TypeCode == XmlTypeCode.Boolean ? XmlTypeCode.Boolean : XmlTypeCode.Double; return CompareNodeSetAndValue(op, /*nodeset:*/left, /*val:*/right, compType); } else if (rightType.IsNode) { XmlTypeCode compType = leftType.TypeCode == XmlTypeCode.Boolean ? XmlTypeCode.Boolean : XmlTypeCode.Double; op = InvertOp(op); return CompareNodeSetAndValue(op, /*nodeset:*/right, /*val:*/left, compType); } else { return CompareValues(op, left, right, XmlTypeCode.Double); } } private QilNode NegateOperator(XPathOperator op, QilNode left, QilNode right) { Debug.Assert(op == XPathOperator.UnaryMinus); Debug.Assert(right == null); return _f.Negate(_f.ConvertToNumber(left)); } private QilNode ArithmeticOperator(XPathOperator op, QilNode left, QilNode right) { left = _f.ConvertToNumber(left); right = _f.ConvertToNumber(right); switch (op) { case XPathOperator.Plus: return _f.Add(left, right); case XPathOperator.Minus: return _f.Subtract(left, right); case XPathOperator.Multiply: return _f.Multiply(left, right); case XPathOperator.Divide: return _f.Divide(left, right); case XPathOperator.Modulo: return _f.Modulo(left, right); default: Debug.Fail("Wrong operator type"); return null; } } private QilNode UnionOperator(XPathOperator op, QilNode left, QilNode right) { Debug.Assert(op == XPathOperator.Union); if (left == null) { return _f.EnsureNodeSet(right); } left = _f.EnsureNodeSet(left); right = _f.EnsureNodeSet(right); if (left.NodeType == QilNodeType.Sequence) { ((QilList)left).Add(right); return left; } else { return _f.Union(left, right); } } // also called by XPathPatternBuilder public static XmlNodeKindFlags AxisTypeMask(XmlNodeKindFlags inputTypeMask, XPathNodeType nodeType, XPathAxis xpathAxis) { return (XmlNodeKindFlags)( (int)inputTypeMask & (int)s_XPathNodeType2QilXmlNodeKind[(int)nodeType] & (int)s_XPathAxisMask[(int)xpathAxis] ); } private QilNode BuildAxisFilter(QilNode qilAxis, XPathAxis xpathAxis, XPathNodeType nodeType, string name, string nsUri) { XmlNodeKindFlags original = qilAxis.XmlType.NodeKinds; XmlNodeKindFlags required = AxisTypeMask(original, nodeType, xpathAxis); QilIterator itr; if (required == 0) { return _f.Sequence(); } else if (required == original) { } else { qilAxis = _f.Filter(itr = _f.For(qilAxis), _f.IsType(itr, T.NodeChoice(required))); qilAxis.XmlType = T.PrimeProduct(T.NodeChoice(required), qilAxis.XmlType.Cardinality); // Without code bellow IlGeneragion gives stack overflow exception for the following passage. //<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> // <xsl:template match="/"> // <xsl:value-of select="descendant::author/@id | comment()" /> // </xsl:template> //</xsl:stylesheet> if (qilAxis.NodeType == QilNodeType.Filter) { QilLoop filter = (QilLoop)qilAxis; filter.Body = _f.And(filter.Body, name != null && nsUri != null ? _f.Eq(_f.NameOf(itr), _f.QName(name, nsUri)) : // ns:bar || bar nsUri != null ? _f.Eq(_f.NamespaceUriOf(itr), _f.String(nsUri)) : // ns:* name != null ? _f.Eq(_f.LocalNameOf(itr), _f.String(name)) : // *:foo /*name == nsUri == null*/ _f.True() // * ); return filter; } } return _f.Filter(itr = _f.For(qilAxis), name != null && nsUri != null ? _f.Eq(_f.NameOf(itr), _f.QName(name, nsUri)) : // ns:bar || bar nsUri != null ? _f.Eq(_f.NamespaceUriOf(itr), _f.String(nsUri)) : // ns:* name != null ? _f.Eq(_f.LocalNameOf(itr), _f.String(name)) : // *:foo /*name == nsUri == null*/ _f.True() // * ); } // XmlNodeKindFlags from XPathNodeType private static XmlNodeKindFlags[] s_XPathNodeType2QilXmlNodeKind = { /*Root */ XmlNodeKindFlags.Document, /*Element */ XmlNodeKindFlags.Element, /*Attribute */ XmlNodeKindFlags.Attribute, /*Namespace */ XmlNodeKindFlags.Namespace, /*Text */ XmlNodeKindFlags.Text, /*SignificantWhitespace*/ XmlNodeKindFlags.Text, /*Whitespace */ XmlNodeKindFlags.Text, /*ProcessingInstruction*/ XmlNodeKindFlags.PI, /*Comment */ XmlNodeKindFlags.Comment, /*All */ XmlNodeKindFlags.Any }; private QilNode BuildAxis(XPathAxis xpathAxis, XPathNodeType nodeType, string nsUri, string name) { QilNode currentNode = GetCurrentNode(); QilNode qilAxis; switch (xpathAxis) { case XPathAxis.Ancestor: qilAxis = _f.Ancestor(currentNode); break; case XPathAxis.AncestorOrSelf: qilAxis = _f.AncestorOrSelf(currentNode); break; case XPathAxis.Attribute: qilAxis = _f.Content(currentNode); break; case XPathAxis.Child: qilAxis = _f.Content(currentNode); break; case XPathAxis.Descendant: qilAxis = _f.Descendant(currentNode); break; case XPathAxis.DescendantOrSelf: qilAxis = _f.DescendantOrSelf(currentNode); break; case XPathAxis.Following: qilAxis = _f.XPathFollowing(currentNode); break; case XPathAxis.FollowingSibling: qilAxis = _f.FollowingSibling(currentNode); break; case XPathAxis.Namespace: qilAxis = _f.XPathNamespace(currentNode); break; case XPathAxis.Parent: qilAxis = _f.Parent(currentNode); break; case XPathAxis.Preceding: qilAxis = _f.XPathPreceding(currentNode); break; case XPathAxis.PrecedingSibling: qilAxis = _f.PrecedingSibling(currentNode); break; case XPathAxis.Self: qilAxis = (currentNode); break; // Can be done using BuildAxisFilter() but f.Root() sets wrong XmlNodeKindFlags case XPathAxis.Root: return _f.Root(currentNode); default: qilAxis = null; Debug.Fail("Invalid EnumValue 'XPathAxis'"); break; } QilNode result = BuildAxisFilter(qilAxis, xpathAxis, nodeType, name, nsUri); if ( xpathAxis == XPathAxis.Ancestor || xpathAxis == XPathAxis.Preceding || xpathAxis == XPathAxis.AncestorOrSelf || xpathAxis == XPathAxis.PrecedingSibling ) { result = _f.BaseFactory.DocOrderDistinct(result); // To make grouping operator NOP we should always return path expressions in DOD. // I can't use Pattern factory here becasue Predicate() depends on fact that DOD() is // outmost node in reverse steps } return result; } public virtual QilNode Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string prefix, string name) { string nsUri = prefix == null ? null : _environment.ResolvePrefix(prefix); return BuildAxis(xpathAxis, nodeType, nsUri, name); } // "left/right" public virtual QilNode JoinStep(QilNode left, QilNode right) { _f.CheckNodeSet(right); QilIterator leftIt = _f.For(_f.EnsureNodeSet(left)); // in XPath 1.0 step is always nodetest and as a result it can't contain last(). right = _fixupVisitor.Fixup(right, /*current:*/leftIt, /*last:*/null); numFixupCurrent -= _fixupVisitor.numCurrent; numFixupPosition -= _fixupVisitor.numPosition; numFixupLast -= _fixupVisitor.numLast; return _f.DocOrderDistinct(_f.Loop(leftIt, right)); } // "nodeset[predicate]" // XPath spec $3.3 (para 5) public virtual QilNode Predicate(QilNode nodeset, QilNode predicate, bool isReverseStep) { if (isReverseStep) { Debug.Assert(nodeset.NodeType == QilNodeType.DocOrderDistinct, "ReverseAxe in Qil is actually reverse and we compile them here in builder by wrapping to DocOrderDistinct()" ); // The trick here is that we unwarp it back, compile as regular predicate and wrap again. // this way this wat we hold invariant that path expresion are always DOD and make predicates on reverse axe // work as specified in XPath 2.0 FS: http://www.w3.org/TR/xquery-semantics/#id-axis-steps nodeset = ((QilUnary)nodeset).Child; } predicate = PredicateToBoolean(predicate, _f, this); return BuildOnePredicate(nodeset, predicate, isReverseStep, _f, _fixupVisitor, ref numFixupCurrent, ref numFixupPosition, ref numFixupLast); } //also used by XPathPatternBuilder public static QilNode PredicateToBoolean(QilNode predicate, XPathQilFactory f, IXPathEnvironment env) { // Prepocess predicate: if (predicate is number) then predicate := (position() == predicate) if (!f.IsAnyType(predicate)) { if (predicate.XmlType.TypeCode == XmlTypeCode.Double) { predicate = f.Eq(env.GetPosition(), predicate); } else { predicate = f.ConvertToBoolean(predicate); } } else { QilIterator i; predicate = f.Loop(i = f.Let(predicate), f.Conditional(f.IsType(i, T.Double), f.Eq(env.GetPosition(), f.TypeAssert(i, T.DoubleX)), f.ConvertToBoolean(i) ) ); } return predicate; } //also used by XPathPatternBuilder public static QilNode BuildOnePredicate(QilNode nodeset, QilNode predicate, bool isReverseStep, XPathQilFactory f, FixupVisitor fixupVisitor, ref int numFixupCurrent, ref int numFixupPosition, ref int numFixupLast) { nodeset = f.EnsureNodeSet(nodeset); // Mirgeing nodeset and predicate: // 1. Predicate contains 0 last() : // for $i in nodeset // where predicate // return $i // Note: Currently we are keepeing old output to minimize diff. // 2. Predicate contains 1 last() // let $cach := nodeset return // for $i in $cach // where predicate(length($cach)) // return $i // Suggestion: This is a little optimisation we can do or don't do. // 3. Predicate contains 2+ last() // let $cash := nodeset return // let $size := length($cash) return // for $i in $cash // where predicate($size) // return $i QilNode result; if (numFixupLast != 0 && fixupVisitor.CountUnfixedLast(predicate) != 0) { // this subtree has unfixed last() nodes QilIterator cash = f.Let(nodeset); QilIterator size = f.Let(f.XsltConvert(f.Length(cash), T.DoubleX)); QilIterator it = f.For(cash); predicate = fixupVisitor.Fixup(predicate, /*current:*/it, /*last:*/size); numFixupCurrent -= fixupVisitor.numCurrent; numFixupPosition -= fixupVisitor.numPosition; numFixupLast -= fixupVisitor.numLast; result = f.Loop(cash, f.Loop(size, f.Filter(it, predicate))); } else { QilIterator it = f.For(nodeset); predicate = fixupVisitor.Fixup(predicate, /*current:*/it, /*last:*/null); numFixupCurrent -= fixupVisitor.numCurrent; numFixupPosition -= fixupVisitor.numPosition; numFixupLast -= fixupVisitor.numLast; result = f.Filter(it, predicate); } if (isReverseStep) { result = f.DocOrderDistinct(result); } return result; } public virtual QilNode Variable(string prefix, string name) { return _environment.ResolveVariable(prefix, name); } public virtual QilNode Function(string prefix, string name, IList<QilNode> args) { Debug.Assert(!args.IsReadOnly, "Writable collection expected"); if (prefix.Length == 0) { FunctionInfo func; if (FunctionTable.TryGetValue(name, out func)) { func.CastArguments(args, name, _f); switch (func.id) { case FuncId.Not: return _f.Not(args[0]); case FuncId.Last: return GetLastPosition(); case FuncId.Position: return GetCurrentPosition(); case FuncId.Count: return _f.XsltConvert(_f.Length(_f.DocOrderDistinct(args[0])), T.DoubleX); case FuncId.LocalName: return args.Count == 0 ? _f.LocalNameOf(GetCurrentNode()) : LocalNameOfFirstNode(args[0]); case FuncId.NamespaceUri: return args.Count == 0 ? _f.NamespaceUriOf(GetCurrentNode()) : NamespaceOfFirstNode(args[0]); case FuncId.Name: return args.Count == 0 ? NameOf(GetCurrentNode()) : NameOfFirstNode(args[0]); case FuncId.String: return args.Count == 0 ? _f.XPathNodeValue(GetCurrentNode()) : _f.ConvertToString(args[0]); case FuncId.Number: return args.Count == 0 ? _f.XsltConvert(_f.XPathNodeValue(GetCurrentNode()), T.DoubleX) : _f.ConvertToNumber(args[0]); case FuncId.Boolean: return _f.ConvertToBoolean(args[0]); case FuncId.True: return _f.True(); case FuncId.False: return _f.False(); case FuncId.Id: return _f.DocOrderDistinct(_f.Id(GetCurrentNode(), args[0])); case FuncId.Concat: return _f.StrConcat(args); case FuncId.StartsWith: return _f.InvokeStartsWith(args[0], args[1]); case FuncId.Contains: return _f.InvokeContains(args[0], args[1]); case FuncId.SubstringBefore: return _f.InvokeSubstringBefore(args[0], args[1]); case FuncId.SubstringAfter: return _f.InvokeSubstringAfter(args[0], args[1]); case FuncId.Substring: return args.Count == 2 ? _f.InvokeSubstring(args[0], args[1]) : _f.InvokeSubstring(args[0], args[1], args[2]); case FuncId.StringLength: return _f.XsltConvert(_f.StrLength(args.Count == 0 ? _f.XPathNodeValue(GetCurrentNode()) : args[0]), T.DoubleX); case FuncId.Normalize: return _f.InvokeNormalizeSpace(args.Count == 0 ? _f.XPathNodeValue(GetCurrentNode()) : args[0]); case FuncId.Translate: return _f.InvokeTranslate(args[0], args[1], args[2]); case FuncId.Lang: return _f.InvokeLang(args[0], GetCurrentNode()); case FuncId.Sum: return Sum(_f.DocOrderDistinct(args[0])); case FuncId.Floor: return _f.InvokeFloor(args[0]); case FuncId.Ceiling: return _f.InvokeCeiling(args[0]); case FuncId.Round: return _f.InvokeRound(args[0]); default: Debug.Fail(func.id + " is present in the function table, but absent from the switch"); return null; } } } return _environment.ResolveFunction(prefix, name, args, (IFocus)this); } private QilNode LocalNameOfFirstNode(QilNode arg) { _f.CheckNodeSet(arg); if (arg.XmlType.IsSingleton) { return _f.LocalNameOf(arg); } else { QilIterator i; return _f.StrConcat(_f.Loop(i = _f.FirstNode(arg), _f.LocalNameOf(i))); } } private QilNode NamespaceOfFirstNode(QilNode arg) { _f.CheckNodeSet(arg); if (arg.XmlType.IsSingleton) { return _f.NamespaceUriOf(arg); } else { QilIterator i; return _f.StrConcat(_f.Loop(i = _f.FirstNode(arg), _f.NamespaceUriOf(i))); } } private QilNode NameOf(QilNode arg) { _f.CheckNodeNotRtf(arg); // We may want to introduce a new QIL node that returns a string. if (arg is QilIterator) { QilIterator p, ln; return _f.Loop(p = _f.Let(_f.PrefixOf(arg)), _f.Loop(ln = _f.Let(_f.LocalNameOf(arg)), _f.Conditional(_f.Eq(_f.StrLength(p), _f.Int32(0)), ln, _f.StrConcat(p, _f.String(":"), ln) ))); } else { QilIterator let = _f.Let(arg); return _f.Loop(let, /*recursion:*/NameOf(let)); } } private QilNode NameOfFirstNode(QilNode arg) { _f.CheckNodeSet(arg); if (arg.XmlType.IsSingleton) { return NameOf(arg); } else { QilIterator i; return _f.StrConcat(_f.Loop(i = _f.FirstNode(arg), NameOf(i))); } } private QilNode Sum(QilNode arg) { _f.CheckNodeSet(arg); QilIterator i; return _f.Sum(_f.Sequence(_f.Double(0d), _f.Loop(i = _f.For(arg), _f.ConvertToNumber(i)))); } private enum XPathOperatorGroup { Unknown, Logical, Equality, Relational, Arithmetic, Negate, Union, } private static XPathOperatorGroup[] s_operatorGroup = { /*Unknown */ XPathOperatorGroup.Unknown , /*Or */ XPathOperatorGroup.Logical , /*And */ XPathOperatorGroup.Logical , /*Eq */ XPathOperatorGroup.Equality , /*Ne */ XPathOperatorGroup.Equality , /*Lt */ XPathOperatorGroup.Relational, /*Le */ XPathOperatorGroup.Relational, /*Gt */ XPathOperatorGroup.Relational, /*Ge */ XPathOperatorGroup.Relational, /*Plus */ XPathOperatorGroup.Arithmetic, /*Minus */ XPathOperatorGroup.Arithmetic, /*Multiply */ XPathOperatorGroup.Arithmetic, /*Divide */ XPathOperatorGroup.Arithmetic, /*Modulo */ XPathOperatorGroup.Arithmetic, /*UnaryMinus*/ XPathOperatorGroup.Negate , /*Union */ XPathOperatorGroup.Union , }; private static QilNodeType[] s_qilOperator = { /*Unknown */ QilNodeType.Unknown , /*Or */ QilNodeType.Or , /*And */ QilNodeType.And , /*Eq */ QilNodeType.Eq , /*Ne */ QilNodeType.Ne , /*Lt */ QilNodeType.Lt , /*Le */ QilNodeType.Le , /*Gt */ QilNodeType.Gt , /*Ge */ QilNodeType.Ge , /*Plus */ QilNodeType.Add , /*Minus */ QilNodeType.Subtract, /*Multiply */ QilNodeType.Multiply, /*Divide */ QilNodeType.Divide , /*Modulo */ QilNodeType.Modulo , /*UnaryMinus */ QilNodeType.Negate , /*Union */ QilNodeType.Sequence, }; // XmlNodeType(s) of nodes by XPathAxis private static XmlNodeKindFlags[] s_XPathAxisMask = { /*Unknown */ XmlNodeKindFlags.None, /*Ancestor */ XmlNodeKindFlags.Element | XmlNodeKindFlags.Document, /*AncestorOrSelf */ XmlNodeKindFlags.Any, /*Attribute */ XmlNodeKindFlags.Attribute, /*Child */ XmlNodeKindFlags.Content, /*Descendant */ XmlNodeKindFlags.Content, /*DescendantOrSelf*/ XmlNodeKindFlags.Any, /*Following */ XmlNodeKindFlags.Content, /*FollowingSibling*/ XmlNodeKindFlags.Content, /*Namespace */ XmlNodeKindFlags.Namespace, /*Parent */ XmlNodeKindFlags.Element | XmlNodeKindFlags.Document, /*Preceding */ XmlNodeKindFlags.Content, /*PrecedingSibling*/ XmlNodeKindFlags.Content, /*Self */ XmlNodeKindFlags.Any, /*Root */ XmlNodeKindFlags.Document, }; // ---------------------------------------------------------------- internal enum FuncId { Last = 0, Position, Count, LocalName, NamespaceUri, Name, String, Number, Boolean, True, False, Not, Id, Concat, StartsWith, Contains, SubstringBefore, SubstringAfter, Substring, StringLength, Normalize, Translate, Lang, Sum, Floor, Ceiling, Round }; public static readonly XmlTypeCode[] argAny = { XmlTypeCode.Item }; public static readonly XmlTypeCode[] argNodeSet = { XmlTypeCode.Node }; public static readonly XmlTypeCode[] argBoolean = { XmlTypeCode.Boolean }; public static readonly XmlTypeCode[] argDouble = { XmlTypeCode.Double }; public static readonly XmlTypeCode[] argString = { XmlTypeCode.String }; public static readonly XmlTypeCode[] argString2 = { XmlTypeCode.String, XmlTypeCode.String }; public static readonly XmlTypeCode[] argString3 = { XmlTypeCode.String, XmlTypeCode.String, XmlTypeCode.String }; public static readonly XmlTypeCode[] argFnSubstr = { XmlTypeCode.String, XmlTypeCode.Double, XmlTypeCode.Double }; public static Dictionary<string, FunctionInfo> FunctionTable = CreateFunctionTable(); private static Dictionary<string, FunctionInfo> CreateFunctionTable() { Dictionary<string, FunctionInfo> table = new Dictionary<string, FunctionInfo>(36); table.Add("last", new FunctionInfo(FuncId.Last, 0, 0, null)); table.Add("position", new FunctionInfo(FuncId.Position, 0, 0, null)); table.Add("name", new FunctionInfo(FuncId.Name, 0, 1, argNodeSet)); table.Add("namespace-uri", new FunctionInfo(FuncId.NamespaceUri, 0, 1, argNodeSet)); table.Add("local-name", new FunctionInfo(FuncId.LocalName, 0, 1, argNodeSet)); table.Add("count", new FunctionInfo(FuncId.Count, 1, 1, argNodeSet)); table.Add("id", new FunctionInfo(FuncId.Id, 1, 1, argAny)); table.Add("string", new FunctionInfo(FuncId.String, 0, 1, argAny)); table.Add("concat", new FunctionInfo(FuncId.Concat, 2, FunctionInfo.Infinity, null)); table.Add("starts-with", new FunctionInfo(FuncId.StartsWith, 2, 2, argString2)); table.Add("contains", new FunctionInfo(FuncId.Contains, 2, 2, argString2)); table.Add("substring-before", new FunctionInfo(FuncId.SubstringBefore, 2, 2, argString2)); table.Add("substring-after", new FunctionInfo(FuncId.SubstringAfter, 2, 2, argString2)); table.Add("substring", new FunctionInfo(FuncId.Substring, 2, 3, argFnSubstr)); table.Add("string-length", new FunctionInfo(FuncId.StringLength, 0, 1, argString)); table.Add("normalize-space", new FunctionInfo(FuncId.Normalize, 0, 1, argString)); table.Add("translate", new FunctionInfo(FuncId.Translate, 3, 3, argString3)); table.Add("boolean", new FunctionInfo(FuncId.Boolean, 1, 1, argAny)); table.Add("not", new FunctionInfo(FuncId.Not, 1, 1, argBoolean)); table.Add("true", new FunctionInfo(FuncId.True, 0, 0, null)); table.Add("false", new FunctionInfo(FuncId.False, 0, 0, null)); table.Add("lang", new FunctionInfo(FuncId.Lang, 1, 1, argString)); table.Add("number", new FunctionInfo(FuncId.Number, 0, 1, argAny)); table.Add("sum", new FunctionInfo(FuncId.Sum, 1, 1, argNodeSet)); table.Add("floor", new FunctionInfo(FuncId.Floor, 1, 1, argDouble)); table.Add("ceiling", new FunctionInfo(FuncId.Ceiling, 1, 1, argDouble)); table.Add("round", new FunctionInfo(FuncId.Round, 1, 1, argDouble)); return table; } public static bool IsFunctionAvailable(string localName, string nsUri) { if (nsUri.Length != 0) { return false; } return FunctionTable.ContainsKey(localName); } internal class FixupVisitor : QilReplaceVisitor { private new QilPatternFactory f; private QilNode _fixupCurrent, _fixupPosition, _fixupLast; // fixup nodes we are replacing private QilIterator _current; private QilNode _last; // expressions we are using to replace fixupNodes private bool _justCount; // Don't change tree, just count private IXPathEnvironment _environment; // temp solution public int numCurrent, numPosition, numLast; // here we are counting all replacements we have made public FixupVisitor(QilPatternFactory f, QilNode fixupCurrent, QilNode fixupPosition, QilNode fixupLast) : base(f.BaseFactory) { this.f = f; _fixupCurrent = fixupCurrent; _fixupPosition = fixupPosition; _fixupLast = fixupLast; } public QilNode Fixup(QilNode inExpr, QilIterator current, QilNode last) { QilDepthChecker.Check(inExpr); _current = current; _last = last; Debug.Assert(current != null); _justCount = false; _environment = null; numCurrent = numPosition = numLast = 0; inExpr = VisitAssumeReference(inExpr); #if StopMaskOptimisation SetStopVisitMark(inExpr, /*stop*/true); #endif return inExpr; } public QilNode Fixup(QilNode inExpr, IXPathEnvironment environment) { Debug.Assert(environment != null); QilDepthChecker.Check(inExpr); _justCount = false; _current = null; _environment = environment; numCurrent = numPosition = numLast = 0; inExpr = VisitAssumeReference(inExpr); #if StopMaskOptimisation // Don't need //SetStopVisitMark(inExpr, /*stop*/true); #endif return inExpr; } public int CountUnfixedLast(QilNode inExpr) { _justCount = true; numCurrent = numPosition = numLast = 0; VisitAssumeReference(inExpr); return numLast; } protected override QilNode VisitUnknown(QilNode unknown) { Debug.Assert(unknown.NodeType == QilNodeType.Unknown); if (unknown == _fixupCurrent) { numCurrent++; if (!_justCount) { if (_environment != null) { unknown = _environment.GetCurrent(); } else if (_current != null) { unknown = _current; } } } else if (unknown == _fixupPosition) { numPosition++; if (!_justCount) { if (_environment != null) { unknown = _environment.GetPosition(); } else if (_current != null) { // position can be in predicate only and in predicate current olways an iterator unknown = f.XsltConvert(f.PositionOf((QilIterator)_current), T.DoubleX); } } } else if (unknown == _fixupLast) { numLast++; if (!_justCount) { if (_environment != null) { unknown = _environment.GetLast(); } else if (_current != null) { Debug.Assert(_last != null); unknown = _last; } } } Debug.Assert(unknown != null); return unknown; } #if StopMaskOptimisation // This optimisation marks subtrees that was fixed already and prevents FixupVisitor from // visiting them again. The logic is brokken, because when unfixed tree is added inside fixed one // it never fixed anymore. // This happens in all cortasian productions now. // Excample "a/b=c". 'c' is added inside 'b' // I belive some optimisation is posible and would be nice to have. // We may change the way we generating cortasian product. protected override QilNode Visit(QilNode n) { if (GetStopVisitMark(n)) { // Optimisation: // This subtree was fixed already. No need to go inside it. if (! justCount) { SetStopVisitMark(n, /*stop*/false); // We clean this annotation } return n; } return base.Visit(n); } void SetStopVisitMark(QilNode n, bool stop) { if (n.Type != QilNodeType.For && n.Type != QilNodeType.Let) { XsltAnnotation.Write(n)[0] = (stop ? /*any object*/fixupCurrent : null); } else { // we shouldn't alter annotation of "reference" nodes (Iterators, Functions, ...) } } bool GetStopVisitMark(QilNode n) { return XsltAnnotation.Write(n)[0] != null; } #endif } internal class FunctionInfo<T> { public T id; public int minArgs; public int maxArgs; public XmlTypeCode[] argTypes; public const int Infinity = int.MaxValue; public FunctionInfo(T id, int minArgs, int maxArgs, XmlTypeCode[] argTypes) { Debug.Assert(maxArgs == 0 || maxArgs == Infinity || argTypes != null && argTypes.Length == maxArgs); this.id = id; this.minArgs = minArgs; this.maxArgs = maxArgs; this.argTypes = argTypes; } public static void CheckArity(int minArgs, int maxArgs, string name, int numArgs) { if (minArgs <= numArgs && numArgs <= maxArgs) { return; } // Possible cases: // [0, 0], [1, 1], [2, 2], [3, 3] // [0, 1], [1, 2], [2, 3], [2, +inf] // [1, 3], [2, 4] string resId; if (minArgs == maxArgs) { resId = SR.XPath_NArgsExpected; } else { if (maxArgs == minArgs + 1) { resId = SR.XPath_NOrMArgsExpected; } else if (numArgs < minArgs) { resId = SR.XPath_AtLeastNArgsExpected; } else { // This case is impossible for standard XPath/XSLT functions Debug.Assert(numArgs > maxArgs); resId = SR.XPath_AtMostMArgsExpected; } } throw new XPathCompileException(resId, name, minArgs.ToString(CultureInfo.InvariantCulture), maxArgs.ToString(CultureInfo.InvariantCulture)); } public void CastArguments(IList<QilNode> args, string name, XPathQilFactory f) { CheckArity(this.minArgs, this.maxArgs, name, args.Count); // Convert arguments to the appropriate types if (maxArgs == Infinity) { // Special case for concat() function for (int i = 0; i < args.Count; i++) { args[i] = f.ConvertToType(XmlTypeCode.String, args[i]); } } else { for (int i = 0; i < args.Count; i++) { if (argTypes[i] == XmlTypeCode.Node && f.CannotBeNodeSet(args[i])) { throw new XPathCompileException(SR.XPath_NodeSetArgumentExpected, name, (i + 1).ToString(CultureInfo.InvariantCulture)); } args[i] = f.ConvertToType(argTypes[i], args[i]); } } } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DynamiteContentOrganizer.EventReceiver.cs" company="GSoft @2014"> // Dynamite Example ContentOrganizer // </copyright> // ----------------------------------------------------------------------- namespace Dynamite.Example.ContentOrganizer.Features.DynamiteContentOrganizer { using System.Collections.Generic; using System.Runtime.InteropServices; using Dynamite.Example.ContentOrganizer.Constants; using Dynamite.Example.ContentOrganizer.ContentOrganizer.Rules; using Dynamite.Example.ContentOrganizer.Unity; using GSoft.Dynamite.Taxonomy; using GSoft.Dynamite.Utils; using Microsoft.Practices.Unity; using Microsoft.SharePoint; using Microsoft.SharePoint.Taxonomy; /// <summary> /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade. /// </summary> /// <remarks> /// The GUID attached to this class may be used during packaging and should not be modified. /// </remarks> [Guid("3d4b4c32-7174-48d9-b653-d59a15602248")] public class DynamiteContentOrganizerEventReceiver : SPFeatureReceiver { #region Content Types definition /// <summary> /// Content Organizer Example fields /// </summary> private readonly ICollection<FieldInfo> contentOrganizerExampleFields = new List<FieldInfo>() { MyFields.MyTaxField, MyFields.MyTaxFieldTaxHT, MyFields.MyDocumentId, MyFields.MyIndexDate }; #endregion #region Dynamite framework helpers /// <summary> /// The content type helper. /// </summary> private ContentTypeHelper contentTypeHelper; /// <summary> /// The taxonomy helper. /// </summary> private TaxonomyHelper taxonomyHelper; /// <summary> /// The list helper. /// </summary> private ListHelper listHelper; /// <summary> /// The content organizer helper. /// </summary> private ContentOrganizerHelper contentOrganizerHelper; /// <summary> /// My custom rule /// </summary> private MyCustomRule myCustomRule; #endregion /// <summary> /// Feature activation /// </summary> /// <param name="properties">The properties.</param>s public override void FeatureActivated(SPFeatureReceiverProperties properties) { this.ResolveDependencies(); var web = properties.Feature.Parent as SPWeb; if (web != null) { // Configure site columns this.ConfigureSiteColumns(web); // Create Example Content Type this.CreateExampleContentType(web.ContentTypes); // Add destination list this.SetupDestinationList(web, MyUrlSettings.FinalRepository); // Configure Drop Off Library this.SetupDropOffLibrary(web); // Create Custom router this.CreateRouters(web); // Create Custom rules this.CreateCustomRules(web); } } /// <summary> /// Feature deactivating event /// </summary> /// <param name="properties">The properties.</param> public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { this.ResolveDependencies(); var web = properties.Feature.Parent as SPWeb; if (web != null) { // Delete Custom Rules this.DeleteCustomRules(web); // Delete Custom Routers this.DeleteRouters(web); } } /// <summary> /// Configures web sites columns /// </summary> /// <param name="web">The web</param> private void ConfigureSiteColumns(SPWeb web) { // Map terms to site columns this.taxonomyHelper.AssignTermSetToSiteColumn(web, MyFields.MyTaxField.ID, MyTaxonomySettings.TermStoreGroupName, MyTaxonomySettings.MyTaxonomyFieldTermSetValue, null); // Set default values var confidentialityTaxonomyField = web.Fields.GetFieldByInternalName(MyFields.MyTaxField.InternalName) as TaxonomyField; this.taxonomyHelper.SetDefaultTaxonomyValue(web, confidentialityTaxonomyField, MyTaxonomySettings.TermStoreGroupName, MyTaxonomySettings.MyTaxonomyFieldTermSetValue, MyTaxonomySettings.MyTaxonomyFieldTermValue); } /// <summary> /// Creates the Example Document Content Type /// </summary> /// <param name="collection">The collection the content type will be added to.</param> private void CreateExampleContentType(SPContentTypeCollection collection) { var contentType = this.contentTypeHelper.EnsureContentType( collection, MyContentTypes.ContentOrganizerExampleContentType, "Content Organizer Example Content Type"); this.contentTypeHelper.EnsureFieldInContentType(contentType, this.contentOrganizerExampleFields); contentType.Group = "Dynamite"; contentType.Description = "Content Organizer Example Content Type"; contentType.Update(true); this.taxonomyHelper.EnsureTaxonomyEventReceivers(contentType.EventReceivers); } /// <summary> /// Resolve dependencies for Dynamite Helpers /// </summary> private void ResolveDependencies() { this.contentTypeHelper = AppContainer.Current.Resolve<ContentTypeHelper>(); this.taxonomyHelper = AppContainer.Current.Resolve<TaxonomyHelper>(); this.listHelper = AppContainer.Current.Resolve<ListHelper>(); this.contentOrganizerHelper = AppContainer.Current.Resolve<ContentOrganizerHelper>(); this.myCustomRule = AppContainer.Current.Resolve<MyCustomRule>(); } /// <summary> /// Setup lists on the web site /// </summary> /// <param name="web">The web</param> /// <param name="listUrl">List url</param> private void SetupDestinationList(SPWeb web, string listUrl) { var listTemplate = web.ListTemplates["Document Library"]; var list = this.listHelper.EnsureList( web, listUrl, "Destination Library for the content organizer", listTemplate); this.listHelper.AddContentType(list, MyContentTypes.ContentOrganizerExampleContentType); var indexDateField = list.Fields[MyFields.MyIndexDate.ID]; indexDateField.ShowInListSettings = true; indexDateField.ShowInDisplayForm = true; indexDateField.ShowInEditForm = false; indexDateField.ShowInNewForm = false; indexDateField.Update(); } /// <summary> /// Setup the Drop Off Library /// </summary> /// <param name="web">The web.</param> private void SetupDropOffLibrary(SPWeb web) { var list = this.contentOrganizerHelper.GetDropOffLibrary(web); this.listHelper.AddContentType(list, MyContentTypes.ContentOrganizerExampleContentType); var indexDateField = list.Fields[MyFields.MyIndexDate.ID]; indexDateField.ShowInListSettings = false; indexDateField.ShowInDisplayForm = true; indexDateField.ShowInEditForm = false; indexDateField.ShowInNewForm = false; indexDateField.Update(); } /// <summary> /// Creates custom content organizer routers /// </summary> /// <param name="web">The web.</param> private void CreateRouters(SPWeb web) { this.contentOrganizerHelper.CreateCustomRouter(web, MyContentOrganizerSettings.MyRouter1Name, MyContentOrganizerSettings.CustomRoutersAssemblyName, MyContentOrganizerSettings.MyRouter1ClassName); } /// <summary> /// Delete all custom routers /// </summary> /// <param name="web">The web</param> private void DeleteRouters(SPWeb web) { this.contentOrganizerHelper.DeleteCustomRouter(web, MyContentOrganizerSettings.MyRouter1Name); } /// <summary> /// Delete custom Content Organizer Rules /// </summary> /// <param name="web">The web.</param> private void DeleteCustomRules(SPWeb web) { this.contentOrganizerHelper.DeleteCustomRule(web, this.myCustomRule.RuleName); } /// <summary> /// Creates custom Content Organizer rules /// </summary> /// <param name="web">The web.</param> private void CreateCustomRules(SPWeb web) { var destinationList = this.listHelper.GetListByRootFolderUrl(web, MyUrlSettings.FinalRepository); // Add "My Custom Rule" this.contentOrganizerHelper.CreateCustomRule( web, this.myCustomRule.RuleName, this.myCustomRule.RuleDescription, "Content Organizer Example Content Type", this.myCustomRule.GetXmlConditions(web), 1, false, destinationList.RootFolder.ServerRelativeUrl, MyContentOrganizerSettings.MyRouter1Name); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Faculties Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KSFDataSet : EduHubDataSet<KSF> { /// <inheritdoc /> public override string Name { get { return "KSF"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KSFDataSet(EduHubContext Context) : base(Context) { Index_COORDINATOR = new Lazy<NullDictionary<string, IReadOnlyList<KSF>>>(() => this.ToGroupedNullDictionary(i => i.COORDINATOR)); Index_KSFKEY = new Lazy<Dictionary<string, KSF>>(() => this.ToDictionary(i => i.KSFKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KSF" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KSF" /> fields for each CSV column header</returns> internal override Action<KSF, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KSF, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KSFKEY": mapper[i] = (e, v) => e.KSFKEY = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "COORDINATOR": mapper[i] = (e, v) => e.COORDINATOR = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KSF" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KSF" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KSF" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KSF}"/> of entities</returns> internal override IEnumerable<KSF> ApplyDeltaEntities(IEnumerable<KSF> Entities, List<KSF> DeltaEntities) { HashSet<string> Index_KSFKEY = new HashSet<string>(DeltaEntities.Select(i => i.KSFKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KSFKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KSFKEY.Remove(entity.KSFKEY); if (entity.KSFKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<KSF>>> Index_COORDINATOR; private Lazy<Dictionary<string, KSF>> Index_KSFKEY; #endregion #region Index Methods /// <summary> /// Find KSF by COORDINATOR field /// </summary> /// <param name="COORDINATOR">COORDINATOR value used to find KSF</param> /// <returns>List of related KSF entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KSF> FindByCOORDINATOR(string COORDINATOR) { return Index_COORDINATOR.Value[COORDINATOR]; } /// <summary> /// Attempt to find KSF by COORDINATOR field /// </summary> /// <param name="COORDINATOR">COORDINATOR value used to find KSF</param> /// <param name="Value">List of related KSF entities</param> /// <returns>True if the list of related KSF entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCOORDINATOR(string COORDINATOR, out IReadOnlyList<KSF> Value) { return Index_COORDINATOR.Value.TryGetValue(COORDINATOR, out Value); } /// <summary> /// Attempt to find KSF by COORDINATOR field /// </summary> /// <param name="COORDINATOR">COORDINATOR value used to find KSF</param> /// <returns>List of related KSF entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KSF> TryFindByCOORDINATOR(string COORDINATOR) { IReadOnlyList<KSF> value; if (Index_COORDINATOR.Value.TryGetValue(COORDINATOR, out value)) { return value; } else { return null; } } /// <summary> /// Find KSF by KSFKEY field /// </summary> /// <param name="KSFKEY">KSFKEY value used to find KSF</param> /// <returns>Related KSF entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KSF FindByKSFKEY(string KSFKEY) { return Index_KSFKEY.Value[KSFKEY]; } /// <summary> /// Attempt to find KSF by KSFKEY field /// </summary> /// <param name="KSFKEY">KSFKEY value used to find KSF</param> /// <param name="Value">Related KSF entity</param> /// <returns>True if the related KSF entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKSFKEY(string KSFKEY, out KSF Value) { return Index_KSFKEY.Value.TryGetValue(KSFKEY, out Value); } /// <summary> /// Attempt to find KSF by KSFKEY field /// </summary> /// <param name="KSFKEY">KSFKEY value used to find KSF</param> /// <returns>Related KSF entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KSF TryFindByKSFKEY(string KSFKEY) { KSF value; if (Index_KSFKEY.Value.TryGetValue(KSFKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KSF table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KSF]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KSF]( [KSFKEY] varchar(10) NOT NULL, [DESCRIPTION] varchar(30) NULL, [COORDINATOR] varchar(4) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KSF_Index_KSFKEY] PRIMARY KEY CLUSTERED ( [KSFKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KSF_Index_COORDINATOR] ON [dbo].[KSF] ( [COORDINATOR] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KSF]') AND name = N'KSF_Index_COORDINATOR') ALTER INDEX [KSF_Index_COORDINATOR] ON [dbo].[KSF] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KSF]') AND name = N'KSF_Index_COORDINATOR') ALTER INDEX [KSF_Index_COORDINATOR] ON [dbo].[KSF] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KSF"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KSF"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KSF> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KSFKEY = new List<string>(); foreach (var entity in Entities) { Index_KSFKEY.Add(entity.KSFKEY); } builder.AppendLine("DELETE [dbo].[KSF] WHERE"); // Index_KSFKEY builder.Append("[KSFKEY] IN ("); for (int index = 0; index < Index_KSFKEY.Count; index++) { if (index != 0) builder.Append(", "); // KSFKEY var parameterKSFKEY = $"@p{parameterIndex++}"; builder.Append(parameterKSFKEY); command.Parameters.Add(parameterKSFKEY, SqlDbType.VarChar, 10).Value = Index_KSFKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KSF data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KSF data set</returns> public override EduHubDataSetDataReader<KSF> GetDataSetDataReader() { return new KSFDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KSF data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KSF data set</returns> public override EduHubDataSetDataReader<KSF> GetDataSetDataReader(List<KSF> Entities) { return new KSFDataReader(new EduHubDataSetLoadedReader<KSF>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KSFDataReader : EduHubDataSetDataReader<KSF> { public KSFDataReader(IEduHubDataSetReader<KSF> Reader) : base (Reader) { } public override int FieldCount { get { return 6; } } public override object GetValue(int i) { switch (i) { case 0: // KSFKEY return Current.KSFKEY; case 1: // DESCRIPTION return Current.DESCRIPTION; case 2: // COORDINATOR return Current.COORDINATOR; case 3: // LW_DATE return Current.LW_DATE; case 4: // LW_TIME return Current.LW_TIME; case 5: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DESCRIPTION return Current.DESCRIPTION == null; case 2: // COORDINATOR return Current.COORDINATOR == null; case 3: // LW_DATE return Current.LW_DATE == null; case 4: // LW_TIME return Current.LW_TIME == null; case 5: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KSFKEY return "KSFKEY"; case 1: // DESCRIPTION return "DESCRIPTION"; case 2: // COORDINATOR return "COORDINATOR"; case 3: // LW_DATE return "LW_DATE"; case 4: // LW_TIME return "LW_TIME"; case 5: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KSFKEY": return 0; case "DESCRIPTION": return 1; case "COORDINATOR": return 2; case "LW_DATE": return 3; case "LW_TIME": return 4; case "LW_USER": return 5; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #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; /// <summary> /// Convert.ToUInt32(String) /// </summary> public class ConvertToUInt3217 { public static int Main() { ConvertToUInt3217 convertToUInt3217 = new ConvertToUInt3217(); TestLibrary.TestFramework.BeginTestCase("ConvertToUInt3217"); if (convertToUInt3217.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert to UInt32 from string 1"); try { string strVal = UInt32.MaxValue.ToString(); uint uintVal = Convert.ToUInt32(strVal); if (uintVal != UInt32.MaxValue) { TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Convert to UInt32 from string 2"); try { string strVal = UInt32.MinValue.ToString(); uint uintVal = Convert.ToUInt32(strVal); if (uintVal != UInt32.MinValue) { TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Convert to UInt32 from string 3"); try { string strVal = "-" + UInt32.MinValue.ToString(); uint uintVal = Convert.ToUInt32(strVal); if (uintVal != UInt32.MinValue) { TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert to UInt32 from string 4"); try { uint intVal = (UInt32)this.GetInt32(0, Int32.MaxValue) + (UInt32)this.GetInt32(0, Int32.MaxValue); string strVal = "+" + intVal.ToString(); uint uintVal = Convert.ToUInt32(strVal); if (uintVal != intVal) { TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Convert to UInt32 from string 5"); try { string strVal = null; uint uintVal = Convert.ToUInt32(strVal); if (uintVal != 0) { TestLibrary.TestFramework.LogError("009", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: the string represents a number less than MinValue"); try { int intVal = this.GetInt32(1, Int32.MaxValue); string strVal = "-" + intVal.ToString(); uint uintVal = Convert.ToUInt32(strVal); TestLibrary.TestFramework.LogError("N001", "the string represents a number less than MinValue but not throw exception"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: the string represents a number greater than MaxValue"); try { UInt64 sourceVal = (UInt64)UInt32.MaxValue + (UInt64)this.GetInt32(1, Int32.MaxValue); string strVal = sourceVal.ToString(); uint uintVal = Convert.ToUInt32(strVal); TestLibrary.TestFramework.LogError("N003", "the string represents a number greater than MaxValue but not throw exception"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: the string does not consist of an optional sign followed by a sequence of digits "); try { string strVal = "helloworld"; uint uintVal = Convert.ToUInt32(strVal); TestLibrary.TestFramework.LogError("N005", "the string does not consist of an optional sign followed by a sequence of digits but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: the string is empty string"); try { string strVal = string.Empty; uint uintVal = Convert.ToUInt32(strVal); TestLibrary.TestFramework.LogError("N007", "the string is empty string but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
using System.Collections.Generic; using System; using System.Reflection; using System.Data; using UnityEngine; using Oxide.Core; using Oxide.Core.Configuration; using Oxide.Core.Plugins; /* This is my first plugin, and I'm not very good with C# - so this is probably horrible and I apologize now. Thanks! */ namespace Oxide.Plugins { [Info("PersonalBeacon", "Mordenak", "1.0.7", ResourceId = 1000)] class PersonalBeacon : RustPlugin { // To be moved into config file at some point... static int beaconHeight = 500; static int arrowSize = 10; static float beaconRefresh = 2f; static Core.Configuration.DynamicConfigFile BeaconData; static Dictionary<string, bool> userBeacons = new Dictionary<string, bool>(); static Dictionary<string, Oxide.Plugins.Timer> userBeaconTimers = new Dictionary<string, Oxide.Plugins.Timer>(); static Dictionary<string, bool> adminBeacons = new Dictionary<string, bool>(); static Dictionary<string, Oxide.Plugins.Timer> adminTimers = new Dictionary<string, Oxide.Plugins.Timer>(); static Dictionary<string, bool> adminBeaconIsOn = new Dictionary<string, bool>(); static Dictionary<string, Oxide.Plugins.Timer> adminBeaconTimers = new Dictionary<string, Oxide.Plugins.Timer>(); void Loaded() { LoadBeaconData(); } void Unload() { SaveBeaconData(); //CleanUpBeacons(); } void OnServerSave() { SaveBeaconData(); } private void SaveBeaconData() { Interface.GetMod().DataFileSystem.SaveDatafile("PersonalBeacon_Data"); } private void LoadBeaconData() { //Debug.Log("Loading data..."); try { //BeaconData = Interface.GetMod().DataFileSystem.ReadObject<Oxide.Core.Configuration.DynamicConfigFile>("PersonalBeacon_Data"); BeaconData = Interface.GetMod().DataFileSystem.GetDatafile("PersonalBeacon_Data"); } catch { Debug.Log("Failed to load datafile."); } //Debug.Log("Data should be loaded."); } void DisplayBeacon(BasePlayer player) { var playerId = player.userID.ToString(); // player has disconnected if (!player.IsConnected()) { Debug.Log("Cleaning up disconnected player timer."); userBeacons[playerId] = false; userBeaconTimers[playerId].Destroy(); return; } if (BeaconData == null) { Debug.Log("BeaconData wasn't loaded before use, forcing load."); LoadBeaconData(); } if (BeaconData[playerId] == null) { Debug.Log(string.Format("Player [{0}] -- BeaconData is corrupt.", playerId) ); userBeacons[playerId] = false; userBeaconTimers[playerId].Destroy(); return; /* foreach (var playerbeacons in BeaconData) { Debug.Log(playerbeacons.ToString()); } */ } var table = BeaconData[playerId] as Dictionary<string, object>; //var beaconGround = new Vector3((float)table["x"], (float)table["y"], (float)table["z"]); var beaconGround = new Vector3(); // Necessary evil here beaconGround.x = float.Parse(table["x"].ToString()); beaconGround.y = float.Parse(table["y"].ToString()); beaconGround.z = float.Parse(table["z"].ToString()); var beaconSky = beaconGround; beaconSky.y = beaconSky.y + beaconHeight; player.SendConsoleCommand("ddraw.arrow", beaconRefresh, UnityEngine.Color.red, beaconGround, beaconSky, arrowSize); } [ChatCommand("setwp")] void cmdSetBeacon(BasePlayer player, string command, string[] args) { Dictionary<string, object> coords = new Dictionary<string, object>(); coords.Add("x", player.transform.position.x); coords.Add("y", player.transform.position.y); coords.Add("z", player.transform.position.z); if (BeaconData == null) { Debug.Log("BeaconData wasn't loaded before use, forcing load."); LoadBeaconData(); } BeaconData[player.userID.ToString()] = coords; var newVals = BeaconData[player.userID.ToString()] as Dictionary<string, object>; SendReply(player, string.Format("Beacon set to: x: {0}, y: {1}, z: {2}", newVals["x"], newVals["y"], newVals["z"]) ); } [ChatCommand("wp")] void cmdBeacon(BasePlayer player, string command, string[] args) { if (BeaconData == null) { Debug.Log("BeaconData wasn't loaded before use, forcing load."); LoadBeaconData(); } var playerId = player.userID.ToString(); if (BeaconData[playerId] == null) { SendReply(player, "You have not set a waypoint yet. Please run /setwp to create a waypoint."); Debug.Log(string.Format("Player [{0}] -- BeaconData is corrupt or non-existent.", playerId) ); return; /* foreach (var playerbeacons in BeaconData) { Debug.Log(playerbeacons.ToString()); } */ } if (!userBeacons.ContainsKey(playerId)) userBeacons.Add(playerId, false); // maybe unecessary if (userBeacons[playerId] == null) userBeacons[playerId] = false; if (userBeacons[playerId] == false) { DisplayBeacon(player); // display immediately userBeaconTimers[playerId] = timer.Repeat(beaconRefresh, 0, delegate() { DisplayBeacon(player); } ); SendReply(player, "Beacon on."); userBeacons[playerId] = true; } else { userBeaconTimers[playerId].Destroy(); SendReply(player, "Beacon off."); userBeacons[playerId] = false; } } // Admin commands: [ChatCommand("wpadmin")] void cmdAdminWaypoint(BasePlayer player, string command, string[] args) { if (player.net.connection.authLevel == 0) return; // set a wp at the current location var currLocation = player.transform.position; var playerId = player.userID.ToString(); if (!adminBeaconIsOn.ContainsKey(playerId)) adminBeaconIsOn.Add(playerId, false); if (adminBeaconIsOn[playerId] == null) adminBeaconIsOn[playerId] = false; //var repeatBeacon = new Dictionary<string, Oxide.Plugins.Timer>(); if (adminBeaconIsOn[playerId] == false) { SendReply(player, "Sending Admin Waypoint to all players."); adminBeaconTimers[playerId] = timer.Repeat(beaconRefresh, 0, delegate() { var beaconGround = currLocation; var beaconSky = beaconGround; beaconSky.y = beaconSky.y + beaconHeight; ConsoleSystem.Broadcast("ddraw.arrow", beaconRefresh, UnityEngine.Color.green, beaconGround, beaconSky, arrowSize); } ); adminBeaconIsOn[playerId] = true; } else { SendReply(player, "Removing the Admin Waypoint."); foreach (var adbeacontimers in adminBeaconTimers) { adbeacontimers.Value.Destroy(); } adminBeaconIsOn[playerId] = false; } } [ChatCommand("wpcount")] void cmdCountBeacons(BasePlayer player, string command, string[] args) { if (player.net.connection.authLevel == 0) return; int wpCount = 0; foreach (var playerbeacons in BeaconData) { //Debug.Log(playerbeacons.ToString()); wpCount = wpCount + 1; } //Debug.Log(string.Format("Found {0} waypoints.", wpCount) ); SendReply(player, string.Format("Tracking {0} waypoints.", wpCount) ); } [ChatCommand("wpshowall")] void cmdShowAllBeacons(BasePlayer player, string command, string[] args) { if (player.net.connection.authLevel == 0) return; var playerId = player.userID.ToString(); if (!adminBeacons.ContainsKey(playerId)) adminBeacons.Add(playerId, false); if (adminBeacons[playerId] == null) adminBeacons[playerId] = false; if (adminBeacons[playerId] == false) { foreach (var playerbeacons in BeaconData) { //Debug.Log(string.Format("Looking for beacon for player: {0}", playerbeacons.Key) ); var targetId = playerbeacons.Key; var table = BeaconData[targetId] as Dictionary<string, object>; //var beaconGround = new Vector3((float)table["x"], (float)table["y"], (float)table["z"]); var beaconGround = new Vector3(); // Necessary evil here beaconGround.x = float.Parse(table["x"].ToString()); beaconGround.y = float.Parse(table["y"].ToString()); beaconGround.z = float.Parse(table["z"].ToString()); var beaconSky = beaconGround; beaconSky.y = beaconSky.y + beaconHeight; player.SendConsoleCommand("ddraw.arrow", beaconRefresh, UnityEngine.Color.red, beaconGround, beaconSky, arrowSize); adminTimers[targetId] = timer.Repeat(beaconRefresh, 0, delegate() { player.SendConsoleCommand("ddraw.arrow", beaconRefresh, UnityEngine.Color.red, beaconGround, beaconSky, arrowSize);; } ); //player.SendConsoleCommand("ddraw.arrow", 10f, UnityEngine.Color.red, beaconGround, beaconSky, 10); } SendReply(player, "All beacons on."); adminBeacons[playerId] = true; } else { foreach (var playerdata in BeaconData) { adminTimers[playerdata.Key].Destroy(); } //adminTimers[targetId].Destroy(); SendReply(player, "All beacons off."); adminBeacons[playerId] = false; } } [HookMethod("SendHelpText")] private void SendHelpText(BasePlayer player) { var helpString = "<color=#11FF22>PersonalBeacon</color>:\n/setwp - Sets the beacon to the current location.\n/wp - Toggles beacon on or off."; player.ChatMessage(helpString.TrimEnd()); } } }
//--------------------------------------------------------------------------- // // <copyright file="DiffuseMaterial.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { sealed partial class DiffuseMaterial : Material { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new DiffuseMaterial Clone() { return (DiffuseMaterial)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new DiffuseMaterial CloneCurrentValue() { return (DiffuseMaterial)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void ColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DiffuseMaterial target = ((DiffuseMaterial) d); target.PropertyChanged(ColorProperty); } private static void AmbientColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DiffuseMaterial target = ((DiffuseMaterial) d); target.PropertyChanged(AmbientColorProperty); } private static void BrushPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { // The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children) // will promote the property value from a default value to a local value. This is technically a sub-property // change because the collection was changed and not a new collection set (GeometryGroup.Children. // Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled // the default value to the compositor. If the property changes from a default value, the new local value // needs to be marshalled to the compositor. We detect this scenario with the second condition // e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be // Default and the NewValueSource will be Local. if (e.IsASubPropertyChange && (e.OldValueSource == e.NewValueSource)) { return; } DiffuseMaterial target = ((DiffuseMaterial) d); Brush oldV = (Brush) e.OldValue; Brush newV = (Brush) e.NewValue; System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher; if (dispatcher != null) { DUCE.IResource targetResource = (DUCE.IResource)target; using (CompositionEngineLock.Acquire()) { int channelCount = targetResource.GetChannelCount(); for (int channelIndex = 0; channelIndex < channelCount; channelIndex++) { DUCE.Channel channel = targetResource.GetChannel(channelIndex); Debug.Assert(!channel.IsOutOfBandChannel); Debug.Assert(!targetResource.GetHandle(channel).IsNull); target.ReleaseResource(oldV,channel); target.AddRefResource(newV,channel); } } } target.PropertyChanged(BrushProperty); } #region Public Properties /// <summary> /// Color - Color. Default value is Colors.White. /// </summary> public Color Color { get { return (Color) GetValue(ColorProperty); } set { SetValueInternal(ColorProperty, value); } } /// <summary> /// AmbientColor - Color. Default value is Colors.White. /// </summary> public Color AmbientColor { get { return (Color) GetValue(AmbientColorProperty); } set { SetValueInternal(AmbientColorProperty, value); } } /// <summary> /// Brush - Brush. Default value is null. /// </summary> public Brush Brush { get { return (Brush) GetValue(BrushProperty); } set { SetValueInternal(BrushProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new DiffuseMaterial(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Read values of properties into local variables Brush vBrush = Brush; // Obtain handles for properties that implement DUCE.IResource DUCE.ResourceHandle hBrush = vBrush != null ? ((DUCE.IResource)vBrush).GetHandle(channel) : DUCE.ResourceHandle.Null; // Pack & send command packet DUCE.MILCMD_DIFFUSEMATERIAL data; unsafe { data.Type = MILCMD.MilCmdDiffuseMaterial; data.Handle = _duceResource.GetHandle(channel); data.color = CompositionResourceManager.ColorToMilColorF(Color); data.ambientColor = CompositionResourceManager.ColorToMilColorF(AmbientColor); data.hbrush = hBrush; // Send packed command structure channel.SendCommand( (byte*)&data, sizeof(DUCE.MILCMD_DIFFUSEMATERIAL)); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_DIFFUSEMATERIAL)) { Brush vBrush = Brush; if (vBrush != null) ((DUCE.IResource)vBrush).AddRefOnChannel(channel); AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { Brush vBrush = Brush; if (vBrush != null) ((DUCE.IResource)vBrush).ReleaseOnChannel(channel); ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties // // This property finds the correct initial size for the _effectiveValues store on the // current DependencyObject as a performance optimization // // This includes: // Brush // internal override int EffectiveValuesInitialSize { get { return 1; } } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the DiffuseMaterial.Color property. /// </summary> public static readonly DependencyProperty ColorProperty; /// <summary> /// The DependencyProperty for the DiffuseMaterial.AmbientColor property. /// </summary> public static readonly DependencyProperty AmbientColorProperty; /// <summary> /// The DependencyProperty for the DiffuseMaterial.Brush property. /// </summary> public static readonly DependencyProperty BrushProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal static Color s_Color = Colors.White; internal static Color s_AmbientColor = Colors.White; internal static Brush s_Brush = null; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static DiffuseMaterial() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // Debug.Assert(s_Brush == null || s_Brush.IsFrozen, "Detected context bound default value DiffuseMaterial.s_Brush (See OS Bug #947272)."); // Initializations Type typeofThis = typeof(DiffuseMaterial); ColorProperty = RegisterProperty("Color", typeof(Color), typeofThis, Colors.White, new PropertyChangedCallback(ColorPropertyChanged), null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); AmbientColorProperty = RegisterProperty("AmbientColor", typeof(Color), typeofThis, Colors.White, new PropertyChangedCallback(AmbientColorPropertyChanged), null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); BrushProperty = RegisterProperty("Brush", typeof(Brush), typeofThis, null, new PropertyChangedCallback(BrushPropertyChanged), null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); } #endregion Constructors } }
// 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. // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // NOTE: This file is generated via a T4 template. Please do not edit this file directly. Any changes should be made // in InvariantBool.tt. namespace System.Text { public static partial class PrimitiveParser { public static partial class InvariantUtf8 { public unsafe static bool TryParseBoolean(byte* text, int length, out bool value) { if (length >= 4) { if ((text[0] == 'T' || text[0] == 't') && (text[1] == 'R' || text[1] == 'r') && (text[2] == 'U' || text[2] == 'u') && (text[3] == 'E' || text[3] == 'e')) { // No need to set consumed value = true; return true; } if (length >= 5) { if ((text[0] == 'F' || text[0] == 'f') && (text[1] == 'A' || text[1] == 'a') && (text[2] == 'L' || text[2] == 'l') && (text[3] == 'S' || text[3] == 's') && (text[4] == 'E' || text[4] == 'e')) { // No need to set consumed value = false; return true; } } } // No need to set consumed value = default(bool); return false; } public unsafe static bool TryParseBoolean(byte* text, int length, out bool value, out int bytesConsumed) { if (length >= 4) { if ((text[0] == 'T' || text[0] == 't') && (text[1] == 'R' || text[1] == 'r') && (text[2] == 'U' || text[2] == 'u') && (text[3] == 'E' || text[3] == 'e')) { bytesConsumed = 4; value = true; return true; } if (length >= 5) { if ((text[0] == 'F' || text[0] == 'f') && (text[1] == 'A' || text[1] == 'a') && (text[2] == 'L' || text[2] == 'l') && (text[3] == 'S' || text[3] == 's') && (text[4] == 'E' || text[4] == 'e')) { bytesConsumed = 5; value = false; return true; } } } bytesConsumed = 0; value = default(bool); return false; } public static bool TryParseBoolean(ReadOnlySpan<byte> text, out bool value) { if (text.Length >= 4) { if ((text[0] == 'T' || text[0] == 't') && (text[1] == 'R' || text[1] == 'r') && (text[2] == 'U' || text[2] == 'u') && (text[3] == 'E' || text[3] == 'e')) { // No need to set consumed value = true; return true; } if (text.Length >= 5) { if ((text[0] == 'F' || text[0] == 'f') && (text[1] == 'A' || text[1] == 'a') && (text[2] == 'L' || text[2] == 'l') && (text[3] == 'S' || text[3] == 's') && (text[4] == 'E' || text[4] == 'e')) { // No need to set consumed value = false; return true; } } } // No need to set consumed value = default(bool); return false; } public static bool TryParseBoolean(ReadOnlySpan<byte> text, out bool value, out int bytesConsumed) { if (text.Length >= 4) { if ((text[0] == 'T' || text[0] == 't') && (text[1] == 'R' || text[1] == 'r') && (text[2] == 'U' || text[2] == 'u') && (text[3] == 'E' || text[3] == 'e')) { bytesConsumed = 4; value = true; return true; } if (text.Length >= 5) { if ((text[0] == 'F' || text[0] == 'f') && (text[1] == 'A' || text[1] == 'a') && (text[2] == 'L' || text[2] == 'l') && (text[3] == 'S' || text[3] == 's') && (text[4] == 'E' || text[4] == 'e')) { bytesConsumed = 5; value = false; return true; } } } bytesConsumed = 0; value = default(bool); return false; } } public static partial class InvariantUtf16 { public unsafe static bool TryParseBoolean(char* text, int length, out bool value) { if (length >= 4) { if ((text[0] == 'T' || text[0] == 't') && (text[1] == 'R' || text[1] == 'r') && (text[2] == 'U' || text[2] == 'u') && (text[3] == 'E' || text[3] == 'e')) { // No need to set consumed value = true; return true; } if (length >= 5) { if ((text[0] == 'F' || text[0] == 'f') && (text[1] == 'A' || text[1] == 'a') && (text[2] == 'L' || text[2] == 'l') && (text[3] == 'S' || text[3] == 's') && (text[4] == 'E' || text[4] == 'e')) { // No need to set consumed value = false; return true; } } } // No need to set consumed value = default(bool); return false; } public unsafe static bool TryParseBoolean(char* text, int length, out bool value, out int charsConsumed) { if (length >= 4) { if ((text[0] == 'T' || text[0] == 't') && (text[1] == 'R' || text[1] == 'r') && (text[2] == 'U' || text[2] == 'u') && (text[3] == 'E' || text[3] == 'e')) { charsConsumed = 4; value = true; return true; } if (length >= 5) { if ((text[0] == 'F' || text[0] == 'f') && (text[1] == 'A' || text[1] == 'a') && (text[2] == 'L' || text[2] == 'l') && (text[3] == 'S' || text[3] == 's') && (text[4] == 'E' || text[4] == 'e')) { charsConsumed = 5; value = false; return true; } } } charsConsumed = 0; value = default(bool); return false; } public static bool TryParseBoolean(ReadOnlySpan<char> text, out bool value) { if (text.Length >= 4) { if ((text[0] == 'T' || text[0] == 't') && (text[1] == 'R' || text[1] == 'r') && (text[2] == 'U' || text[2] == 'u') && (text[3] == 'E' || text[3] == 'e')) { // No need to set consumed value = true; return true; } if (text.Length >= 5) { if ((text[0] == 'F' || text[0] == 'f') && (text[1] == 'A' || text[1] == 'a') && (text[2] == 'L' || text[2] == 'l') && (text[3] == 'S' || text[3] == 's') && (text[4] == 'E' || text[4] == 'e')) { // No need to set consumed value = false; return true; } } } // No need to set consumed value = default(bool); return false; } public static bool TryParseBoolean(ReadOnlySpan<char> text, out bool value, out int charsConsumed) { if (text.Length >= 4) { if ((text[0] == 'T' || text[0] == 't') && (text[1] == 'R' || text[1] == 'r') && (text[2] == 'U' || text[2] == 'u') && (text[3] == 'E' || text[3] == 'e')) { charsConsumed = 4; value = true; return true; } if (text.Length >= 5) { if ((text[0] == 'F' || text[0] == 'f') && (text[1] == 'A' || text[1] == 'a') && (text[2] == 'L' || text[2] == 'l') && (text[3] == 'S' || text[3] == 's') && (text[4] == 'E' || text[4] == 'e')) { charsConsumed = 5; value = false; return true; } } } charsConsumed = 0; value = default(bool); return false; } } } }
#region Namespaces using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Data; using System.Drawing; using System.Drawing.Printing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using Epi.Analysis; using Epi.Diagnostics; using Epi.Windows; using Epi.Windows.Docking; using Epi.Windows.Dialogs; using Epi.Windows.Analysis.Dialogs; #endregion namespace Epi.Windows.Analysis.Forms { #region Delegates /// <summary> /// Represents the method that handles the RunCommand event /// </summary> public delegate void RunCommandEventHandler(string command); /// <summary> /// Represents the method that will be used to process the results from a command /// </summary> public delegate void ProcessResultsHandler( CommandProcessorResults results ); /// <summary> /// Represents the method that handles the RunPGM event /// </summary> public delegate void RunPGMEventHandler(string command); ///// <summary> ///// Represents the method that handles the RunPGM event ///// </summary> //public delegate void RunPGMEventHandler( string command, ProcessResultsHandler resultshandler ); #endregion /// <summary> /// The Analysis program editor /// </summary> public partial class ProgramEditor : DockWindow { #region Private Attributes private string currentPgmName = string.Empty; private string findString = string.Empty; private int lineNo = 0; // private bool dirty = false; private Font printFont = new Font("Arial", 10); private static Char[] noiseChars = { '\r', '\n', ' ', '\t' }; private string currentSearchString = string.Empty; private RichTextBoxFinds currentSearchOpts; new private Epi.Windows.Analysis.Forms.AnalysisMainForm mainForm; #endregion Private Attributes #region Public Events /// <summary> /// Occurs when RunThisCommand is clicked /// </summary> public event RunCommandEventHandler RunCommand; /// <summary> /// Occurs when Run is clicked /// </summary> public event RunPGMEventHandler RunPGM; #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> public ProgramEditor() { InitializeComponent(); } /// <summary> /// Constructor /// </summary> /// <param name="mainForm">The main form</param> public ProgramEditor(AnalysisMainForm mainForm) { this.mainForm = mainForm; InitializeComponent(); } #endregion #region Public Methods /// <summary> /// Adds the generated command to the text area /// </summary> /// <param name="commandText">Command Text</param> public void AddCommand(string commandText) { if (string.IsNullOrEmpty(commandText.Trim())) { throw new ArgumentNullException("commandText"); } if (!(txtTextArea.Text.EndsWith(Environment.NewLine) || txtTextArea.Text.EndsWith("\n") || txtTextArea.Text == "")) { commandText = Environment.NewLine + commandText; } commandText += Environment.NewLine; if (mnuEditInsertCommandAtCursor.Checked) { int line = txtTextArea.GetLineFromCharIndex( txtTextArea.SelectionStart ); txtTextArea.SelectionStart = txtTextArea.GetFirstCharIndexFromLine( line ); txtTextArea.SelectionLength = 0; txtTextArea.SelectedText = commandText; } else { txtTextArea.AppendText( commandText ); } } /// <summary> /// Clears out the program editor's text area. /// </summary> public virtual void Clear() { txtTextArea.Text = string.Empty; } /// <summary> /// Clears all the text in the editor /// </summary> public void OnNew() { if (!string.IsNullOrEmpty(this.txtTextArea.Text)) { DialogResult result = MsgBox.ShowQuestion(SharedStrings.CREATE_NEW_PGM); if (result == DialogResult.Yes) { Clear(); ShowNewPgm(); // dirty = false; currentPgmName = string.Empty; } } else { ShowNewPgm(); } } /// <summary> /// Loads pgm from command line text file and executes. /// </summary> /// <param name="programPath">Path to program</param> public void LoadProgramFromCommandLine(string programPath) { if (File.Exists(programPath)) { txtTextArea.Text = File.ReadAllText(programPath); RunPGM(txtTextArea.Text); } } /// <summary> /// Set Cursor /// </summary> /// <param name="index">Index of the cursor</param> public void SetCursor(int index) { txtTextArea.SelectionStart = index; } /// <summary> /// Set Line Focus /// </summary> /// <param > </param> public void SetLineFocus() { int lineNumber = txtTextArea.GetLineFromCharIndex(txtTextArea.SelectionStart); int start = txtTextArea.GetFirstCharIndexFromLine(lineNumber); txtTextArea.SelectionStart = start; txtTextArea.SelectionLength = 0; txtTextArea.Focus(); } /// <summary> /// Set Cursor /// </summary> /// <param name="args">Parse Exception</param> public void SetCursor(ParseException args) { int lineNumber = args.UnexpectedToken.Location.LineNr; if (lineNumber == 0) { string compare = string.Empty; if ( txtTextArea.Lines[lineNumber].Length > (args.UnexpectedToken.Location.Position - 1 + args.UnexpectedToken.Text.Length)) { compare = txtTextArea.Lines[lineNumber].Substring(args.UnexpectedToken.Location.Position - 1, args.UnexpectedToken.Text.Length); } if (compare != args.UnexpectedToken.Text) { lineNumber = txtTextArea.GetLineFromCharIndex(txtTextArea.SelectionStart); } } txtTextArea.Text = txtTextArea.Text.TrimStart(new char[]{'\n','\r',' '}); int start = txtTextArea.GetFirstCharIndexFromLine(lineNumber); int length = txtTextArea.Lines[lineNumber].Length; txtTextArea.Select(start, length); txtTextArea.SelectionColor = Color.Red; txtTextArea.Select(start, 0); } #endregion #region Private Methods /// <summary> /// Show a blank Pgm /// </summary> private void ShowNewPgm() { this.Text = SharedStrings.PROGRAM_EDITOR + " - " + SharedStrings.NEW_PROGRAM; } private void SetTitle() { this.Text = SharedStrings.PROGRAM_EDITOR; if (!string.IsNullOrEmpty(this.currentPgmName)) this.Text += " - " + this.currentPgmName; } /// <summary> /// Saves the current program /// </summary> /// <param name="content">Content of th Pgm</param> private void SaveCurrentPgm(string content) { PgmDialog dialog = new PgmDialog(mainForm, currentPgmName, content, PgmDialog.PgmDialogMode.SaveProgram); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { } } /// <summary> /// Raises the RunPGM event. /// </summary> /// <param name="command">Command that is to be executed</param> private void OnRunPGM(string command) { //Issue 889: making sure command text is not null or empty string if (RunPGM != null && !string.IsNullOrEmpty(command) && command.Trim().Length> 0) { OutputTextBox.Clear(); btnCancelRunningCommands.Enabled = true; btnRun.Enabled = false; RunPGM(command); // dcs90 7/7/2008 because resultlts must be handled for each command } } ///// <summary> ///// change the font color of the selected Line. ///// </summary> ///// <param name="lineNo">number of line to be changed</param> ///// <param name="color">the color to which to change</param> //private void ChangeColor(int lineNo, Color color) //{ // int startPos = TextArea.SelectionStart; // int currLine = txtTextArea.GetLineFromCharIndex(txtTextArea.SelectionStart); // int lineLen = txtTextArea //} /// <summary> /// Raises the RunCommand event. /// </summary> /// <param name="command">Command that is to be executed</param> private void OnRunCommand(string command) { //Issue 889: making sure command text is not null or empty string if (RunCommand != null && !string.IsNullOrEmpty(command) && command.Trim().Length > 0) { OutputTextBox.Clear(); btnCancelRunningCommands.Enabled = false; btnRun.Enabled = false; RunCommand(command); btnCancelRunningCommands.Enabled = true; btnRun.Enabled = true; } } #endregion Private Methods #region Event Handlers private void mnuFileExit_Click(object sender, EventArgs e) { mainForm.Close(); } private void ProgramEditor_TextChanged(object sender, EventArgs e) { } private void txtTextArea_TextChanged(object sender, EventArgs e) { } private void btnNew_Click(object sender, EventArgs e) { OnNew(); } private void btnOpen_Click(object sender, EventArgs e) { PgmDialog dialog = new PgmDialog(mainForm, string.Empty, string.Empty, PgmDialog.PgmDialogMode.OpenProgram); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { currentPgmName = dialog.ProgramName; txtTextArea.Text = dialog.Content; SetTitle(); } if (result != DialogResult.None) { dialog.Close(); } } private void btnSave_Click(object sender, EventArgs ev) { PgmDialog dialog = new PgmDialog(mainForm, currentPgmName, this.txtTextArea.Text, PgmDialog.PgmDialogMode.SaveProgram); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { currentPgmName = dialog.ProgramName; txtTextArea.Text = dialog.Content; SetTitle(); } dialog.Close(); } private void mnuFileSaveAs_Click(object sender, EventArgs e) { PgmDialog dialog = new PgmDialog(mainForm, currentPgmName, this.txtTextArea.Text, PgmDialog.PgmDialogMode.SaveProgramAs); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { currentPgmName = dialog.ProgramName; txtTextArea.Text = dialog.Content; SetTitle(); } dialog.Close(); } private void btnPrint_Click(object sender, EventArgs ev) { using (PrintDialog pd = new PrintDialog()) { if (pd.ShowDialog() == DialogResult.OK) { using (PrintDocument doc = new PrintDocument()) { printFont = txtTextArea.Font; lineNo = 0; doc.PrintPage += new PrintPageEventHandler(doc_PrintPage); try { doc.Print(); } catch (Win32Exception ex) { MsgBox.Show(ex.Message, SharedStrings.PRINT); } } } } } // The PrintPage event is raised for each page to be printed. private void doc_PrintPage(object sender, PrintPageEventArgs ev) { float linesPerPage = 0; float yPos = 0; int count = 0; float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; String line = null; // Calculate the number of lines per page. linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics); // Iterate over the file, printing each line. while (count < linesPerPage && (lineNo < txtTextArea.Lines.GetUpperBound(0))) { line = txtTextArea.Lines[lineNo]; yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); ev.Graphics.DrawString(line, printFont, Brushes.Black,leftMargin, yPos, new StringFormat()); count++; lineNo++; } // If more lines exist, print another page. ev.HasMorePages = (lineNo < txtTextArea.Lines.GetUpperBound(0)); } private void btnRun_Click(object sender, EventArgs e) { /*txtTextArea.SelectAll(); txtTextArea.SelectionColor = Color.Black; txtTextArea.Select(0, 0); */ if (txtTextArea.SelectedText.Length > 0) { OnRunCommand(txtTextArea.SelectedText); } else { OnRunPGM(txtTextArea.Text.Replace("\n", "\r\n")); } } private void btnCancelRunningCommands_Click(object sender, EventArgs e) { this.mainForm.CancelRunningCommand(); } private void mnuEditUndo_Click(object sender, EventArgs e) { this.txtTextArea.Undo(); } private void mnuEditRedo_Click(object sender, EventArgs e) { this.txtTextArea.Redo(); } private void mnuEditCut_Click(object sender, EventArgs e) { this.txtTextArea.Cut(); } private void mnuEditCopy_Click(object sender, EventArgs e) { this.txtTextArea.Copy(); } private void mnuEditPaste_Click(object sender, EventArgs e) { this.txtTextArea.Paste(); } private void mnuSelectAll_Click(object sender, EventArgs e) { //this.txtTextArea.SelectAll(); this doesn't work - par for M$ this.txtTextArea.Select(0, txtTextArea.TextLength); //txtTextArea.SelectionStart = 0; //txtTextArea.SelectionLength = txtTextArea.TextLength; } private void mnuEditDeleteLine_Click(object sender, EventArgs e) { // TODO: dcs0 figure out how to delete a line //this.txtTextArea.SelectionStart = this.txtTextArea.GetFirstCharIndexOfCurrentLine(); //this.txtTextArea.SelectionLength = txtTextArea.GetFirstCharIndexFromLine(this.txtTextArea.GetLineFromCharIndex(1)); } private void mnuEditFind_Click(object sender, EventArgs e) { OutputTextBox.Clear(); if (txtTextArea.TextLength > 0) { SearchDialog dlg = new SearchDialog(txtTextArea.SelectedText); if (dlg.ShowDialog(this) == DialogResult.OK) { currentSearchString = dlg.SearchString; int currentPos = txtTextArea.SelectionStart; currentSearchOpts = (RichTextBoxFinds)0; if (dlg.SearchDirection == SearchDialog.Direction.Beginning) { txtTextArea.SelectionStart = 0; } else if (dlg.SearchDirection == SearchDialog.Direction.Backward) { currentSearchOpts |= RichTextBoxFinds.Reverse; } if (dlg.CaseSensitive) { currentSearchOpts |= RichTextBoxFinds.MatchCase; } currentSearchOpts |= (dlg.WholeWord) ? RichTextBoxFinds.WholeWord : RichTextBoxFinds.None; int location = 0; if (txtTextArea.TextLength > txtTextArea.SelectionStart) { location = txtTextArea.Find(dlg.SearchString, txtTextArea.SelectionStart, currentSearchOpts); } if (location > 0) { txtTextArea.SelectionStart = location; txtTextArea.SelectionLength = currentSearchString.Length; } else { OutputTextBox.Text = SharedStrings.EOF; txtTextArea.SelectionStart = currentPos; txtTextArea.SelectionLength = 0; } } } else { OutputTextBox.Text = SharedStrings.NO_SEARCH_TEXT; } } private void mnuEditFindNext_Click(object sender, EventArgs e) { OutputTextBox.Clear(); int currentPos = 0; if (txtTextArea.TextLength > 0) { currentPos = txtTextArea.SelectionStart; if (currentPos == txtTextArea.TextLength) { currentPos = 0; txtTextArea.SelectionLength = 0; } if (txtTextArea.SelectionLength > 0) { currentPos += txtTextArea.SelectionLength; } int location = 0; if (currentPos < txtTextArea.TextLength) { location = txtTextArea.Find(currentSearchString, currentPos, currentSearchOpts); } if (location > 0) { txtTextArea.SelectionStart = location; txtTextArea.SelectionLength = currentSearchString.Length; } else { OutputTextBox.Text = SharedStrings.EOF; txtTextArea.SelectionStart = txtTextArea.TextLength; txtTextArea.SelectionLength = 0; } } } private void mnuEditReplace_Click(object sender, EventArgs e) { if (txtTextArea.TextLength > 0) { int location = txtTextArea.SelectionStart; string text = txtTextArea.SelectedText; ReplaceDialog dlg = new ReplaceDialog(text); if (dlg.ShowDialog(this) == DialogResult.OK) { currentSearchOpts = (RichTextBoxFinds)0; currentSearchString = dlg.ReplaceString; if (dlg.CaseSensitive) { currentSearchOpts |= RichTextBoxFinds.MatchCase; } currentSearchOpts |= (dlg.WholeWord) ? RichTextBoxFinds.WholeWord : RichTextBoxFinds.None; do { location = txtTextArea.Find(currentSearchString, currentSearchOpts); if (location > 0) { txtTextArea.SelectionStart = location; txtTextArea.SelectionLength = currentSearchString.Length; txtTextArea.SelectedText = dlg.ReplacementString; } } while (location > 0 && dlg.ReplaceAll); } } else { OutputTextBox.Text = SharedStrings.NO_SEARCH_TEXT; } } private void mnuEditProgramBeginning_Click(object sender, EventArgs e) { this.txtTextArea.SelectionStart = 0; } private void mnuEditProgramEnd_Click(object sender, EventArgs e) { int line = txtTextArea.Lines.GetUpperBound(0); if (line >= 0) { txtTextArea.SelectionStart = txtTextArea.GetFirstCharIndexFromLine(line); } } private void mnuEditInsertCommandAtCursor_Click(object sender, EventArgs e) { mnuEditInsertCommandAtCursor.Checked = (!mnuEditInsertCommandAtCursor.Checked); } private void mnuFontsSetEditorFont_Click(object sender, EventArgs e) { fontDialog.ShowDialog(this); txtTextArea.Font = fontDialog.Font; } #endregion private void mnuOutputTextCopy_Click(object sender, EventArgs e) { this.OutputTextBox.Copy(); } public void ShowErrorMessage(string pErrorMessage) { this.OutputTextBox.Text = pErrorMessage; } private void cutToolStripMenuItem_Click(object sender, EventArgs e) { this.txtTextArea.Cut(); } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { this.txtTextArea.Copy(); } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { this.txtTextArea.Paste(); } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { this.txtTextArea.SelectedText = ""; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; // ReSharper disable InconsistentNaming namespace Northwind.Models { #region ISaveable /// <summary> /// Marker interface indicating that instances of this class may be saved; /// </summary> public interface ISaveable { Guid? UserSessionId { get; set; } string CanAdd(); } #endregion #region Category class public class Category { public int CategoryID {get;set;} public string CategoryName {get;set;} public string Description {get;set;} public byte[] Picture {get;set;} public int RowVersion {get;set;} public ICollection<Product> Products {get;set;} } #endregion Category class #region Customer class public class Customer : ISaveable { public Guid CustomerID { get; set; } [JsonIgnore] [MaxLength(5)] public string CustomerID_OLD { get; set;} [Required, MaxLength(40)] public string CompanyName { get; set; } [MaxLength(30)] public string ContactName { get; set;} [MaxLength(30)] public string ContactTitle { get; set; } [MaxLength(60)] public string Address { get; set; } [MaxLength(15)] public string City { get; set; } [MaxLength(15)] public string Region { get; set; } [MaxLength(10)] public string PostalCode { get; set; } [MaxLength(15)] public string Country { get; set; } [MaxLength(24)] public string Phone { get; set; } [MaxLength(24)] public string Fax { get; set; } [ConcurrencyCheck] public int? RowVersion { get; set; } public ICollection<Order> Orders { get; set; } [JsonIgnore] public Guid? UserSessionId { get; set; } public string CanAdd() { return CustomerID == Guid.Empty ? null : "must provide a CustomerID"; } } #endregion Customer class #region Employee class public class Employee : ISaveable { public int EmployeeID {get; set;} [Required, MaxLength(30)] public string LastName {get; set;} [Required, MaxLength(30)] public string FirstName {get; set;} // Unmapped, server-side calculated property // FullName is "Last, First" (compared to usual client-side version, "First Last") [NotMapped] public string FullName { get { return LastName + (String.IsNullOrWhiteSpace(FirstName)? "" : (", " + FirstName)); } } [MaxLength(30)] public string Title {get; set;} [MaxLength(25)] public string TitleOfCourtesy {get; set;} public DateTime? BirthDate {get; set;} public DateTime? HireDate {get; set;} [MaxLength(60)] public string Address {get; set;} [MaxLength(15)] public string City {get; set;} [MaxLength(15)] public string Region {get; set;} [MaxLength(10)] public string PostalCode {get; set;} [MaxLength(15)] public string Country {get; set;} [MaxLength(24)] public string HomePhone {get; set;} [MaxLength(4)] public string Extension {get; set;} public byte[] Photo {get; set;} public string Notes {get; set;} [MaxLength(255)] public string PhotoPath {get; set;} public int? ReportsToEmployeeID {get; set;} public int RowVersion {get; set;} [InverseProperty("Manager")] public ICollection<Employee> DirectReports {get; set;} [ForeignKey("ReportsToEmployeeID")] [InverseProperty("DirectReports")] public Employee Manager {get; set;} [InverseProperty("Employee")] public ICollection<EmployeeTerritory> EmployeeTerritories {get;set;} [InverseProperty("Employee")] public ICollection<Order> Orders {get; set;} [InverseProperty("Employees")] public ICollection<Territory> Territories {get;set;} [JsonIgnore] public Guid? UserSessionId { get; set; } public string CanAdd() { return null; } } #endregion Employee class #region EmployeeTerritory class public class EmployeeTerritory { public int ID {get;set;} public int EmployeeID {get;set;} public int TerritoryID {get;set;} public int RowVersion {get;set;} [ForeignKey("EmployeeID")] [InverseProperty("EmployeeTerritories")] public Employee Employee {get;set;} [ForeignKey("TerritoryID")] [InverseProperty("EmployeeTerritories")] public Territory Territory {get;set;} } #endregion EmployeeTerritory class #region Order class public class Order : ISaveable { public int OrderID {get; set;} public Guid? CustomerID {get; set;} public int? EmployeeID {get; set;} public DateTime? OrderDate {get; set;} public DateTime? RequiredDate {get; set;} public DateTime? ShippedDate {get; set;} public decimal? Freight {get; set;} [MaxLength(40)] public string ShipName {get; set;} [MaxLength(60)] public string ShipAddress {get; set;} [MaxLength(15)] public string ShipCity {get; set;} [MaxLength(15)] public string ShipRegion {get; set;} [MaxLength(10)] public string ShipPostalCode {get; set;} [MaxLength(15)] public string ShipCountry {get; set;} public int RowVersion {get; set;} [ForeignKey("CustomerID")] [InverseProperty("Orders")] public Customer Customer {get; set;} [ForeignKey("EmployeeID")] [InverseProperty("Orders")] public Employee Employee {get; set;} [InverseProperty("Order")] public ICollection<OrderDetail> OrderDetails {get; set;} [InverseProperty("Order")] public InternationalOrder InternationalOrder {get;set;} [JsonIgnore] public Guid? UserSessionId { get; set; } public static int HighestOriginalID = 11077; public string CanAdd() { return null; } } #endregion Order class #region OrderDetail class public class OrderDetail : ISaveable { public int OrderID {get; set;} public int ProductID {get; set;} public decimal UnitPrice {get; set;} public short Quantity {get; set;} public float Discount {get; set;} public int RowVersion {get; set;} [ForeignKey("OrderID")] [InverseProperty("OrderDetails")] public Order Order {get; set;} [ForeignKey("ProductID")] // disabled navigation from Product to OrderDetails //[InverseProperty("OrderDetails")] public Product Product {get;set;} [JsonIgnore] public Guid? UserSessionId { get; set; } public string CanAdd() { return (OrderID == 0 || ProductID == 0) ? null : "must provide non-zero OrderID and ProductID"; } } #endregion OrderDetail class #region PreviousEmployee class public class PreviousEmployee { public int EmployeeID { get; set; } [Required, MaxLength(30)] public string LastName { get; set; } [Required, MaxLength(30)] public string FirstName { get; set; } [MaxLength(30)] public string Title { get; set; } [MaxLength(25)] public string TitleOfCourtesy { get; set; } public DateTime? BirthDate { get; set; } public DateTime? HireDate { get; set; } [MaxLength(60)] public string Address { get; set; } [MaxLength(15)] public string City { get; set; } [MaxLength(15)] public string Region { get; set; } [MaxLength(10)] public string PostalCode { get; set; } [MaxLength(15)] public string Country { get; set; } [MaxLength(24)] public string HomePhone { get; set; } [MaxLength(4)] public string Extension { get; set; } public byte[] Photo { get; set; } public string Notes { get; set; } [MaxLength(255)] public string PhotoPath { get; set; } public int? ReportsToEmployeeID { get; set; } public int RowVersion { get; set; } } #endregion PreviousEmployee class #region Product class public class Product { public int ProductID {get;set;} [MaxLength(40)] public string ProductName {get;set;} public int? SupplierID {get;set;} public int? CategoryID {get;set;} public string QuantityPerUnit {get;set;} public decimal? UnitPrice {get;set;} public short? UnitsInStock {get;set;} public short? UnitsOnOrder {get;set;} public short? ReorderLevel {get;set;} [DefaultValue(false)] public bool Discontinued {get;set;} public DateTime? DiscontinuedDate {get;set;} public int RowVersion {get;set;} [ForeignKey("CategoryID")] [InverseProperty("Products")] public Category Category {get;set;} // Disable the navigation from Product to OrderDetails // Retain navigation from OrderDetails to Product // //[InverseProperty("Product")] //public ICollection<OrderDetail> OrderDetails {get;set;} [ForeignKey("SupplierID")] [InverseProperty("Products")] public Supplier Supplier {get;set;} } #endregion Product class #region Region class public class Region { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int RegionID { get; set; } [Required, MaxLength(50)] public string RegionDescription { get; set; } public int RowVersion { get; set; } [InverseProperty("Region")] public ICollection<Territory> Territories { get; set; } } #endregion Region class #region Role class public class Role { public long Id { get; set; } [Required, MaxLength(50)] public string Name { get; set; } [MaxLength(2000)] public string Description { get; set; } [InverseProperty("Role")] public ICollection<UserRole> UserRoles { get; set; } } #endregion Role class #region Supplier class public class Supplier { public int SupplierID { get; set; } [Required, MaxLength(40)] public string CompanyName {get; set;} [MaxLength(30)] public string ContactName {get; set;} [MaxLength(30)] public string ContactTitle {get; set;} [MaxLength(60)] public string Address {get; set;} [MaxLength(15)] public string City {get; set;} [MaxLength(15)] public string Region {get; set;} [MaxLength(10)] public string PostalCode {get; set;} [MaxLength(15)] public string Country {get; set;} [MaxLength(24)] public string Phone {get; set;} [MaxLength(24)] public string Fax {get; set;} public string HomePage {get; set;} public int RowVersion {get; set;} [InverseProperty("Supplier")] public ICollection<Product> Products {get; set;} } #endregion Supplier Class #region Territory class public class Territory { public int TerritoryID { get; set; } [Required, MaxLength(50)] public string TerritoryDescription { get; set; } public int RegionID { get; set; } public int RowVersion { get; set; } [InverseProperty("Territory")] public ICollection<EmployeeTerritory> EmployeeTerritories { get; set; } [ForeignKey("RegionID")] [InverseProperty("Territories")] public Region Region { get; set; } [InverseProperty("Territories")] public ICollection<Employee> Employees { get; set; } } #endregion Territory class #region User class public class User : ISaveable { public long Id { get; set; } [MaxLength(100)] public string UserName { get; set; } [MaxLength(200)] public string UserPassword { get; set; } [MaxLength(100)] public string FirstName { get; set; } [MaxLength(100)] public string LastName { get; set; } [MaxLength(100)] public string Email { get; set; } public decimal RowVersion { get; set; } [MaxLength(100)] public string CreatedBy { get; set; } public long CreatedByUserId { get; set; } public DateTime CreatedDate { get; set; } [MaxLength(100)] public string ModifiedBy { get; set; } public long ModifiedByUserId { get; set; } [ConcurrencyCheck] public DateTime ModifiedDate { get; set; } [InverseProperty("User")] public ICollection<UserRole> UserRoles { get; set; } [JsonIgnore] public Guid? UserSessionId { get; set; } public string CanAdd() { return null; } } #endregion User class #region UserRole class public class UserRole { public long ID { get; set; } public long UserId { get; set; } public long RoleId { get; set; } [ForeignKey("RoleId")] [InverseProperty("UserRoles")] public Role Role { get; set; } [ForeignKey("UserId")] [InverseProperty("UserRoles")] public User User { get; set; } } #endregion UserRole class #region InternationalOrder class // 1-1 with Order. For Code First configuration background see // http://stackoverflow.com/questions/5980260/entity-framework-0-1-to-0-relation public class InternationalOrder : ISaveable { [Key] [ForeignKey("Order")] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int OrderID { get; set; } [MaxLength(100)] public string CustomsDescription { get; set; } public decimal ExciseTax { get; set; } public int RowVersion { get; set; } public Order Order { get; set; } [JsonIgnore] public Guid? UserSessionId { get; set; } public string CanAdd() { return null; } } #endregion InternationalOrder class }
/* * Copyright 2021 Google LLC All Rights Reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/resource.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/resource.proto</summary> public static partial class ResourceReflection { #region Descriptor /// <summary>File descriptor for google/api/resource.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ResourceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chlnb29nbGUvYXBpL3Jlc291cmNlLnByb3RvEgpnb29nbGUuYXBpGiBnb29n", "bGUvcHJvdG9idWYvZGVzY3JpcHRvci5wcm90byLuAgoSUmVzb3VyY2VEZXNj", "cmlwdG9yEgwKBHR5cGUYASABKAkSDwoHcGF0dGVybhgCIAMoCRISCgpuYW1l", "X2ZpZWxkGAMgASgJEjcKB2hpc3RvcnkYBCABKA4yJi5nb29nbGUuYXBpLlJl", "c291cmNlRGVzY3JpcHRvci5IaXN0b3J5Eg4KBnBsdXJhbBgFIAEoCRIQCghz", "aW5ndWxhchgGIAEoCRIzCgVzdHlsZRgKIAMoDjIkLmdvb2dsZS5hcGkuUmVz", "b3VyY2VEZXNjcmlwdG9yLlN0eWxlIlsKB0hpc3RvcnkSFwoTSElTVE9SWV9V", "TlNQRUNJRklFRBAAEh0KGU9SSUdJTkFMTFlfU0lOR0xFX1BBVFRFUk4QARIY", "ChRGVVRVUkVfTVVMVElfUEFUVEVSThACIjgKBVN0eWxlEhUKEVNUWUxFX1VO", "U1BFQ0lGSUVEEAASGAoUREVDTEFSQVRJVkVfRlJJRU5ETFkQASI1ChFSZXNv", "dXJjZVJlZmVyZW5jZRIMCgR0eXBlGAEgASgJEhIKCmNoaWxkX3R5cGUYAiAB", "KAk6WQoScmVzb3VyY2VfcmVmZXJlbmNlEh0uZ29vZ2xlLnByb3RvYnVmLkZp", "ZWxkT3B0aW9ucxifCCABKAsyHS5nb29nbGUuYXBpLlJlc291cmNlUmVmZXJl", "bmNlOloKE3Jlc291cmNlX2RlZmluaXRpb24SHC5nb29nbGUucHJvdG9idWYu", "RmlsZU9wdGlvbnMYnQggAygLMh4uZ29vZ2xlLmFwaS5SZXNvdXJjZURlc2Ny", "aXB0b3I6UgoIcmVzb3VyY2USHy5nb29nbGUucHJvdG9idWYuTWVzc2FnZU9w", "dGlvbnMYnQggASgLMh4uZ29vZ2xlLmFwaS5SZXNvdXJjZURlc2NyaXB0b3JC", "bgoOY29tLmdvb2dsZS5hcGlCDVJlc291cmNlUHJvdG9QAVpBZ29vZ2xlLmdv", "bGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkvYW5ub3RhdGlvbnM7", "YW5ub3RhdGlvbnP4AQGiAgRHQVBJYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pb::Extension[] { ResourceExtensions.ResourceReference, ResourceExtensions.ResourceDefinition, ResourceExtensions.Resource }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.ResourceDescriptor), global::Google.Api.ResourceDescriptor.Parser, new[]{ "Type", "Pattern", "NameField", "History", "Plural", "Singular", "Style" }, null, new[]{ typeof(global::Google.Api.ResourceDescriptor.Types.History), typeof(global::Google.Api.ResourceDescriptor.Types.Style) }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.ResourceReference), global::Google.Api.ResourceReference.Parser, new[]{ "Type", "ChildType" }, null, null, null, null) })); } #endregion } /// <summary>Holder for extension identifiers generated from the top level of google/api/resource.proto</summary> public static partial class ResourceExtensions { /// <summary> /// An annotation that describes a resource reference, see /// [ResourceReference][]. /// </summary> public static readonly pb::Extension<global::Google.Protobuf.Reflection.FieldOptions, global::Google.Api.ResourceReference> ResourceReference = new pb::Extension<global::Google.Protobuf.Reflection.FieldOptions, global::Google.Api.ResourceReference>(1055, pb::FieldCodec.ForMessage(8442, global::Google.Api.ResourceReference.Parser)); /// <summary> /// An annotation that describes a resource definition without a corresponding /// message; see [ResourceDescriptor][]. /// </summary> public static readonly pb::RepeatedExtension<global::Google.Protobuf.Reflection.FileOptions, global::Google.Api.ResourceDescriptor> ResourceDefinition = new pb::RepeatedExtension<global::Google.Protobuf.Reflection.FileOptions, global::Google.Api.ResourceDescriptor>(1053, pb::FieldCodec.ForMessage(8426, global::Google.Api.ResourceDescriptor.Parser)); /// <summary> /// An annotation that describes a resource definition, see /// [ResourceDescriptor][]. /// </summary> public static readonly pb::Extension<global::Google.Protobuf.Reflection.MessageOptions, global::Google.Api.ResourceDescriptor> Resource = new pb::Extension<global::Google.Protobuf.Reflection.MessageOptions, global::Google.Api.ResourceDescriptor>(1053, pb::FieldCodec.ForMessage(8426, global::Google.Api.ResourceDescriptor.Parser)); } #region Messages /// <summary> /// A simple descriptor of a resource type. /// /// ResourceDescriptor annotates a resource message (either by means of a /// protobuf annotation or use in the service config), and associates the /// resource's schema, the resource type, and the pattern of the resource name. /// /// Example: /// /// message Topic { /// // Indicates this message defines a resource schema. /// // Declares the resource type in the format of {service}/{kind}. /// // For Kubernetes resources, the format is {api group}/{kind}. /// option (google.api.resource) = { /// type: "pubsub.googleapis.com/Topic" /// pattern: "projects/{project}/topics/{topic}" /// }; /// } /// /// The ResourceDescriptor Yaml config will look like: /// /// resources: /// - type: "pubsub.googleapis.com/Topic" /// pattern: "projects/{project}/topics/{topic}" /// /// Sometimes, resources have multiple patterns, typically because they can /// live under multiple parents. /// /// Example: /// /// message LogEntry { /// option (google.api.resource) = { /// type: "logging.googleapis.com/LogEntry" /// pattern: "projects/{project}/logs/{log}" /// pattern: "folders/{folder}/logs/{log}" /// pattern: "organizations/{organization}/logs/{log}" /// pattern: "billingAccounts/{billing_account}/logs/{log}" /// }; /// } /// /// The ResourceDescriptor Yaml config will look like: /// /// resources: /// - type: 'logging.googleapis.com/LogEntry' /// pattern: "projects/{project}/logs/{log}" /// pattern: "folders/{folder}/logs/{log}" /// pattern: "organizations/{organization}/logs/{log}" /// pattern: "billingAccounts/{billing_account}/logs/{log}" /// </summary> public sealed partial class ResourceDescriptor : pb::IMessage<ResourceDescriptor> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<ResourceDescriptor> _parser = new pb::MessageParser<ResourceDescriptor>(() => new ResourceDescriptor()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<ResourceDescriptor> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.ResourceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceDescriptor() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceDescriptor(ResourceDescriptor other) : this() { type_ = other.type_; pattern_ = other.pattern_.Clone(); nameField_ = other.nameField_; history_ = other.history_; plural_ = other.plural_; singular_ = other.singular_; style_ = other.style_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceDescriptor Clone() { return new ResourceDescriptor(this); } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 1; private string type_ = ""; /// <summary> /// The resource type. It must be in the format of /// {service_name}/{resource_type_kind}. The `resource_type_kind` must be /// singular and must not include version numbers. /// /// Example: `storage.googleapis.com/Bucket` /// /// The value of the resource_type_kind must follow the regular expression /// /[A-Za-z][a-zA-Z0-9]+/. It should start with an upper case character and /// should use PascalCase (UpperCamelCase). The maximum number of /// characters allowed for the `resource_type_kind` is 100. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Type { get { return type_; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "pattern" field.</summary> public const int PatternFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_pattern_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> pattern_ = new pbc::RepeatedField<string>(); /// <summary> /// Optional. The relative resource name pattern associated with this resource /// type. The DNS prefix of the full resource name shouldn't be specified here. /// /// The path pattern must follow the syntax, which aligns with HTTP binding /// syntax: /// /// Template = Segment { "/" Segment } ; /// Segment = LITERAL | Variable ; /// Variable = "{" LITERAL "}" ; /// /// Examples: /// /// - "projects/{project}/topics/{topic}" /// - "projects/{project}/knowledgeBases/{knowledge_base}" /// /// The components in braces correspond to the IDs for each resource in the /// hierarchy. It is expected that, if multiple patterns are provided, /// the same component name (e.g. "project") refers to IDs of the same /// type of resource. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> Pattern { get { return pattern_; } } /// <summary>Field number for the "name_field" field.</summary> public const int NameFieldFieldNumber = 3; private string nameField_ = ""; /// <summary> /// Optional. The field on the resource that designates the resource name /// field. If omitted, this is assumed to be "name". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string NameField { get { return nameField_; } set { nameField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "history" field.</summary> public const int HistoryFieldNumber = 4; private global::Google.Api.ResourceDescriptor.Types.History history_ = global::Google.Api.ResourceDescriptor.Types.History.Unspecified; /// <summary> /// Optional. The historical or future-looking state of the resource pattern. /// /// Example: /// /// // The InspectTemplate message originally only supported resource /// // names with organization, and project was added later. /// message InspectTemplate { /// option (google.api.resource) = { /// type: "dlp.googleapis.com/InspectTemplate" /// pattern: /// "organizations/{organization}/inspectTemplates/{inspect_template}" /// pattern: "projects/{project}/inspectTemplates/{inspect_template}" /// history: ORIGINALLY_SINGLE_PATTERN /// }; /// } /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Api.ResourceDescriptor.Types.History History { get { return history_; } set { history_ = value; } } /// <summary>Field number for the "plural" field.</summary> public const int PluralFieldNumber = 5; private string plural_ = ""; /// <summary> /// The plural name used in the resource name and permission names, such as /// 'projects' for the resource name of 'projects/{project}' and the permission /// name of 'cloudresourcemanager.googleapis.com/projects.get'. It is the same /// concept of the `plural` field in k8s CRD spec /// https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ /// /// Note: The plural form is required even for singleton resources. See /// https://aip.dev/156 /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Plural { get { return plural_; } set { plural_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "singular" field.</summary> public const int SingularFieldNumber = 6; private string singular_ = ""; /// <summary> /// The same concept of the `singular` field in k8s CRD spec /// https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ /// Such as "project" for the `resourcemanager.googleapis.com/Project` type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Singular { get { return singular_; } set { singular_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "style" field.</summary> public const int StyleFieldNumber = 10; private static readonly pb::FieldCodec<global::Google.Api.ResourceDescriptor.Types.Style> _repeated_style_codec = pb::FieldCodec.ForEnum(82, x => (int) x, x => (global::Google.Api.ResourceDescriptor.Types.Style) x); private readonly pbc::RepeatedField<global::Google.Api.ResourceDescriptor.Types.Style> style_ = new pbc::RepeatedField<global::Google.Api.ResourceDescriptor.Types.Style>(); /// <summary> /// Style flag(s) for this resource. /// These indicate that a resource is expected to conform to a given /// style. See the specific style flags for additional information. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Api.ResourceDescriptor.Types.Style> Style { get { return style_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as ResourceDescriptor); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(ResourceDescriptor other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Type != other.Type) return false; if(!pattern_.Equals(other.pattern_)) return false; if (NameField != other.NameField) return false; if (History != other.History) return false; if (Plural != other.Plural) return false; if (Singular != other.Singular) return false; if(!style_.Equals(other.style_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Type.Length != 0) hash ^= Type.GetHashCode(); hash ^= pattern_.GetHashCode(); if (NameField.Length != 0) hash ^= NameField.GetHashCode(); if (History != global::Google.Api.ResourceDescriptor.Types.History.Unspecified) hash ^= History.GetHashCode(); if (Plural.Length != 0) hash ^= Plural.GetHashCode(); if (Singular.Length != 0) hash ^= Singular.GetHashCode(); hash ^= style_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } pattern_.WriteTo(output, _repeated_pattern_codec); if (NameField.Length != 0) { output.WriteRawTag(26); output.WriteString(NameField); } if (History != global::Google.Api.ResourceDescriptor.Types.History.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) History); } if (Plural.Length != 0) { output.WriteRawTag(42); output.WriteString(Plural); } if (Singular.Length != 0) { output.WriteRawTag(50); output.WriteString(Singular); } style_.WriteTo(output, _repeated_style_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } pattern_.WriteTo(ref output, _repeated_pattern_codec); if (NameField.Length != 0) { output.WriteRawTag(26); output.WriteString(NameField); } if (History != global::Google.Api.ResourceDescriptor.Types.History.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) History); } if (Plural.Length != 0) { output.WriteRawTag(42); output.WriteString(Plural); } if (Singular.Length != 0) { output.WriteRawTag(50); output.WriteString(Singular); } style_.WriteTo(ref output, _repeated_style_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Type.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); } size += pattern_.CalculateSize(_repeated_pattern_codec); if (NameField.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NameField); } if (History != global::Google.Api.ResourceDescriptor.Types.History.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) History); } if (Plural.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Plural); } if (Singular.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Singular); } size += style_.CalculateSize(_repeated_style_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(ResourceDescriptor other) { if (other == null) { return; } if (other.Type.Length != 0) { Type = other.Type; } pattern_.Add(other.pattern_); if (other.NameField.Length != 0) { NameField = other.NameField; } if (other.History != global::Google.Api.ResourceDescriptor.Types.History.Unspecified) { History = other.History; } if (other.Plural.Length != 0) { Plural = other.Plural; } if (other.Singular.Length != 0) { Singular = other.Singular; } style_.Add(other.style_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Type = input.ReadString(); break; } case 18: { pattern_.AddEntriesFrom(input, _repeated_pattern_codec); break; } case 26: { NameField = input.ReadString(); break; } case 32: { History = (global::Google.Api.ResourceDescriptor.Types.History) input.ReadEnum(); break; } case 42: { Plural = input.ReadString(); break; } case 50: { Singular = input.ReadString(); break; } case 82: case 80: { style_.AddEntriesFrom(input, _repeated_style_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Type = input.ReadString(); break; } case 18: { pattern_.AddEntriesFrom(ref input, _repeated_pattern_codec); break; } case 26: { NameField = input.ReadString(); break; } case 32: { History = (global::Google.Api.ResourceDescriptor.Types.History) input.ReadEnum(); break; } case 42: { Plural = input.ReadString(); break; } case 50: { Singular = input.ReadString(); break; } case 82: case 80: { style_.AddEntriesFrom(ref input, _repeated_style_codec); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the ResourceDescriptor message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// A description of the historical or future-looking state of the /// resource pattern. /// </summary> public enum History { /// <summary> /// The "unset" value. /// </summary> [pbr::OriginalName("HISTORY_UNSPECIFIED")] Unspecified = 0, /// <summary> /// The resource originally had one pattern and launched as such, and /// additional patterns were added later. /// </summary> [pbr::OriginalName("ORIGINALLY_SINGLE_PATTERN")] OriginallySinglePattern = 1, /// <summary> /// The resource has one pattern, but the API owner expects to add more /// later. (This is the inverse of ORIGINALLY_SINGLE_PATTERN, and prevents /// that from being necessary once there are multiple patterns.) /// </summary> [pbr::OriginalName("FUTURE_MULTI_PATTERN")] FutureMultiPattern = 2, } /// <summary> /// A flag representing a specific style that a resource claims to conform to. /// </summary> public enum Style { /// <summary> /// The unspecified value. Do not use. /// </summary> [pbr::OriginalName("STYLE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// This resource is intended to be "declarative-friendly". /// /// Declarative-friendly resources must be more strictly consistent, and /// setting this to true communicates to tools that this resource should /// adhere to declarative-friendly expectations. /// /// Note: This is used by the API linter (linter.aip.dev) to enable /// additional checks. /// </summary> [pbr::OriginalName("DECLARATIVE_FRIENDLY")] DeclarativeFriendly = 1, } } #endregion } /// <summary> /// Defines a proto annotation that describes a string field that refers to /// an API resource. /// </summary> public sealed partial class ResourceReference : pb::IMessage<ResourceReference> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<ResourceReference> _parser = new pb::MessageParser<ResourceReference>(() => new ResourceReference()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<ResourceReference> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.ResourceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceReference() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceReference(ResourceReference other) : this() { type_ = other.type_; childType_ = other.childType_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceReference Clone() { return new ResourceReference(this); } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 1; private string type_ = ""; /// <summary> /// The resource type that the annotated field references. /// /// Example: /// /// message Subscription { /// string topic = 2 [(google.api.resource_reference) = { /// type: "pubsub.googleapis.com/Topic" /// }]; /// } /// /// Occasionally, a field may reference an arbitrary resource. In this case, /// APIs use the special value * in their resource reference. /// /// Example: /// /// message GetIamPolicyRequest { /// string resource = 2 [(google.api.resource_reference) = { /// type: "*" /// }]; /// } /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Type { get { return type_; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "child_type" field.</summary> public const int ChildTypeFieldNumber = 2; private string childType_ = ""; /// <summary> /// The resource type of a child collection that the annotated field /// references. This is useful for annotating the `parent` field that /// doesn't have a fixed resource type. /// /// Example: /// /// message ListLogEntriesRequest { /// string parent = 1 [(google.api.resource_reference) = { /// child_type: "logging.googleapis.com/LogEntry" /// }; /// } /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string ChildType { get { return childType_; } set { childType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as ResourceReference); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(ResourceReference other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Type != other.Type) return false; if (ChildType != other.ChildType) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Type.Length != 0) hash ^= Type.GetHashCode(); if (ChildType.Length != 0) hash ^= ChildType.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } if (ChildType.Length != 0) { output.WriteRawTag(18); output.WriteString(ChildType); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } if (ChildType.Length != 0) { output.WriteRawTag(18); output.WriteString(ChildType); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Type.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); } if (ChildType.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ChildType); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(ResourceReference other) { if (other == null) { return; } if (other.Type.Length != 0) { Type = other.Type; } if (other.ChildType.Length != 0) { ChildType = other.ChildType; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Type = input.ReadString(); break; } case 18: { ChildType = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Type = input.ReadString(); break; } case 18: { ChildType = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Text; using System.Drawing.Printing; using System.Drawing; using DowUtils; namespace Factotum { class RsStatsAndNonGrid : ReportSection { private int startingNonGrid; public RsStatsAndNonGrid(MainReport report, ReportSectionRules rules, int subsections) : base(report, rules, subsections) { startingNonGrid = 0; } public override bool IsIncluded() { return (rpt.eInspection != null && (rpt.eInspection.InspectionTextFilePoints + rpt.eInspection.InspectionEmpties + rpt.eInspection.InspectionAdditionalMeasurements) > 0); } public override bool CanFitSome(PrintPageEventArgs args, float Y) { // If we're finishing up some additional measurements that we started on the // previous page, we're on a fresh page so some will fit. if (startingNonGrid > 0) return true; int padding = 5; int tablePadding = 2; return (args.MarginBounds.Bottom - Y - rpt.footerHeight > rpt.regTextFont.Height * 3 + rpt.boldRegTextFont.Height + padding * 3 + tablePadding * 4); } public override bool Print(PrintPageEventArgs args, float Y) { // Todo: use measurement graphics for row height? Graphics g = args.Graphics; Graphics measure = args.PageSettings.PrinterSettings.CreateMeasurementGraphics(); int leftX = args.MarginBounds.X; int centerX = (int)(leftX + args.MarginBounds.Width / 2); int rightX = leftX + args.MarginBounds.Width; int curX = leftX; int padding = 5; float startY = Y + padding; float curY = startY; float maxY = startY; int rows; int cols; int colHeadRows; int rowHeadCols; int headColWidth; int dataColWidth; int tablePadding; int nonGridCount = (int)rpt.eInspection.InspectionAdditionalMeasurements; Font curFont = rpt.regTextFont; if (startingNonGrid == 0) { // Get the stats tables. string[,] stats1 = GetStats1Array(); string[,] stats2 = GetStats2Array(); // Put the title left-aligned. g.DrawString("Statistics", curFont, Brushes.Black, leftX, curY); curY += curFont.Height + padding; // Put the stats tables left-aligned side-by-side rows = 3; cols = 2; colHeadRows = 0; rowHeadCols = 1; headColWidth = 75; dataColWidth = 50; tablePadding = 2; DrawTable(stats1, rows, cols, colHeadRows, rowHeadCols, g, curX, curY, headColWidth, dataColWidth, tablePadding, rpt.boldRegTextFont, rpt.regTextFont, true, true); curX = leftX + headColWidth + dataColWidth; curY = DrawTable(stats2, rows, cols, colHeadRows, rowHeadCols, g, curX, curY, headColWidth, dataColWidth, tablePadding, rpt.boldRegTextFont, rpt.regTextFont, true, true); if (curY > maxY) maxY = curY; } if (nonGridCount > startingNonGrid) { // The non-grid data table string[,] nonGrids; // curX = rightX - 400; curX = rightX - 495; curY = startY; curFont = rpt.regTextFont; // Put the title. string s = "Additional (Non-Grid) Measurements" + (startingNonGrid > 0 ? " Cont'd" : ""); g.DrawString(s, curFont, Brushes.Black, curX, curY); curY += curFont.Height + padding; cols = 3; colHeadRows = 1; rowHeadCols = 0; tablePadding = 2; // Figure out how many additional measurements will fit on the page. // Note: this calculation could become invalid if the DrawTable logic is changed. int dataRowsToInclude = TableRowsThatWillFitInHeight( args.MarginBounds.Bottom - curY - rpt.footerHeight, colHeadRows,tablePadding, rpt.boldRegTextFont, rpt.regTextFont); // If we can fit more than we actually have, just include what we have. if (dataRowsToInclude > nonGridCount-startingNonGrid) dataRowsToInclude = nonGridCount-startingNonGrid; // Get the array with the non-grid measurement data nonGrids = GetNonGridsArray(startingNonGrid, dataRowsToInclude); //int[] colWidths = new int[] { 100, 50, 250 }; int[] colWidths = new int[] { 100, 50, 345 }; // Draw the table curY = DrawTable(nonGrids, dataRowsToInclude + 1, cols, colHeadRows, rowHeadCols, g, curX, curY, colWidths, tablePadding, rpt.boldRegTextFont, rpt.regTextFont, true, true); if (curY > maxY) maxY = curY; // Set the starting non-grid measurement for next time, in case we couldn't get // them all on the page. startingNonGrid += dataRowsToInclude; } maxY += padding; hr(args, maxY); this.Y = maxY; // We're finished if either there were no measurements or we got them all in. return nonGridCount == 0 || startingNonGrid >= nonGridCount; } private string[,] GetStats1Array() { string[,] table = new string[3, 2]; int row, col; // No Heading row row = 0; // Min row col = 0; table[row, col] = "Min"; col++; table[row, col] = Util.GetFormattedFloat_NA(rpt.eInspection.InspectionMinWall,3); row++; // Max row col = 0; table[row, col] = "Max"; col++; table[row, col] = Util.GetFormattedFloat_NA(rpt.eInspection.InspectionMaxWall,3); row++; // Obst row col = 0; table[row, col] = "Obst"; col++; table[row, col] = rpt.eInspection.InspectionObstructions.ToString(); return table; } private string[,] GetStats2Array() { string[,] table = new string[3, 2]; int row, col; // No Heading row row = 0; // Mean row col = 0; table[row, col] = "Mean"; col++; table[row, col] = Util.GetFormattedFloat_NA(rpt.eInspection.InspectionMeanWall,3); row++; // Std Dev row col = 0; table[row, col] = "Std Dev"; col++; table[row, col] = Util.GetFormattedFloat_NA(rpt.eInspection.InspectionStdevWall,3); row++; // Empties row col = 0; table[row, col] = "Empties"; col++; table[row, col] = rpt.eInspection.InspectionEmpties.ToString(); return table; } private string[,] GetNonGridsArray(int startingNonGrid, int rows) { // First make a 2D string array to contain all the data that we want to present // Before calling this function, make sure that Non-grid data exists. string[,] table = new string[rows+1, 3]; // Flag whether the component has a branch bool hasBranch = rpt.eComponent.ComponentBranchOd != null; // Heading row int row = 0; int col = 0; table[row, col] = "Name"; col++; table[row, col] = "Value"; col++; table[row, col] = "Note"; EAdditionalMeasurementCollection addMeasures = EAdditionalMeasurement.ListByNameForInspection((Guid)rpt.eInspection.ID); // Data rows for (int i = startingNonGrid; i < startingNonGrid+rows; i++) { EAdditionalMeasurement addMeasure = addMeasures[i]; row++; col = 0; table[row, col] = addMeasure.AdditionalMeasurementName; col++; table[row, col] = Util.GetFormattedDecimal_NA(addMeasure.AdditionalMeasurementThickness); col++; table[row, col] = addMeasure.AdditionalMeasurementDescription; } return table; } } }
// 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.Buffers; using System.Buffers.Binary; using System.Diagnostics; using System.Numerics; using System.Text; namespace System.Security.Cryptography.Asn1 { internal partial class AsnReader { /// <summary> /// Reads the next value as an OBJECT IDENTIFIER with tag UNIVERSAL 6, returning /// the value in a dotted decimal format string. /// </summary> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> public string ReadObjectIdentifierAsString() => ReadObjectIdentifierAsString(Asn1Tag.ObjectIdentifier); /// <summary> /// Reads the next value as an OBJECT IDENTIFIER with a specified tag, returning /// the value in a dotted decimal format string. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> public string ReadObjectIdentifierAsString(Asn1Tag expectedTag) { string oidValue = ReadObjectIdentifierAsString(expectedTag, out int bytesRead); _data = _data.Slice(bytesRead); return oidValue; } /// <summary> /// Reads the next value as an OBJECT IDENTIFIER with tag UNIVERSAL 6, returning /// the value as an <see cref="Oid"/>. /// </summary> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> public Oid ReadObjectIdentifier() => ReadObjectIdentifier(Asn1Tag.ObjectIdentifier); /// <summary> /// Reads the next value as an OBJECT IDENTIFIER with a specified tag, returning /// the value as an <see cref="Oid"/>. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> public Oid ReadObjectIdentifier(Asn1Tag expectedTag) { string oidValue = ReadObjectIdentifierAsString(expectedTag, out int bytesRead); // Specifying null for friendly name makes the lookup deferred until first read // of the Oid.FriendlyName property. Oid oid = new Oid(oidValue, null); // Don't slice until the return object has been created. _data = _data.Slice(bytesRead); return oid; } private static void ReadSubIdentifier( ReadOnlySpan<byte> source, out int bytesRead, out long? smallValue, out BigInteger? largeValue) { Debug.Assert(source.Length > 0); // T-REC-X.690-201508 sec 8.19.2 (last sentence) if (source[0] == 0x80) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } // First, see how long the segment is int end = -1; int idx; for (idx = 0; idx < source.Length; idx++) { // If the high bit isn't set this marks the end of the sub-identifier. bool endOfIdentifier = (source[idx] & 0x80) == 0; if (endOfIdentifier) { end = idx; break; } } if (end < 0) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } bytesRead = end + 1; long accum = 0; // Fast path, 9 or fewer bytes => fits in a signed long. // (7 semantic bits per byte * 9 bytes = 63 bits, which leaves the sign bit alone) if (bytesRead <= 9) { for (idx = 0; idx < bytesRead; idx++) { byte cur = source[idx]; accum <<= 7; accum |= (byte)(cur & 0x7F); } largeValue = null; smallValue = accum; return; } // Slow path, needs temporary storage. const int SemanticByteCount = 7; const int ContentByteCount = 8; // Every 8 content bytes turns into 7 integer bytes, so scale the count appropriately. // Add one while we're shrunk to account for the needed padding byte or the len%8 discarded bytes. int bytesRequired = ((bytesRead / ContentByteCount) + 1) * SemanticByteCount; byte[] tmpBytes = ArrayPool<byte>.Shared.Rent(bytesRequired); // Ensure all the bytes are zeroed out for BigInteger's parsing. Array.Clear(tmpBytes, 0, tmpBytes.Length); Span<byte> writeSpan = tmpBytes; Span<byte> accumValueBytes = stackalloc byte[sizeof(long)]; int nextStop = bytesRead; idx = bytesRead - ContentByteCount; while (nextStop > 0) { byte cur = source[idx]; accum <<= 7; accum |= (byte)(cur & 0x7F); idx++; if (idx >= nextStop) { Debug.Assert(idx == nextStop); Debug.Assert(writeSpan.Length >= SemanticByteCount); BinaryPrimitives.WriteInt64LittleEndian(accumValueBytes, accum); Debug.Assert(accumValueBytes[7] == 0); accumValueBytes.Slice(0, SemanticByteCount).CopyTo(writeSpan); writeSpan = writeSpan.Slice(SemanticByteCount); accum = 0; nextStop -= ContentByteCount; idx = Math.Max(0, nextStop - ContentByteCount); } } int bytesWritten = tmpBytes.Length - writeSpan.Length; // Verify our bytesRequired calculation. There should be at most 7 padding bytes. // If the length % 8 is 7 we'll have 0 padding bytes, but the sign bit is still clear. // // 8 content bytes had a sign bit problem, so we gave it a second 7-byte block, 7 remain. // 7 content bytes got a single block but used and wrote 7 bytes, but only 49 of the 56 bits. // 6 content bytes have a padding count of 1. // 1 content byte has a padding count of 6. // 0 content bytes is illegal, but see 8 for the cycle. int paddingByteCount = bytesRequired - bytesWritten; Debug.Assert(paddingByteCount >= 0 && paddingByteCount < sizeof(long)); largeValue = new BigInteger(tmpBytes); smallValue = null; Array.Clear(tmpBytes, 0, bytesWritten); ArrayPool<byte>.Shared.Return(tmpBytes); } private string ReadObjectIdentifierAsString(Asn1Tag expectedTag, out int totalBytesRead) { Asn1Tag tag = ReadTagAndLength(out int? length, out int headerLength); CheckExpectedTag(tag, expectedTag, UniversalTagNumber.ObjectIdentifier); // T-REC-X.690-201508 sec 8.19.1 // T-REC-X.690-201508 sec 8.19.2 says the minimum length is 1 if (tag.IsConstructed || length < 1) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } ReadOnlyMemory<byte> contentsMemory = Slice(_data, headerLength, length.Value); ReadOnlySpan<byte> contents = contentsMemory.Span; // Each byte can contribute a 3 digit value and a '.' (e.g. "126."), but usually // they convey one digit and a separator. // // The OID with the most arcs which were found after a 30 minute search is // "1.3.6.1.4.1.311.60.2.1.1" (EV cert jurisdiction of incorporation - locality) // which has 11 arcs. // The longest "known" segment is 16 bytes, a UUID-as-an-arc value. // 16 * 11 = 176 bytes for an "extremely long" OID. // // So pre-allocate the StringBuilder with at most 1020 characters, an input longer than // 255 encoded bytes will just have to re-allocate. StringBuilder builder = new StringBuilder(((byte)contents.Length) * 4); ReadSubIdentifier(contents, out int bytesRead, out long? smallValue, out BigInteger? largeValue); // T-REC-X.690-201508 sec 8.19.4 // The first two subidentifiers (X.Y) are encoded as (X * 40) + Y, because Y is // bounded [0, 39] for X in {0, 1}, and only X in {0, 1, 2} are legal. // So: // * identifier < 40 => X = 0, Y = identifier. // * identifier < 80 => X = 1, Y = identifier - 40. // * else: X = 2, Y = identifier - 80. byte firstArc; if (smallValue != null) { long firstIdentifier = smallValue.Value; if (firstIdentifier < 40) { firstArc = 0; } else if (firstIdentifier < 80) { firstArc = 1; firstIdentifier -= 40; } else { firstArc = 2; firstIdentifier -= 80; } builder.Append(firstArc); builder.Append('.'); builder.Append(firstIdentifier); } else { Debug.Assert(largeValue != null); BigInteger firstIdentifier = largeValue.Value; // We're only here because we were bigger than long.MaxValue, so // we're definitely on arc 2. Debug.Assert(firstIdentifier > long.MaxValue); firstArc = 2; firstIdentifier -= 80; builder.Append(firstArc); builder.Append('.'); builder.Append(firstIdentifier.ToString()); } contents = contents.Slice(bytesRead); while (!contents.IsEmpty) { ReadSubIdentifier(contents, out bytesRead, out smallValue, out largeValue); // Exactly one should be non-null. Debug.Assert((smallValue == null) != (largeValue == null)); builder.Append('.'); if (smallValue != null) { builder.Append(smallValue.Value); } else { builder.Append(largeValue.Value.ToString()); } contents = contents.Slice(bytesRead); } totalBytesRead = headerLength + length.Value; return builder.ToString(); } } }
using System; using Avalonia.Collections; using Avalonia.Controls.Metadata; using Avalonia.Controls.Mixins; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Layout; using Avalonia.Utilities; namespace Avalonia.Controls { /// <summary> /// Enum which describes how to position the ticks in a <see cref="Slider"/>. /// </summary> public enum TickPlacement { /// <summary> /// No tick marks will appear. /// </summary> None, /// <summary> /// Tick marks will appear above the track for a horizontal <see cref="Slider"/>, or to the left of the track for a vertical <see cref="Slider"/>. /// </summary> TopLeft, /// <summary> /// Tick marks will appear below the track for a horizontal <see cref="Slider"/>, or to the right of the track for a vertical <see cref="Slider"/>. /// </summary> BottomRight, /// <summary> /// Tick marks appear on both sides of either a horizontal or vertical <see cref="Slider"/>. /// </summary> Outside } /// <summary> /// A control that lets the user select from a range of values by moving a Thumb control along a Track. /// </summary> [PseudoClasses(":vertical", ":horizontal", ":pressed")] public class Slider : RangeBase { /// <summary> /// Defines the <see cref="Orientation"/> property. /// </summary> public static readonly StyledProperty<Orientation> OrientationProperty = ScrollBar.OrientationProperty.AddOwner<Slider>(); /// <summary> /// Defines the <see cref="IsSnapToTickEnabled"/> property. /// </summary> public static readonly StyledProperty<bool> IsSnapToTickEnabledProperty = AvaloniaProperty.Register<Slider, bool>(nameof(IsSnapToTickEnabled), false); /// <summary> /// Defines the <see cref="TickFrequency"/> property. /// </summary> public static readonly StyledProperty<double> TickFrequencyProperty = AvaloniaProperty.Register<Slider, double>(nameof(TickFrequency), 0.0); /// <summary> /// Defines the <see cref="TickPlacement"/> property. /// </summary> public static readonly StyledProperty<TickPlacement> TickPlacementProperty = AvaloniaProperty.Register<TickBar, TickPlacement>(nameof(TickPlacement), 0d); /// <summary> /// Defines the <see cref="TicksProperty"/> property. /// </summary> public static readonly StyledProperty<AvaloniaList<double>> TicksProperty = TickBar.TicksProperty.AddOwner<Slider>(); // Slider required parts private bool _isDragging = false; private Track _track; private Button _decreaseButton; private Button _increaseButton; private IDisposable _decreaseButtonPressDispose; private IDisposable _decreaseButtonReleaseDispose; private IDisposable _increaseButtonSubscription; private IDisposable _increaseButtonReleaseDispose; private IDisposable _pointerMovedDispose; /// <summary> /// Initializes static members of the <see cref="Slider"/> class. /// </summary> static Slider() { PressedMixin.Attach<Slider>(); OrientationProperty.OverrideDefaultValue(typeof(Slider), Orientation.Horizontal); Thumb.DragStartedEvent.AddClassHandler<Slider>((x, e) => x.OnThumbDragStarted(e), RoutingStrategies.Bubble); Thumb.DragCompletedEvent.AddClassHandler<Slider>((x, e) => x.OnThumbDragCompleted(e), RoutingStrategies.Bubble); } /// <summary> /// Instantiates a new instance of the <see cref="Slider"/> class. /// </summary> public Slider() { UpdatePseudoClasses(Orientation); } /// <summary> /// Defines the ticks to be drawn on the tick bar. /// </summary> public AvaloniaList<double> Ticks { get => GetValue(TicksProperty); set => SetValue(TicksProperty, value); } /// <summary> /// Gets or sets the orientation of a <see cref="Slider"/>. /// </summary> public Orientation Orientation { get { return GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } /// <summary> /// Gets or sets a value that indicates whether the <see cref="Slider"/> automatically moves the <see cref="Thumb"/> to the closest tick mark. /// </summary> public bool IsSnapToTickEnabled { get { return GetValue(IsSnapToTickEnabledProperty); } set { SetValue(IsSnapToTickEnabledProperty, value); } } /// <summary> /// Gets or sets the interval between tick marks. /// </summary> public double TickFrequency { get { return GetValue(TickFrequencyProperty); } set { SetValue(TickFrequencyProperty, value); } } /// <summary> /// Gets or sets a value that indicates where to draw /// tick marks in relation to the track. /// </summary> public TickPlacement TickPlacement { get { return GetValue(TickPlacementProperty); } set { SetValue(TickPlacementProperty, value); } } /// <inheritdoc/> protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _decreaseButtonPressDispose?.Dispose(); _decreaseButtonReleaseDispose?.Dispose(); _increaseButtonSubscription?.Dispose(); _increaseButtonReleaseDispose?.Dispose(); _pointerMovedDispose?.Dispose(); _decreaseButton = e.NameScope.Find<Button>("PART_DecreaseButton"); _track = e.NameScope.Find<Track>("PART_Track"); _increaseButton = e.NameScope.Find<Button>("PART_IncreaseButton"); if (_track != null) { _track.IsThumbDragHandled = true; } if (_decreaseButton != null) { _decreaseButtonPressDispose = _decreaseButton.AddDisposableHandler(PointerPressedEvent, TrackPressed, RoutingStrategies.Tunnel); _decreaseButtonReleaseDispose = _decreaseButton.AddDisposableHandler(PointerReleasedEvent, TrackReleased, RoutingStrategies.Tunnel); } if (_increaseButton != null) { _increaseButtonSubscription = _increaseButton.AddDisposableHandler(PointerPressedEvent, TrackPressed, RoutingStrategies.Tunnel); _increaseButtonReleaseDispose = _increaseButton.AddDisposableHandler(PointerReleasedEvent, TrackReleased, RoutingStrategies.Tunnel); } _pointerMovedDispose = this.AddDisposableHandler(PointerMovedEvent, TrackMoved, RoutingStrategies.Tunnel); } private void TrackMoved(object sender, PointerEventArgs e) { if (_isDragging) { MoveToPoint(e.GetCurrentPoint(_track)); } } private void TrackReleased(object sender, PointerReleasedEventArgs e) { _isDragging = false; } private void TrackPressed(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) { MoveToPoint(e.GetCurrentPoint(_track)); _isDragging = true; } } private void MoveToPoint(PointerPoint x) { var orient = Orientation == Orientation.Horizontal; var pointDen = orient ? _track.Bounds.Width : _track.Bounds.Height; // Just add epsilon to avoid NaN in case 0/0 pointDen += double.Epsilon; var pointNum = orient ? x.Position.X : x.Position.Y; var logicalPos = MathUtilities.Clamp(pointNum / pointDen, 0.0d, 1.0d); var invert = orient ? 0 : 1; var calcVal = Math.Abs(invert - logicalPos); var range = Maximum - Minimum; var finalValue = calcVal * range + Minimum; Value = IsSnapToTickEnabled ? SnapToTick(finalValue) : finalValue; } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); if (change.Property == OrientationProperty) { UpdatePseudoClasses(change.NewValue.GetValueOrDefault<Orientation>()); } } /// <summary> /// Called when user start dragging the <see cref="Thumb"/>. /// </summary> /// <param name="e"></param> protected virtual void OnThumbDragStarted(VectorEventArgs e) { _isDragging = true; } /// <summary> /// Called when user stop dragging the <see cref="Thumb"/>. /// </summary> /// <param name="e"></param> protected virtual void OnThumbDragCompleted(VectorEventArgs e) { _isDragging = false; } /// <summary> /// Snap the input 'value' to the closest tick. /// </summary> /// <param name="value">Value that want to snap to closest Tick.</param> private double SnapToTick(double value) { if (IsSnapToTickEnabled) { double previous = Minimum; double next = Maximum; // This property is rarely set so let's try to avoid the GetValue var ticks = Ticks; // If ticks collection is available, use it. // Note that ticks may be unsorted. if ((ticks != null) && (ticks.Count > 0)) { for (int i = 0; i < ticks.Count; i++) { double tick = ticks[i]; if (MathUtilities.AreClose(tick, value)) { return value; } if (MathUtilities.LessThan(tick, value) && MathUtilities.GreaterThan(tick, previous)) { previous = tick; } else if (MathUtilities.GreaterThan(tick, value) && MathUtilities.LessThan(tick, next)) { next = tick; } } } else if (MathUtilities.GreaterThan(TickFrequency, 0.0)) { previous = Minimum + (Math.Round(((value - Minimum) / TickFrequency)) * TickFrequency); next = Math.Min(Maximum, previous + TickFrequency); } // Choose the closest value between previous and next. If tie, snap to 'next'. value = MathUtilities.GreaterThanOrClose(value, (previous + next) * 0.5) ? next : previous; } return value; } private void UpdatePseudoClasses(Orientation o) { PseudoClasses.Set(":vertical", o == Orientation.Vertical); PseudoClasses.Set(":horizontal", o == Orientation.Horizontal); } } }
// 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.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudioTools; namespace Microsoft.NodejsTools.Debugger.DebugEngine { // This class represents a pending breakpoint which is an abstract representation of a breakpoint before it is bound. // When a user creates a new breakpoint, the pending breakpoint is created and is later bound. The bound breakpoints // become children of the pending breakpoint. internal class AD7PendingBreakpoint : IDebugPendingBreakpoint2 { // The breakpoint request that resulted in this pending breakpoint being created. private readonly BreakpointManager _bpManager; private readonly IDebugBreakpointRequest2 _bpRequest; private readonly List<AD7BreakpointErrorEvent> _breakpointErrors = new List<AD7BreakpointErrorEvent>(); private readonly AD7Engine _engine; private BP_REQUEST_INFO _bpRequestInfo; private NodeBreakpoint _breakpoint; private string _documentName; private bool _enabled, _deleted; public AD7PendingBreakpoint(IDebugBreakpointRequest2 pBpRequest, AD7Engine engine, BreakpointManager bpManager) { this._bpRequest = pBpRequest; var requestInfo = new BP_REQUEST_INFO[1]; EngineUtils.CheckOk(this._bpRequest.GetRequestInfo(enum_BPREQI_FIELDS.BPREQI_BPLOCATION | enum_BPREQI_FIELDS.BPREQI_CONDITION | enum_BPREQI_FIELDS.BPREQI_ALLFIELDS, requestInfo)); this._bpRequestInfo = requestInfo[0]; this._engine = engine; this._bpManager = bpManager; this._enabled = true; this._deleted = false; } public BP_PASSCOUNT PassCount => this._bpRequestInfo.bpPassCount; public string DocumentName { get { if (this._documentName == null) { var docPosition = (IDebugDocumentPosition2)(Marshal.GetObjectForIUnknown(this._bpRequestInfo.bpLocation.unionmember2)); EngineUtils.CheckOk(docPosition.GetFileName(out this._documentName)); } return this._documentName; } } #region IDebugPendingBreakpoint2 Members // Binds this pending breakpoint to one or more code locations. int IDebugPendingBreakpoint2.Bind() { if (CanBind()) { // Get the location in the document that the breakpoint is in. var startPosition = new TEXT_POSITION[1]; var endPosition = new TEXT_POSITION[1]; var docPosition = (IDebugDocumentPosition2)(Marshal.GetObjectForIUnknown(this._bpRequestInfo.bpLocation.unionmember2)); EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition)); EngineUtils.CheckOk(docPosition.GetFileName(out var fileName)); this._breakpoint = this._engine.Process.AddBreakpoint( fileName, (int)startPosition[0].dwLine, (int)startPosition[0].dwColumn, this._enabled, AD7BoundBreakpoint.GetBreakOnForPassCount(this._bpRequestInfo.bpPassCount), this._bpRequestInfo.bpCondition.bstrCondition); this._bpManager.AddPendingBreakpoint(this._breakpoint, this); this._breakpoint.BindAsync().WaitAsync(TimeSpan.FromSeconds(2)).Wait(); return VSConstants.S_OK; } // The breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc... // The sample engine does not support this, but a real world engine will want to send an instance of IDebugBreakpointErrorEvent2 to the // UI and return a valid instance of IDebugErrorBreakpoint2 from IDebugPendingBreakpoint2::EnumErrorBreakpoints. The debugger will then // display information about why the breakpoint did not bind to the user. return VSConstants.S_FALSE; } // Determines whether this pending breakpoint can bind to a code location. int IDebugPendingBreakpoint2.CanBind(out IEnumDebugErrorBreakpoints2 ppErrorEnum) { ppErrorEnum = null; if (!CanBind()) { // Called to determine if a pending breakpoint can be bound. // The breakpoint may not be bound for many reasons such as an invalid location, an invalid expression, etc... // The sample engine does not support this, but a real world engine will want to return a valid enumeration of IDebugErrorBreakpoint2. // The debugger will then display information about why the breakpoint did not bind to the user. return VSConstants.S_FALSE; } return VSConstants.S_OK; } // Deletes this pending breakpoint and all breakpoints bound from it. int IDebugPendingBreakpoint2.Delete() { ClearBreakpointBindingResults(); this._deleted = true; return VSConstants.S_OK; } // Toggles the enabled state of this pending breakpoint. int IDebugPendingBreakpoint2.Enable(int fEnable) { this._enabled = fEnable != 0; if (this._breakpoint != null) { lock (this._breakpoint) { foreach (var binding in this._breakpoint.GetBindings()) { var boundBreakpoint = (IDebugBoundBreakpoint2)this._bpManager.GetBoundBreakpoint(binding); boundBreakpoint.Enable(fEnable); } } } return VSConstants.S_OK; } // Enumerates all breakpoints bound from this pending breakpoint int IDebugPendingBreakpoint2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) { ppEnum = null; if (this._breakpoint != null) { lock (this._breakpoint) { var boundBreakpoints = this._breakpoint.GetBindings() .Select(binding => this._bpManager.GetBoundBreakpoint(binding)) .Cast<IDebugBoundBreakpoint2>().ToArray(); ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints); } } return VSConstants.S_OK; } // Enumerates all error breakpoints that resulted from this pending breakpoint. int IDebugPendingBreakpoint2.EnumErrorBreakpoints(enum_BP_ERROR_TYPE bpErrorType, out IEnumDebugErrorBreakpoints2 ppEnum) { // Called when a pending breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc... // Return a valid enumeration of IDebugErrorBreakpoint2 from IDebugPendingBreakpoint2::EnumErrorBreakpoints, allowing the debugger to // display information about why the breakpoint did not bind to the user. lock (this._breakpointErrors) { var breakpointErrors = this._breakpointErrors.Cast<IDebugErrorBreakpoint2>().ToArray(); ppEnum = new AD7ErrorBreakpointsEnum(breakpointErrors); } return VSConstants.S_OK; } // Gets the breakpoint request that was used to create this pending breakpoint int IDebugPendingBreakpoint2.GetBreakpointRequest(out IDebugBreakpointRequest2 ppBpRequest) { ppBpRequest = this._bpRequest; return VSConstants.S_OK; } // Gets the state of this pending breakpoint. int IDebugPendingBreakpoint2.GetState(PENDING_BP_STATE_INFO[] pState) { if (this._deleted) { pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_DELETED; } else if (this._enabled) { pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_ENABLED; } else { pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_DISABLED; } return VSConstants.S_OK; } int IDebugPendingBreakpoint2.SetCondition(BP_CONDITION bpCondition) { if (bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_CHANGED) { return VSConstants.E_NOTIMPL; } this._bpRequestInfo.bpCondition = bpCondition; return VSConstants.S_OK; } int IDebugPendingBreakpoint2.SetPassCount(BP_PASSCOUNT bpPassCount) { this._bpRequestInfo.bpPassCount = bpPassCount; return VSConstants.S_OK; } // Toggles the virtualized state of this pending breakpoint. When a pending breakpoint is virtualized, // the debug engine will attempt to bind it every time new code loads into the program. // The sample engine will does not support this. int IDebugPendingBreakpoint2.Virtualize(int fVirtualize) { return VSConstants.S_OK; } #endregion private bool CanBind() { // Reject binding breakpoints which are deleted, not code file line, and on condition changed if (this._deleted || this._bpRequestInfo.bpLocation.bpLocationType != (uint)enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE || this._bpRequestInfo.bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_CHANGED) { return false; } return true; } public void AddBreakpointError(AD7BreakpointErrorEvent breakpointError) { this._breakpointErrors.Add(breakpointError); } // Remove all of the bound breakpoints for this pending breakpoint public void ClearBreakpointBindingResults() { if (this._breakpoint != null) { lock (this._breakpoint) { foreach (var binding in this._breakpoint.GetBindings()) { var boundBreakpoint = (IDebugBoundBreakpoint2)this._bpManager.GetBoundBreakpoint(binding); if (boundBreakpoint != null) { boundBreakpoint.Delete(); binding.Remove().WaitAndUnwrapExceptions(); } } } this._bpManager.RemovePendingBreakpoint(this._breakpoint); this._breakpoint.Deleted = true; this._breakpoint = null; } this._breakpointErrors.Clear(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.IO; using CultureInfo = System.Globalization.CultureInfo; using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; namespace System.Xml.Linq { /// <summary> /// Represents an XML attribute. /// </summary> /// <remarks> /// An XML attribute is a name/value pair associated with an XML element. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Reviewed.")] public class XAttribute : XObject { /// <summary> /// Gets an empty collection of attributes. /// </summary> public static IEnumerable<XAttribute> EmptySequence { get { return Array.Empty<XAttribute>(); } } internal XAttribute next; internal XName name; internal string value; /// <overloads> /// Initializes a new instance of the <see cref="XAttribute"/> class. /// </overloads> /// <summary> /// Initializes a new instance of the <see cref="XAttribute"/> class from /// the specified name and value. /// </summary> /// <param name="name"> /// The name of the attribute. /// </param> /// <param name="value"> /// The value of the attribute. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown if the passed in name or value are null. /// </exception> public XAttribute(XName name, object value) { if (name == null) throw new ArgumentNullException("name"); if (value == null) throw new ArgumentNullException("value"); string s = XContainer.GetStringValue(value); ValidateAttribute(name, s); this.name = name; this.value = s; } /// <summary> /// Initializes an instance of the XAttribute class /// from another XAttribute object. /// </summary> /// <param name="other"><see cref="XAttribute"/> object to copy from.</param> /// <exception cref="ArgumentNullException"> /// Thrown if the specified <see cref="XAttribute"/> is null. /// </exception> public XAttribute(XAttribute other) { if (other == null) throw new ArgumentNullException("other"); name = other.name; value = other.value; } /// <summary> /// Gets a value indicating if this attribute is a namespace declaration. /// </summary> public bool IsNamespaceDeclaration { get { string namespaceName = name.NamespaceName; if (namespaceName.Length == 0) { return name.LocalName == "xmlns"; } return (object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace; } } /// <summary> /// Gets the name of this attribute. /// </summary> public XName Name { get { return name; } } /// <summary> /// Gets the next attribute of the parent element. /// </summary> /// <remarks> /// If this attribute does not have a parent, or if there is no next attribute, /// then this property returns null. /// </remarks> public XAttribute NextAttribute { get { return parent != null && ((XElement)parent).lastAttr != this ? next : null; } } /// <summary> /// Gets the node type for this node. /// </summary> /// <remarks> /// This property will always return XmlNodeType.Attribute. /// </remarks> public override XmlNodeType NodeType { get { return XmlNodeType.Attribute; } } /// <summary> /// Gets the previous attribute of the parent element. /// </summary> /// <remarks> /// If this attribute does not have a parent, or if there is no previous attribute, /// then this property returns null. /// </remarks> public XAttribute PreviousAttribute { get { if (parent == null) return null; XAttribute a = ((XElement)parent).lastAttr; while (a.next != this) { a = a.next; } return a != ((XElement)parent).lastAttr ? a : null; } } /// <summary> /// Gets or sets the value of this attribute. /// </summary> /// <exception cref="ArgumentNullException"> /// Thrown if the value set is null. /// </exception> public string Value { get { return value; } set { if (value == null) throw new ArgumentNullException("value"); ValidateAttribute(name, value); bool notify = NotifyChanging(this, XObjectChangeEventArgs.Value); this.value = value; if (notify) NotifyChanged(this, XObjectChangeEventArgs.Value); } } /// <summary> /// Deletes this XAttribute. /// </summary> /// <exception cref="InvalidOperationException"> /// Thrown if the parent element is null. /// </exception> public void Remove() { if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent); ((XElement)parent).RemoveAttribute(this); } /// <summary> /// Sets the value of this <see cref="XAttribute"/>. /// <seealso cref="XElement.SetValue"/> /// <seealso cref="XElement.SetAttributeValue"/> /// <seealso cref="XElement.SetElementValue"/> /// </summary> /// <param name="value"> /// The value to assign to this attribute. The value is converted to its string /// representation and assigned to the <see cref="Value"/> property. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown if the specified value is null. /// </exception> public void SetValue(object value) { if (value == null) throw new ArgumentNullException("value"); Value = XContainer.GetStringValue(value); } /// <summary> /// Override for <see cref="ToString()"/> on <see cref="XAttribute"/> /// </summary> /// <returns>XML text representation of an attribute and its value</returns> public override string ToString() { using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) { XmlWriterSettings ws = new XmlWriterSettings(); ws.ConformanceLevel = ConformanceLevel.Fragment; using (XmlWriter w = XmlWriter.Create(sw, ws)) { w.WriteAttributeString(GetPrefixOfNamespace(name.Namespace), name.LocalName, name.NamespaceName, value); } return sw.ToString().Trim(); } } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="string"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="string"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="string"/>. /// </returns> [CLSCompliant(false)] public static explicit operator string (XAttribute attribute) { if (attribute == null) return null; return attribute.value; } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="bool"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="bool"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="bool"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator bool (XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant()); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="bool"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="bool"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="bool"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator bool? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant()); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to an <see cref="int"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="int"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as an <see cref="int"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator int (XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToInt32(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to an <see cref="int"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="int"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as an <see cref="int"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator int? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToInt32(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to an <see cref="uint"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="uint"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as an <see cref="uint"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator uint (XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToUInt32(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to an <see cref="uint"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="uint"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as an <see cref="uint"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator uint? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToUInt32(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="long"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="long"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="long"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator long (XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToInt64(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="long"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="long"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="long"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator long? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToInt64(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to an <see cref="ulong"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="ulong"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as an <see cref="ulong"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator ulong (XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToUInt64(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to an <see cref="ulong"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="ulong"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as an <see cref="ulong"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator ulong? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToUInt64(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="float"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="float"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="float"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator float (XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToSingle(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="float"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="float"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="float"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator float? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToSingle(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="double"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="double"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="double"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator double (XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToDouble(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="double"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="double"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="double"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator double? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToDouble(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="decimal"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="decimal"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="decimal"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator decimal (XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToDecimal(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="decimal"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="decimal"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="decimal"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator decimal? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToDecimal(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="DateTime"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="DateTime"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="DateTime"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator DateTime(XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="DateTime"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="DateTime"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="DateTime"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator DateTime? (XAttribute attribute) { if (attribute == null) return null; return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="DateTimeOffset"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="DateTimeOffset"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="DateTimeOffset"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator DateTimeOffset(XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToDateTimeOffset(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="DateTimeOffset"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="DateTimeOffset"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="DateTimeOffset"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator DateTimeOffset? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToDateTimeOffset(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="TimeSpan"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="TimeSpan"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="TimeSpan"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator TimeSpan(XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToTimeSpan(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="TimeSpan"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="TimeSpan"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="TimeSpan"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator TimeSpan? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToTimeSpan(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="Guid"/>. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="Guid"/>. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="Guid"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the specified attribute is null. /// </exception> [CLSCompliant(false)] public static explicit operator Guid(XAttribute attribute) { if (attribute == null) throw new ArgumentNullException("attribute"); return XmlConvert.ToGuid(attribute.value); } /// <summary> /// Cast the value of this <see cref="XAttribute"/> to a <see cref="Guid"/>?. /// </summary> /// <param name="attribute"> /// The <see cref="XAttribute"/> to cast to <see cref="Guid"/>?. Can be null. /// </param> /// <returns> /// The content of this <see cref="XAttribute"/> as a <see cref="Guid"/>?. /// </returns> [CLSCompliant(false)] public static explicit operator Guid? (XAttribute attribute) { if (attribute == null) return null; return XmlConvert.ToGuid(attribute.value); } internal int GetDeepHashCode() { return name.GetHashCode() ^ value.GetHashCode(); } internal string GetPrefixOfNamespace(XNamespace ns) { string namespaceName = ns.NamespaceName; if (namespaceName.Length == 0) return string.Empty; if (parent != null) return ((XElement)parent).GetPrefixOfNamespace(ns); if ((object)namespaceName == (object)XNamespace.xmlPrefixNamespace) return "xml"; if ((object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace) return "xmlns"; return null; } private static void ValidateAttribute(XName name, string value) { // The following constraints apply for namespace declarations: string namespaceName = name.NamespaceName; if ((object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace) { if (value.Length == 0) { // The empty namespace name can only be declared by // the default namespace declaration throw new ArgumentException(SR.Format(SR.Argument_NamespaceDeclarationPrefixed, name.LocalName)); } else if (value == XNamespace.xmlPrefixNamespace) { // 'http://www.w3.org/XML/1998/namespace' can only // be declared by the 'xml' prefix namespace declaration. if (name.LocalName != "xml") throw new ArgumentException(SR.Argument_NamespaceDeclarationXml); } else if (value == XNamespace.xmlnsPrefixNamespace) { // 'http://www.w3.org/2000/xmlns/' must not be declared // by any namespace declaration. throw new ArgumentException(SR.Argument_NamespaceDeclarationXmlns); } else { string localName = name.LocalName; if (localName == "xml") { // No other namespace name can be declared by the 'xml' // prefix namespace declaration. throw new ArgumentException(SR.Argument_NamespaceDeclarationXml); } else if (localName == "xmlns") { // The 'xmlns' prefix must not be declared. throw new ArgumentException(SR.Argument_NamespaceDeclarationXmlns); } } } else if (namespaceName.Length == 0 && name.LocalName == "xmlns") { if (value == XNamespace.xmlPrefixNamespace) { // 'http://www.w3.org/XML/1998/namespace' can only // be declared by the 'xml' prefix namespace declaration. throw new ArgumentException(SR.Argument_NamespaceDeclarationXml); } else if (value == XNamespace.xmlnsPrefixNamespace) { // 'http://www.w3.org/2000/xmlns/' must not be declared // by any namespace declaration. throw new ArgumentException(SR.Argument_NamespaceDeclarationXmlns); } } } } }
/* * 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.Xml; using System.Xml.Serialization; using OpenMetaverse; namespace OpenSim.Framework { /// <summary> /// Details of a Parcel of land /// </summary> public class LandData { // use only one serializer to give the runtime a chance to // optimize it (it won't do that if you use a new instance // every time) private static XmlSerializer serializer = new XmlSerializer(typeof (LandData)); private Vector3 _AABBMax = new Vector3(); private Vector3 _AABBMin = new Vector3(); private int _area = 0; private uint _auctionID = 0; //Unemplemented. If set to 0, not being auctioned private UUID _authBuyerID = UUID.Zero; //Unemplemented. Authorized Buyer's UUID private ParcelCategory _category = ParcelCategory.None; //Unemplemented. Parcel's chosen category private int _claimDate = 0; private int _claimPrice = 0; //Unemplemented private UUID _globalID = UUID.Zero; private UUID _groupID = UUID.Zero; private int _groupPrims = 0; private bool _isGroupOwned = false; private byte[] _bitmap = new byte[512]; private string _description = String.Empty; private uint _flags = (uint) ParcelFlags.AllowFly | (uint) ParcelFlags.AllowLandmark | (uint) ParcelFlags.AllowAPrimitiveEntry | (uint) ParcelFlags.AllowDeedToGroup | (uint) ParcelFlags.AllowTerraform | (uint) ParcelFlags.CreateObjects | (uint) ParcelFlags.AllowOtherScripts | (uint) ParcelFlags.SoundLocal; private byte _landingType = 0; private string _name = "Your Parcel"; private ParcelStatus _status = ParcelStatus.Leased; private int _localID = 0; private byte _mediaAutoScale = 0; private UUID _mediaID = UUID.Zero; private string _mediaURL = String.Empty; private string _musicURL = String.Empty; private int _otherPrims = 0; private UUID _ownerID = UUID.Zero; private int _ownerPrims = 0; private List<ParcelManager.ParcelAccessEntry> _parcelAccessList = new List<ParcelManager.ParcelAccessEntry>(); private float _passHours = 0; private int _passPrice = 0; private int _salePrice = 0; //Unemeplemented. Parcels price. private int _selectedPrims = 0; private int _simwideArea = 0; private int _simwidePrims = 0; private UUID _snapshotID = UUID.Zero; private Vector3 _userLocation = new Vector3(); private Vector3 _userLookAt = new Vector3(); private int _otherCleanTime = 0; private string _mediaType = "none/none"; private string _mediaDescription = ""; private int _mediaHeight = 0; private int _mediaWidth = 0; private bool _mediaLoop = false; private bool _obscureMusic = false; private bool _obscureMedia = false; /// <summary> /// Whether to obscure parcel media URL /// </summary> [XmlIgnore] public bool ObscureMedia { get { return _obscureMedia; } set { _obscureMedia = value; } } /// <summary> /// Whether to obscure parcel music URL /// </summary> [XmlIgnore] public bool ObscureMusic { get { return _obscureMusic; } set { _obscureMusic = value; } } /// <summary> /// Whether to loop parcel media /// </summary> [XmlIgnore] public bool MediaLoop { get { return _mediaLoop; } set { _mediaLoop = value; } } /// <summary> /// Height of parcel media render /// </summary> [XmlIgnore] public int MediaHeight { get { return _mediaHeight; } set { _mediaHeight = value; } } /// <summary> /// Width of parcel media render /// </summary> [XmlIgnore] public int MediaWidth { get { return _mediaWidth; } set { _mediaWidth = value; } } /// <summary> /// Upper corner of the AABB for the parcel /// </summary> [XmlIgnore] public Vector3 AABBMax { get { return _AABBMax; } set { _AABBMax = value; } } /// <summary> /// Lower corner of the AABB for the parcel /// </summary> [XmlIgnore] public Vector3 AABBMin { get { return _AABBMin; } set { _AABBMin = value; } } /// <summary> /// Area in meters^2 the parcel contains /// </summary> public int Area { get { return _area; } set { _area = value; } } /// <summary> /// ID of auction (3rd Party Integration) when parcel is being auctioned /// </summary> public uint AuctionID { get { return _auctionID; } set { _auctionID = value; } } /// <summary> /// UUID of authorized buyer of parcel. This is UUID.Zero if anyone can buy it. /// </summary> public UUID AuthBuyerID { get { return _authBuyerID; } set { _authBuyerID = value; } } /// <summary> /// Category of parcel. Used for classifying the parcel in classified listings /// </summary> public ParcelCategory Category { get { return _category; } set { _category = value; } } /// <summary> /// Date that the current owner purchased or claimed the parcel /// </summary> public int ClaimDate { get { return _claimDate; } set { _claimDate = value; } } /// <summary> /// The last price that the parcel was sold at /// </summary> public int ClaimPrice { get { return _claimPrice; } set { _claimPrice = value; } } /// <summary> /// Global ID for the parcel. (3rd Party Integration) /// </summary> public UUID GlobalID { get { return _globalID; } set { _globalID = value; } } /// <summary> /// Unique ID of the Group that owns /// </summary> public UUID GroupID { get { return _groupID; } set { _groupID = value; } } /// <summary> /// Number of SceneObjectPart that are owned by a Group /// </summary> [XmlIgnore] public int GroupPrims { get { return _groupPrims; } set { _groupPrims = value; } } /// <summary> /// Returns true if the Land Parcel is owned by a group /// </summary> public bool IsGroupOwned { get { return _isGroupOwned; } set { _isGroupOwned = value; } } /// <summary> /// jp2 data for the image representative of the parcel in the parcel dialog /// </summary> public byte[] Bitmap { get { return _bitmap; } set { _bitmap = value; } } /// <summary> /// Parcel Description /// </summary> public string Description { get { return _description; } set { _description = value; } } /// <summary> /// Parcel settings. Access flags, Fly, NoPush, Voice, Scripts allowed, etc. ParcelFlags /// </summary> public uint Flags { get { return _flags; } set { _flags = value; } } /// <summary> /// Determines if people are able to teleport where they please on the parcel or if they /// get constrainted to a specific point on teleport within the parcel /// </summary> public byte LandingType { get { return _landingType; } set { _landingType = value; } } /// <summary> /// Parcel Name /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Status of Parcel, Leased, Abandoned, For Sale /// </summary> public ParcelStatus Status { get { return _status; } set { _status = value; } } /// <summary> /// Internal ID of the parcel. Sometimes the client will try to use this value /// </summary> public int LocalID { get { return _localID; } set { _localID = value; } } /// <summary> /// Determines if we scale the media based on the surface it's on /// </summary> public byte MediaAutoScale { get { return _mediaAutoScale; } set { _mediaAutoScale = value; } } /// <summary> /// Texture Guid to replace with the output of the media stream /// </summary> public UUID MediaID { get { return _mediaID; } set { _mediaID = value; } } /// <summary> /// URL to the media file to display /// </summary> public string MediaURL { get { return _mediaURL; } set { _mediaURL = value; } } public string MediaType { get { return _mediaType; } set { _mediaType = value; } } /// <summary> /// URL to the shoutcast music stream to play on the parcel /// </summary> public string MusicURL { get { return _musicURL; } set { _musicURL = value; } } /// <summary> /// Number of SceneObjectPart that are owned by users who do not own the parcel /// and don't have the 'group. These are elegable for AutoReturn collection /// </summary> [XmlIgnore] public int OtherPrims { get { return _otherPrims; } set { _otherPrims = value; } } /// <summary> /// Owner Avatar or Group of the parcel. Naturally, all land masses must be /// owned by someone /// </summary> public UUID OwnerID { get { return _ownerID; } set { _ownerID = value; } } /// <summary> /// Number of SceneObjectPart that are owned by the owner of the parcel /// </summary> [XmlIgnore] public int OwnerPrims { get { return _ownerPrims; } set { _ownerPrims = value; } } /// <summary> /// List of access data for the parcel. User data, some bitflags, and a time /// </summary> public List<ParcelManager.ParcelAccessEntry> ParcelAccessList { get { return _parcelAccessList; } set { _parcelAccessList = value; } } /// <summary> /// How long in hours a Pass to the parcel is given /// </summary> public float PassHours { get { return _passHours; } set { _passHours = value; } } /// <summary> /// Price to purchase a Pass to a restricted parcel /// </summary> public int PassPrice { get { return _passPrice; } set { _passPrice = value; } } /// <summary> /// When the parcel is being sold, this is the price to purchase the parcel /// </summary> public int SalePrice { get { return _salePrice; } set { _salePrice = value; } } /// <summary> /// Number of SceneObjectPart that are currently selected by avatar /// </summary> [XmlIgnore] public int SelectedPrims { get { return _selectedPrims; } set { _selectedPrims = value; } } /// <summary> /// Number of meters^2 in the Simulator /// </summary> [XmlIgnore] public int SimwideArea { get { return _simwideArea; } set { _simwideArea = value; } } /// <summary> /// Number of SceneObjectPart in the Simulator /// </summary> [XmlIgnore] public int SimwidePrims { get { return _simwidePrims; } set { _simwidePrims = value; } } /// <summary> /// ID of the snapshot used in the client parcel dialog of the parcel /// </summary> public UUID SnapshotID { get { return _snapshotID; } set { _snapshotID = value; } } /// <summary> /// When teleporting is restricted to a certain point, this is the location /// that the user will be redirected to /// </summary> public Vector3 UserLocation { get { return _userLocation; } set { _userLocation = value; } } /// <summary> /// When teleporting is restricted to a certain point, this is the rotation /// that the user will be positioned /// </summary> public Vector3 UserLookAt { get { return _userLookAt; } set { _userLookAt = value; } } /// <summary> /// Number of minutes to return SceneObjectGroup that are owned by someone who doesn't own /// the parcel and isn't set to the same 'group' as the parcel. /// </summary> public int OtherCleanTime { get { return _otherCleanTime; } set { _otherCleanTime = value; } } /// <summary> /// parcel media description /// </summary> public string MediaDescription { get { return _mediaDescription; } set { _mediaDescription = value; } } public LandData() { _globalID = UUID.Random(); } /// <summary> /// Make a new copy of the land data /// </summary> /// <returns></returns> public LandData Copy() { LandData landData = new LandData(); landData._AABBMax = _AABBMax; landData._AABBMin = _AABBMin; landData._area = _area; landData._auctionID = _auctionID; landData._authBuyerID = _authBuyerID; landData._category = _category; landData._claimDate = _claimDate; landData._claimPrice = _claimPrice; landData._globalID = _globalID; landData._groupID = _groupID; landData._groupPrims = _groupPrims; landData._otherPrims = _otherPrims; landData._ownerPrims = _ownerPrims; landData._selectedPrims = _selectedPrims; landData._isGroupOwned = _isGroupOwned; landData._localID = _localID; landData._landingType = _landingType; landData._mediaAutoScale = _mediaAutoScale; landData._mediaID = _mediaID; landData._mediaURL = _mediaURL; landData._musicURL = _musicURL; landData._ownerID = _ownerID; landData._bitmap = (byte[]) _bitmap.Clone(); landData._description = _description; landData._flags = _flags; landData._name = _name; landData._status = _status; landData._passHours = _passHours; landData._passPrice = _passPrice; landData._salePrice = _salePrice; landData._snapshotID = _snapshotID; landData._userLocation = _userLocation; landData._userLookAt = _userLookAt; landData._otherCleanTime = _otherCleanTime; landData._mediaType = _mediaType; landData._mediaDescription = _mediaDescription; landData._mediaWidth = _mediaWidth; landData._mediaHeight = _mediaHeight; landData._mediaLoop = _mediaLoop; landData._obscureMusic = _obscureMusic; landData._obscureMedia = _obscureMedia; landData._parcelAccessList.Clear(); foreach (ParcelManager.ParcelAccessEntry entry in _parcelAccessList) { ParcelManager.ParcelAccessEntry newEntry = new ParcelManager.ParcelAccessEntry(); newEntry.AgentID = entry.AgentID; newEntry.Flags = entry.Flags; newEntry.Time = entry.Time; landData._parcelAccessList.Add(newEntry); } return landData; } public void ToXml(XmlWriter xmlWriter) { serializer.Serialize(xmlWriter, this); } /// <summary> /// Restore a LandData object from the serialized xml representation. /// </summary> /// <param name="xmlReader"></param> /// <returns></returns> public static LandData FromXml(XmlReader xmlReader) { LandData land = (LandData)serializer.Deserialize(xmlReader); return land; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // CryptoAPITransform.cs // namespace System.Security.Cryptography { using System.Security.AccessControl; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; #if FEATURE_MACL && FEATURE_CRYPTO [Serializable] internal enum CryptoAPITransformMode { Encrypt = 0, Decrypt = 1 } [System.Runtime.InteropServices.ComVisible(true)] public sealed class CryptoAPITransform : ICryptoTransform { private int BlockSizeValue; private byte[] IVValue; private CipherMode ModeValue; private PaddingMode PaddingValue; private CryptoAPITransformMode encryptOrDecrypt; private byte[] _rgbKey; private byte[] _depadBuffer = null; [System.Security.SecurityCritical] // auto-generated private SafeKeyHandle _safeKeyHandle; [System.Security.SecurityCritical] // auto-generated private SafeProvHandle _safeProvHandle; private CryptoAPITransform () {} [System.Security.SecurityCritical] // auto-generated internal CryptoAPITransform(int algid, int cArgs, int[] rgArgIds, Object[] rgArgValues, byte[] rgbKey, PaddingMode padding, CipherMode cipherChainingMode, int blockSize, int feedbackSize, bool useSalt, CryptoAPITransformMode encDecMode) { int dwValue; byte[] rgbValue; BlockSizeValue = blockSize; ModeValue = cipherChainingMode; PaddingValue = padding; encryptOrDecrypt = encDecMode; // Copy the input args int _cArgs = cArgs; int[] _rgArgIds = new int[rgArgIds.Length]; Array.Copy(rgArgIds, _rgArgIds, rgArgIds.Length); _rgbKey = new byte[rgbKey.Length]; Array.Copy(rgbKey, _rgbKey, rgbKey.Length); Object[] _rgArgValues = new Object[rgArgValues.Length]; // an element of rgArgValues can only be an int or a byte[] for (int j = 0; j < rgArgValues.Length; j++) { if (rgArgValues[j] is byte[]) { byte[] rgbOrig = (byte[]) rgArgValues[j]; byte[] rgbNew = new byte[rgbOrig.Length]; Array.Copy(rgbOrig, rgbNew, rgbOrig.Length); _rgArgValues[j] = rgbNew; continue; } if (rgArgValues[j] is int) { _rgArgValues[j] = (int) rgArgValues[j]; continue; } if (rgArgValues[j] is CipherMode) { _rgArgValues[j] = (int) rgArgValues[j]; continue; } } _safeProvHandle = Utils.AcquireProvHandle(new CspParameters(Utils.DefaultRsaProviderType)); SafeKeyHandle safeKeyHandle = SafeKeyHandle.InvalidHandle; // _ImportBulkKey will check for failures and throw an exception Utils._ImportBulkKey(_safeProvHandle, algid, useSalt, _rgbKey, ref safeKeyHandle); _safeKeyHandle = safeKeyHandle; for (int i=0; i<cArgs; i++) { switch (rgArgIds[i]) { case Constants.KP_IV: IVValue = (byte[]) _rgArgValues[i]; rgbValue = IVValue; Utils.SetKeyParamRgb(_safeKeyHandle, _rgArgIds[i], rgbValue, rgbValue.Length); break; case Constants.KP_MODE: ModeValue = (CipherMode) _rgArgValues[i]; dwValue = (Int32) _rgArgValues[i]; SetAsDWord: Utils.SetKeyParamDw(_safeKeyHandle, _rgArgIds[i], dwValue); break; case Constants.KP_MODE_BITS: dwValue = (Int32) _rgArgValues[i]; goto SetAsDWord; case Constants.KP_EFFECTIVE_KEYLEN: dwValue = (Int32) _rgArgValues[i]; goto SetAsDWord; default: throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeyParameter"), "_rgArgIds[i]"); } } } public void Dispose() { Clear(); } [System.Security.SecuritySafeCritical] // auto-generated public void Clear() { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecurityCritical] // auto-generated private void Dispose(bool disposing) { if (disposing) { // We need to always zeroize the following fields because they contain sensitive data if (_rgbKey != null) { Array.Clear(_rgbKey,0,_rgbKey.Length); _rgbKey = null; } if (IVValue != null) { Array.Clear(IVValue,0,IVValue.Length); IVValue = null; } if (_depadBuffer != null) { Array.Clear(_depadBuffer, 0, _depadBuffer.Length); _depadBuffer = null; } if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) { _safeKeyHandle.Dispose(); } if (_safeProvHandle != null && !_safeProvHandle.IsClosed) { _safeProvHandle.Dispose(); } } } // // public properties // public IntPtr KeyHandle { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] get { return _safeKeyHandle.DangerousGetHandle(); } } public int InputBlockSize { get { return(BlockSizeValue/8); } } public int OutputBlockSize { get { return(BlockSizeValue/8); } } public bool CanTransformMultipleBlocks { get { return(true); } } public bool CanReuseTransform { get { return(true); } } // // public methods // // This routine resets the internal state of the CryptoAPITransform [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] public void Reset() { _depadBuffer = null; // just ensure we've called CryptEncrypt with the true flag byte[] temp = null; Utils._EncryptData(_safeKeyHandle, EmptyArray<Byte>.Value, 0, 0, ref temp, 0, PaddingValue, true); } [System.Security.SecuritySafeCritical] // auto-generated public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { // Note: special handling required if decrypting & using padding because the padding adds to the end of the last // block, we have to buffer an entire block's worth of bytes in case what I just transformed turns out to be // the last block Then in TransformFinalBlock we strip off the padding. if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (outputBuffer == null) throw new ArgumentNullException("outputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ((inputCount <= 0) || (inputCount % InputBlockSize != 0) || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (encryptOrDecrypt == CryptoAPITransformMode.Encrypt) { // if we're encrypting we can always push out the bytes because no padding mode // removes bytes during encryption return Utils._EncryptData(_safeKeyHandle, inputBuffer, inputOffset, inputCount, ref outputBuffer, outputOffset, PaddingValue, false); } else { if (PaddingValue == PaddingMode.Zeros || PaddingValue == PaddingMode.None) { // like encryption, if we're using None or Zeros padding on decrypt we can write out all // the bytes. Note that we cannot depad a block partially padded with Zeros because // we can't tell if those zeros are plaintext or pad. return Utils._DecryptData(_safeKeyHandle, inputBuffer, inputOffset, inputCount, ref outputBuffer, outputOffset, PaddingValue, false); } else { // OK, now we're in the special case. Check to see if this is the *first* block we've seen // If so, buffer it and return null zero bytes if (_depadBuffer == null) { _depadBuffer = new byte[InputBlockSize]; // copy the last InputBlockSize bytes to _depadBuffer everything else gets processed and returned int inputToProcess = inputCount - InputBlockSize; Buffer.InternalBlockCopy(inputBuffer, inputOffset+inputToProcess, _depadBuffer, 0, InputBlockSize); return Utils._DecryptData(_safeKeyHandle, inputBuffer, inputOffset, inputToProcess, ref outputBuffer, outputOffset, PaddingValue, false); } else { // we already have a depad buffer, so we need to decrypt that info first & copy it out int r = Utils._DecryptData(_safeKeyHandle, _depadBuffer, 0, _depadBuffer.Length, ref outputBuffer, outputOffset, PaddingValue, false); outputOffset += OutputBlockSize; int inputToProcess = inputCount - InputBlockSize; Buffer.InternalBlockCopy(inputBuffer, inputOffset+inputToProcess, _depadBuffer, 0, InputBlockSize); r = Utils._DecryptData(_safeKeyHandle, inputBuffer, inputOffset, inputToProcess, ref outputBuffer, outputOffset, PaddingValue, false); return (OutputBlockSize + r); } } } } [System.Security.SecuritySafeCritical] // auto-generated public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ((inputCount < 0) || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (encryptOrDecrypt == CryptoAPITransformMode.Encrypt) { // If we're encrypting we can always return what we compute because there's no _depadBuffer byte[] transformedBytes = null; Utils._EncryptData(_safeKeyHandle, inputBuffer, inputOffset, inputCount, ref transformedBytes, 0, PaddingValue, true); Reset(); return transformedBytes; } else { if (inputCount%InputBlockSize != 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_SSD_InvalidDataSize")); if (_depadBuffer == null) { byte[] transformedBytes = null; Utils._DecryptData(_safeKeyHandle, inputBuffer, inputOffset, inputCount, ref transformedBytes, 0, PaddingValue, true); Reset(); return transformedBytes; } else { byte[] temp = new byte[_depadBuffer.Length + inputCount]; Buffer.InternalBlockCopy(_depadBuffer, 0, temp, 0, _depadBuffer.Length); Buffer.InternalBlockCopy(inputBuffer, inputOffset, temp, _depadBuffer.Length, inputCount); byte[] transformedBytes = null; Utils._DecryptData(_safeKeyHandle, temp, 0, temp.Length, ref transformedBytes, 0, PaddingValue, true); Reset(); return transformedBytes; } } } } #endif // FEATURE_MACL && FEATURE_CRYPTO [Serializable] [System.Runtime.InteropServices.ComVisible(true)] [Flags] public enum CspProviderFlags { NoFlags = 0x0000, UseMachineKeyStore = 0x0001, UseDefaultKeyContainer = 0x0002, UseNonExportableKey = 0x0004, UseExistingKey = 0x0008, UseArchivableKey = 0x0010, UseUserProtectedKey = 0x0020, NoPrompt = 0x0040, CreateEphemeralKey = 0x0080 } [System.Runtime.InteropServices.ComVisible(true)] public sealed class CspParameters { public int ProviderType; public string ProviderName; [ResourceExposure(ResourceScope.Machine)] public string KeyContainerName; public int KeyNumber; private int m_flags; public CspProviderFlags Flags { get { return (CspProviderFlags) m_flags; } set { int allFlags = 0x00FF; // this should change if more values are added to CspProviderFlags Contract.Assert((CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseDefaultKeyContainer | CspProviderFlags.UseNonExportableKey | CspProviderFlags.UseExistingKey | CspProviderFlags.UseArchivableKey | CspProviderFlags.UseUserProtectedKey | CspProviderFlags.NoPrompt | CspProviderFlags.CreateEphemeralKey) == (CspProviderFlags)allFlags, "allFlags does not match all CspProviderFlags"); int flags = (int) value; if ((flags & ~allFlags) != 0) throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)value), "value"); m_flags = flags; } } #if FEATURE_MACL || MONO private CryptoKeySecurity m_cryptoKeySecurity; public CryptoKeySecurity CryptoKeySecurity { get { return m_cryptoKeySecurity; } set { m_cryptoKeySecurity = value; } } #endif #if FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS private SecureString m_keyPassword; public SecureString KeyPassword { get { return m_keyPassword; } set { m_keyPassword = value; // Parent handle and PIN are mutually exclusive. m_parentWindowHandle = IntPtr.Zero; } } private IntPtr m_parentWindowHandle; public IntPtr ParentWindowHandle { [ResourceExposure(ResourceScope.Machine)] get { return m_parentWindowHandle; } [ResourceExposure(ResourceScope.Machine)] set { m_parentWindowHandle = value; // Parent handle and PIN are mutually exclusive. m_keyPassword = null; } } #endif [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public CspParameters () : this(Utils.DefaultRsaProviderType, null, null) {} [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public CspParameters (int dwTypeIn) : this(dwTypeIn, null, null) {} [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public CspParameters (int dwTypeIn, string strProviderNameIn) : this(dwTypeIn, strProviderNameIn, null) {} [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public CspParameters (int dwTypeIn, string strProviderNameIn, string strContainerNameIn) : this (dwTypeIn, strProviderNameIn, strContainerNameIn, CspProviderFlags.NoFlags) {} #if MONO || (FEATURE_MACL && FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS) [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public CspParameters (int providerType, string providerName, string keyContainerName, CryptoKeySecurity cryptoKeySecurity, SecureString keyPassword) : this (providerType, providerName, keyContainerName) { m_cryptoKeySecurity = cryptoKeySecurity; m_keyPassword = keyPassword; } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public CspParameters (int providerType, string providerName, string keyContainerName, CryptoKeySecurity cryptoKeySecurity, IntPtr parentWindowHandle) : this (providerType, providerName, keyContainerName) { m_cryptoKeySecurity = cryptoKeySecurity; m_parentWindowHandle = parentWindowHandle; } #endif // #if FEATURE_MACL && FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS [ResourceExposure(ResourceScope.Machine)] internal CspParameters (int providerType, string providerName, string keyContainerName, CspProviderFlags flags) { ProviderType = providerType; ProviderName = providerName; KeyContainerName = keyContainerName; KeyNumber = -1; Flags = flags; } // copy constructor internal CspParameters (CspParameters parameters) { ProviderType = parameters.ProviderType; ProviderName = parameters.ProviderName; KeyContainerName = parameters.KeyContainerName; KeyNumber = parameters.KeyNumber; Flags = parameters.Flags; #if FEATURE_MACL || MONO m_cryptoKeySecurity = parameters.m_cryptoKeySecurity; #endif // FEATURE_MACL #if FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS m_keyPassword = parameters.m_keyPassword; m_parentWindowHandle = parameters.m_parentWindowHandle; #endif // FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Configuration; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; using ASC.ActiveDirectory.Base; using ASC.ActiveDirectory.Base.Data; using ASC.ActiveDirectory.Novell.Exceptions; using ASC.ActiveDirectory.Novell.Extensions; using ASC.Common.Logging; using Novell.Directory.Ldap; using Novell.Directory.Ldap.Controls; using Novell.Directory.Ldap.Utilclass; namespace ASC.ActiveDirectory.Novell { public class NovellLdapSearcher : IDisposable { private readonly ILog _log = LogManager.GetLogger("ASC"); private LdapCertificateConfirmRequest _certificateConfirmRequest; private static readonly object RootSync = new object(); private LdapConnection _ldapConnection; public string Login { get; private set; } public string Password { get; private set; } public string Server { get; private set; } public int PortNumber { get; private set; } public bool StartTls { get; private set; } public bool Ssl { get; private set; } public bool AcceptCertificate { get; private set; } public string AcceptCertificateHash { get; private set; } public string LdapUniqueIdAttribute { get; set; } private Dictionary<string, string[]> _capabilities; public bool IsConnected { get { return _ldapConnection != null && _ldapConnection.Connected; } } public NovellLdapSearcher(string login, string password, string server, int portNumber, bool startTls, bool ssl, bool acceptCertificate, string acceptCertificateHash = null) { Login = login; Password = password; Server = server; PortNumber = portNumber; StartTls = startTls; Ssl = ssl; AcceptCertificate = acceptCertificate; AcceptCertificateHash = acceptCertificateHash; LdapUniqueIdAttribute = ConfigurationManagerExtension.AppSettings["ldap.unique.id"]; } public void Connect() { if (Server.StartsWith("LDAP://")) Server = Server.Substring("LDAP://".Length); var ldapConnection = new LdapConnection(); if (StartTls || Ssl) ldapConnection.UserDefinedServerCertValidationDelegate += ServerCertValidationHandler; if (Ssl) ldapConnection.SecureSocketLayer = true; try { ldapConnection.ConnectionTimeout = 30000; // 30 seconds _log.DebugFormat("ldapConnection.Connect(Server='{0}', PortNumber='{1}');", Server, PortNumber); ldapConnection.Connect(Server, PortNumber); if (StartTls) { _log.Debug("ldapConnection.StartTls();"); ldapConnection.StartTls(); } } catch (Exception ex) { if (_certificateConfirmRequest == null) { if (ex.Message.StartsWith("Connect Error")) { throw new SocketException(); } if (ex.Message.StartsWith("Unavailable")) { throw new NotSupportedException(ex.Message); } throw; } _log.Debug("LDAP certificate confirmation requested."); ldapConnection.Disconnect(); var exception = new NovellLdapTlsCertificateRequestedException { CertificateConfirmRequest = _certificateConfirmRequest }; throw exception; } if (string.IsNullOrEmpty(Login) || string.IsNullOrEmpty(Password)) { _log.Debug("ldapConnection.Bind(Anonymous)"); ldapConnection.Bind(null, null); } else { _log.DebugFormat("ldapConnection.Bind(Login: '{0}')", Login); ldapConnection.Bind(Login, Password); } if (!ldapConnection.Bound) { throw new Exception("Bind operation wasn't completed successfully."); } _ldapConnection = ldapConnection; } private bool ServerCertValidationHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; lock (RootSync) { var certHash = certificate.GetCertHashString(); if (LdapUtils.IsCertInstalled(certificate, _log)) { AcceptCertificate = true; AcceptCertificateHash = certHash; return true; } if (AcceptCertificate) { if (AcceptCertificateHash == null || AcceptCertificateHash.Equals(certHash)) { if (LdapUtils.TryInstallCert(certificate, _log)) { AcceptCertificateHash = certHash; } return true; } AcceptCertificate = false; AcceptCertificateHash = null; } _log.WarnFormat("ServerCertValidationHandler: sslPolicyErrors = {0}", sslPolicyErrors); _certificateConfirmRequest = LdapCertificateConfirmRequest.FromCert(certificate, chain, sslPolicyErrors, false, true, _log); } return false; } public enum LdapScope { Base = LdapConnection.SCOPE_BASE, One = LdapConnection.SCOPE_ONE, Sub = LdapConnection.SCOPE_SUB } public List<LdapObject> Search(LdapScope scope, string searchFilter, string[] attributes = null, int limit = -1, LdapSearchConstraints searchConstraints = null) { return Search("", scope, searchFilter, attributes, limit, searchConstraints); } public List<LdapObject> Search(string searchBase, LdapScope scope, string searchFilter, string[] attributes = null, int limit = -1, LdapSearchConstraints searchConstraints = null) { if (!IsConnected) Connect(); if (searchBase == null) searchBase = ""; var entries = new List<LdapEntry>(); if (string.IsNullOrEmpty(searchFilter)) return new List<LdapObject>(); if (attributes == null) { if (string.IsNullOrEmpty(LdapUniqueIdAttribute)) { attributes = new[] { "*", LdapConstants.RfcLDAPAttributes.ENTRY_DN, LdapConstants.RfcLDAPAttributes.ENTRY_UUID, LdapConstants.RfcLDAPAttributes.NS_UNIQUE_ID, LdapConstants.RfcLDAPAttributes.GUID }; } else { attributes = new[] { "*", LdapUniqueIdAttribute }; } } var ldapSearchConstraints = searchConstraints ?? new LdapSearchConstraints { // Maximum number of search results to return. // The value 0 means no limit. The default is 1000. MaxResults = limit == -1 ? 0 : limit, // Returns the number of results to block on during receipt of search results. // This should be 0 if intermediate results are not needed, and 1 if results are to be processed as they come in. //BatchSize = 0, // The maximum number of referrals to follow in a sequence during automatic referral following. // The default value is 10. A value of 0 means no limit. HopLimit = 0, // Specifies whether referrals are followed automatically // Referrals of any type other than to an LDAP server (for example, a referral URL other than ldap://something) are ignored on automatic referral following. // The default is false. ReferralFollowing = true, // The number of seconds to wait for search results. // Sets the maximum number of seconds that the server is to wait when returning search results. //ServerTimeLimit = 600000, // 10 minutes // Sets the maximum number of milliseconds the client waits for any operation under these constraints to complete. // If the value is 0, there is no maximum time limit enforced by the API on waiting for the operation results. //TimeLimit = 600000 // 10 minutes }; var queue = _ldapConnection.Search(searchBase, (int)scope, searchFilter, attributes, false, ldapSearchConstraints); while (queue.hasMore()) { LdapEntry nextEntry; try { nextEntry = queue.next(); if (nextEntry == null) continue; } catch (LdapException ex) { if (!string.IsNullOrEmpty(ex.Message) && ex.Message.Contains("Sizelimit Exceeded")) { if (!string.IsNullOrEmpty(Login) && !string.IsNullOrEmpty(Password) && limit == -1) { _log.Warn("The size of the search results is limited. Start TrySearchSimple()"); List<LdapObject> simpleResults; if (TrySearchSimple(searchBase, scope, searchFilter, out simpleResults, attributes, limit, searchConstraints)) { if (entries.Count >= simpleResults.Count) break; return simpleResults; } } break; } _log.ErrorFormat("Search({0}) error: {1}", searchFilter, ex); continue; } entries.Add(nextEntry); if (string.IsNullOrEmpty(LdapUniqueIdAttribute)) { LdapUniqueIdAttribute = GetLdapUniqueId(nextEntry); } } var result = entries.ToLdapObjects(LdapUniqueIdAttribute); return result; } private bool TrySearchSimple(string searchBase, LdapScope scope, string searchFilter, out List<LdapObject> results, string[] attributes = null, int limit = -1, LdapSearchConstraints searchConstraints = null) { try { results = SearchSimple(searchBase, scope, searchFilter, attributes, limit, searchConstraints); return true; } catch (Exception ex) { _log.ErrorFormat("TrySearchSimple() failed. Error: {0}", ex); } results = null; return false; } public List<LdapObject> SearchSimple(string searchBase, LdapScope scope, string searchFilter, string[] attributes = null, int limit = -1, LdapSearchConstraints searchConstraints = null) { if (!IsConnected) Connect(); if (searchBase == null) searchBase = ""; var entries = new List<LdapEntry>(); if (string.IsNullOrEmpty(searchFilter)) return new List<LdapObject>(); if (attributes == null) { if (string.IsNullOrEmpty(LdapUniqueIdAttribute)) { attributes = new[] { "*", LdapConstants.RfcLDAPAttributes.ENTRY_DN, LdapConstants.RfcLDAPAttributes.ENTRY_UUID, LdapConstants.RfcLDAPAttributes.NS_UNIQUE_ID, LdapConstants.RfcLDAPAttributes.GUID }; } else { attributes = new[] { "*", LdapUniqueIdAttribute }; } } var ldapSearchConstraints = searchConstraints ?? new LdapSearchConstraints { // Maximum number of search results to return. // The value 0 means no limit. The default is 1000. MaxResults = limit == -1 ? 0 : limit, // Returns the number of results to block on during receipt of search results. // This should be 0 if intermediate results are not needed, and 1 if results are to be processed as they come in. //BatchSize = 0, // The maximum number of referrals to follow in a sequence during automatic referral following. // The default value is 10. A value of 0 means no limit. HopLimit = 0, // Specifies whether referrals are followed automatically // Referrals of any type other than to an LDAP server (for example, a referral URL other than ldap://something) are ignored on automatic referral following. // The default is false. ReferralFollowing = true, // The number of seconds to wait for search results. // Sets the maximum number of seconds that the server is to wait when returning search results. //ServerTimeLimit = 600000, // 10 minutes // Sets the maximum number of milliseconds the client waits for any operation under these constraints to complete. // If the value is 0, there is no maximum time limit enforced by the API on waiting for the operation results. //TimeLimit = 600000 // 10 minutes }; // initially, cookie must be set to an empty string var pageSize = 2; sbyte[] cookie = Array.ConvertAll(Encoding.ASCII.GetBytes(""), b => unchecked((sbyte)b)); var i = 0; do { var requestControls = new LdapControl[1]; requestControls[0] = new LdapPagedResultsControl(pageSize, cookie); ldapSearchConstraints.setControls(requestControls); _ldapConnection.Constraints = ldapSearchConstraints; var res = _ldapConnection.Search(searchBase, (int)scope, searchFilter, attributes, false, (LdapSearchConstraints)null); while (res.hasMore()) { LdapEntry nextEntry; try { nextEntry = res.next(); if (nextEntry == null) continue; } catch (LdapException ex) { if (ex is LdapReferralException) continue; if (!string.IsNullOrEmpty(ex.Message) && ex.Message.Contains("Sizelimit Exceeded")) break; _log.ErrorFormat("SearchSimple({0}) error: {1}", searchFilter, ex); continue; } _log.DebugFormat("{0}. DN: {1}", ++i, nextEntry.DN); entries.Add(nextEntry); if (string.IsNullOrEmpty(LdapUniqueIdAttribute)) { LdapUniqueIdAttribute = GetLdapUniqueId(nextEntry); } } // Server should send back a control irrespective of the // status of the search request var controls = res.ResponseControls; if (controls == null) { _log.Debug("No controls returned"); cookie = null; } else { // Multiple controls could have been returned foreach (LdapControl control in controls) { /* Is this the LdapPagedResultsResponse control? */ if (!(control is LdapPagedResultsResponse)) continue; var response = new LdapPagedResultsResponse(control.ID, control.Critical, control.getValue()); cookie = response.Cookie; } } // if cookie is empty, we are done. } while (cookie != null && cookie.Length > 0); var result = entries.ToLdapObjects(LdapUniqueIdAttribute); return result; } public Dictionary<string, string[]> GetCapabilities() { if (_capabilities != null) return _capabilities; _capabilities = new Dictionary<string, string[]>(); try { var ldapSearchConstraints = new LdapSearchConstraints { MaxResults = int.MaxValue, HopLimit = 0, ReferralFollowing = true }; var ldapSearchResults = _ldapConnection.Search("", LdapConnection.SCOPE_BASE, LdapConstants.OBJECT_FILTER, new[] { "*", "supportedControls", "supportedCapabilities" }, false, ldapSearchConstraints); while (ldapSearchResults.hasMore()) { LdapEntry nextEntry; try { nextEntry = ldapSearchResults.next(); if (nextEntry == null) continue; } catch (LdapException ex) { _log.ErrorFormat("GetCapabilities()->LoopResults failed. Error: {0}", ex); continue; } var attributeSet = nextEntry.getAttributeSet(); var ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { var attribute = (LdapAttribute)ienum.Current; if (attribute == null) continue; var attributeName = attribute.Name; var attributeVals = attribute.StringValueArray .ToList() .Select(s => { if (Base64.isLDIFSafe(s)) return s; var tbyte = SupportClass.ToByteArray(s); s = Base64.encode(SupportClass.ToSByteArray(tbyte)); return s; }).ToArray(); _capabilities.Add(attributeName, attributeVals); } } } catch (Exception ex) { _log.ErrorFormat("GetCapabilities() failed. Error: {0}", ex); } return _capabilities; } private string GetLdapUniqueId(LdapEntry ldapEntry) { try { var ldapUniqueIdAttribute = ConfigurationManagerExtension.AppSettings["ldap.unique.id"]; if (ldapUniqueIdAttribute != null) return ldapUniqueIdAttribute; if (!string.IsNullOrEmpty( ldapEntry.GetAttributeValue(LdapConstants.ADSchemaAttributes.OBJECT_SID) as string)) { ldapUniqueIdAttribute = LdapConstants.ADSchemaAttributes.OBJECT_SID; } else if (!string.IsNullOrEmpty( ldapEntry.GetAttributeValue(LdapConstants.RfcLDAPAttributes.ENTRY_UUID) as string)) { ldapUniqueIdAttribute = LdapConstants.RfcLDAPAttributes.ENTRY_UUID; } else if (!string.IsNullOrEmpty( ldapEntry.GetAttributeValue(LdapConstants.RfcLDAPAttributes.NS_UNIQUE_ID) as string)) { ldapUniqueIdAttribute = LdapConstants.RfcLDAPAttributes.NS_UNIQUE_ID; } else if (!string.IsNullOrEmpty( ldapEntry.GetAttributeValue(LdapConstants.RfcLDAPAttributes.GUID) as string)) { ldapUniqueIdAttribute = LdapConstants.RfcLDAPAttributes.GUID; } return ldapUniqueIdAttribute; } catch (Exception ex) { _log.Error("GetLdapUniqueId()", ex); } return null; } public void Dispose() { if (!IsConnected) return; try { _ldapConnection.Constraints.TimeLimit = 10000; _ldapConnection.SearchConstraints.ServerTimeLimit = 10000; _ldapConnection.SearchConstraints.TimeLimit = 10000; _ldapConnection.ConnectionTimeout = 10000; if (_ldapConnection.TLS) { _log.Debug("ldapConnection.StopTls();"); _ldapConnection.StopTls(); } _log.Debug("ldapConnection.Disconnect();"); _ldapConnection.Disconnect(); _log.Debug("ldapConnection.Dispose();"); _ldapConnection.Dispose(); _ldapConnection = null; } catch (Exception ex) { _log.ErrorFormat("LDAP->Dispose() failed. Error: {0}", ex); } } } }
using System; using System.Collections; using System.Reflection; using System.Reflection.Emit; namespace Python.Runtime { /// <summary> /// The DelegateManager class manages the creation of true managed /// delegate instances that dispatch calls to Python methods. /// </summary> internal class DelegateManager { private Hashtable cache; private Type basetype; private Type listtype; private Type voidtype; private Type typetype; private Type ptrtype; private CodeGenerator codeGenerator; public DelegateManager() { basetype = typeof(Dispatcher); listtype = typeof(ArrayList); voidtype = typeof(void); typetype = typeof(Type); ptrtype = typeof(IntPtr); cache = new Hashtable(); codeGenerator = new CodeGenerator(); } /// <summary> /// Given a true delegate instance, return the PyObject handle of the /// Python object implementing the delegate (or IntPtr.Zero if the /// delegate is not implemented in Python code. /// </summary> public IntPtr GetPythonHandle(Delegate d) { if (d?.Target is Dispatcher) { var disp = (Dispatcher)d.Target; return disp.target; } return IntPtr.Zero; } /// <summary> /// GetDispatcher is responsible for creating a class that provides /// an appropriate managed callback method for a given delegate type. /// </summary> private Type GetDispatcher(Type dtype) { // If a dispatcher type for the given delegate type has already // been generated, get it from the cache. The cache maps delegate // types to generated dispatcher types. A possible optimization // for the future would be to generate dispatcher types based on // unique signatures rather than delegate types, since multiple // delegate types with the same sig could use the same dispatcher. object item = cache[dtype]; if (item != null) { return (Type)item; } string name = $"__{dtype.FullName}Dispatcher"; name = name.Replace('.', '_'); name = name.Replace('+', '_'); TypeBuilder tb = codeGenerator.DefineType(name, basetype); // Generate a constructor for the generated type that calls the // appropriate constructor of the Dispatcher base type. MethodAttributes ma = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; var cc = CallingConventions.Standard; Type[] args = { ptrtype, typetype }; ConstructorBuilder cb = tb.DefineConstructor(ma, cc, args); ConstructorInfo ci = basetype.GetConstructor(args); ILGenerator il = cb.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Call, ci); il.Emit(OpCodes.Ret); // Method generation: we generate a method named "Invoke" on the // dispatcher type, whose signature matches the delegate type for // which it is generated. The method body simply packages the // arguments and hands them to the Dispatch() method, which deals // with converting the arguments, calling the Python method and // converting the result of the call. MethodInfo method = dtype.GetMethod("Invoke"); ParameterInfo[] pi = method.GetParameters(); var signature = new Type[pi.Length]; for (var i = 0; i < pi.Length; i++) { signature[i] = pi[i].ParameterType; } MethodBuilder mb = tb.DefineMethod("Invoke", MethodAttributes.Public, method.ReturnType, signature); ConstructorInfo ctor = listtype.GetConstructor(Type.EmptyTypes); MethodInfo dispatch = basetype.GetMethod("Dispatch"); MethodInfo add = listtype.GetMethod("Add"); il = mb.GetILGenerator(); il.DeclareLocal(listtype); il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Stloc_0); for (var c = 0; c < signature.Length; c++) { Type t = signature[c]; il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldarg_S, (byte)(c + 1)); if (t.IsValueType) { il.Emit(OpCodes.Box, t); } il.Emit(OpCodes.Callvirt, add); il.Emit(OpCodes.Pop); } il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Call, dispatch); if (method.ReturnType == voidtype) { il.Emit(OpCodes.Pop); } else if (method.ReturnType.IsValueType) { il.Emit(OpCodes.Unbox_Any, method.ReturnType); } il.Emit(OpCodes.Ret); Type disp = tb.CreateType(); cache[dtype] = disp; return disp; } /// <summary> /// Given a delegate type and a callable Python object, GetDelegate /// returns an instance of the delegate type. The delegate instance /// returned will dispatch calls to the given Python object. /// </summary> internal Delegate GetDelegate(Type dtype, IntPtr callable) { Type dispatcher = GetDispatcher(dtype); object[] args = { callable, dtype }; object o = Activator.CreateInstance(dispatcher, args); return Delegate.CreateDelegate(dtype, o, "Invoke"); } } /* When a delegate instance is created that has a Python implementation, the delegate manager generates a custom subclass of Dispatcher and instantiates it, passing the IntPtr of the Python callable. The "real" delegate is created using CreateDelegate, passing the instance of the generated type and the name of the (generated) implementing method (Invoke). The true delegate instance holds the only reference to the dispatcher instance, which ensures that when the delegate dies, the finalizer of the referenced instance will be able to decref the Python callable. A possible alternate strategy would be to create custom subclasses of the required delegate type, storing the IntPtr in it directly. This would be slightly cleaner, but I'm not sure if delegates are too "special" for this to work. It would be more work, so for now the 80/20 rule applies :) */ public class Dispatcher { public IntPtr target; public Type dtype; public Dispatcher(IntPtr target, Type dtype) { Runtime.XIncref(target); this.target = target; this.dtype = dtype; } ~Dispatcher() { // Note: the managed GC thread can run and try to free one of // these *after* the Python runtime has been finalized! if (Runtime.Py_IsInitialized() > 0) { IntPtr gs = PythonEngine.AcquireLock(); Runtime.XDecref(target); PythonEngine.ReleaseLock(gs); } } public object Dispatch(ArrayList args) { IntPtr gs = PythonEngine.AcquireLock(); object ob = null; try { ob = TrueDispatch(args); } catch (Exception e) { PythonEngine.ReleaseLock(gs); throw e; } PythonEngine.ReleaseLock(gs); return ob; } public object TrueDispatch(ArrayList args) { MethodInfo method = dtype.GetMethod("Invoke"); ParameterInfo[] pi = method.GetParameters(); IntPtr pyargs = Runtime.PyTuple_New(pi.Length); Type rtype = method.ReturnType; for (var i = 0; i < pi.Length; i++) { // Here we own the reference to the Python value, and we // give the ownership to the arg tuple. IntPtr arg = Converter.ToPython(args[i], pi[i].ParameterType); Runtime.PyTuple_SetItem(pyargs, i, arg); } IntPtr op = Runtime.PyObject_Call(target, pyargs, IntPtr.Zero); Runtime.XDecref(pyargs); if (op == IntPtr.Zero) { var e = new PythonException(); throw e; } if (rtype == typeof(void)) { return null; } object result = null; if (!Converter.ToManaged(op, rtype, out result, false)) { Runtime.XDecref(op); throw new ConversionException($"could not convert Python result to {rtype}"); } Runtime.XDecref(op); return result; } } public class ConversionException : Exception { public ConversionException() { } public ConversionException(string msg) : base(msg) { } } }
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt // http://dead-code.org/redir.php?target=wme using System; using System.Collections.Generic; using System.Text; using DeadCode.WME.Core; using DeadCode.WME.Global; using System.Drawing; using System.ComponentModel; using Design; using System.Drawing.Design; using DeadCode.WME.Global.UITypeEditors; namespace DeadCode.WME.WindowEdit { ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// public class UiButtonProxy : UiControlProxy { ////////////////////////////////////////////////////////////////////////// public UiButtonProxy(WUIButton NativeObject) : base(NativeObject) { } ////////////////////////////////////////////////////////////////////////// [Browsable(false)] public new WUIButton NativeObject { get { return (WUIButton)_NativeObject; } } [Category(CategoryName.Appearance), PropertyOrder(150)] [Description("Specifies a caption of the button. It's not directly visible and is typically used by scripts to display a floating 'tooltip'.")] ////////////////////////////////////////////////////////////////////////// public string Caption { get { return NativeObject.Caption; } set { OnPropertyChanging("Caption"); NativeObject.Caption = value; } } [Category(CategoryName.Appearance), PropertyOrder(300)] [Description("Specifies the horizontal alignment of text")] ////////////////////////////////////////////////////////////////////////// public WETextAlign TextAlign { get { return NativeObject.TextAlignment; } set { OnPropertyChanging("TextAlign"); NativeObject.TextAlignment = value; } } [Category(CategoryName.Appearance), PropertyOrder(1120)] [Description("Specifies whether the button appears to be pressed down")] ////////////////////////////////////////////////////////////////////////// public bool Pressed { get { return NativeObject.StayPressed; } set { OnPropertyChanging("Pressed"); NativeObject.StayPressed = value; } } [Category(CategoryName.Appearance), PropertyOrder(1130)] [Description("Specifies whether the image should be centered within the button rectangle")] ////////////////////////////////////////////////////////////////////////// public bool CenterImage { get { return NativeObject.CenterImage; } set { OnPropertyChanging("CenterImage"); NativeObject.CenterImage = value; } } [Category(CategoryName.Appearance), PropertyOrder(1140)] [Description("Specifies whether the button detects mouse-over with pixel precision")] ////////////////////////////////////////////////////////////////////////// public bool PixelPerfect { get { return NativeObject.PixelPerfect; } set { OnPropertyChanging("PixelPerfect"); NativeObject.PixelPerfect = value; } } [Category(CategoryName.Appearance), PropertyOrder(1150)] [Description("Specifies whether the button can be focused")] ////////////////////////////////////////////////////////////////////////// public bool Focusable { get { return NativeObject.CanFocus; } set { OnPropertyChanging("Focusable"); NativeObject.CanFocus = value; } } ////////////////////////////////////////////////////////////////////////// // pressed ////////////////////////////////////////////////////////////////////////// [Category(CategoryName.AppearancePressed), PropertyOrder(10)] [Description("The font used for pressed button")] [EditorAttribute(typeof(FontTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WFont FontPressed { get { return NativeObject.FontPressed; } set { OnPropertyChanging("FontPressed"); NativeObject.FontPressed = value; } } [Category(CategoryName.AppearancePressed), PropertyOrder(20)] [Description("The background image used for pressed button")] [EditorAttribute(typeof(SpriteTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WSprite ImagePressed { get { return NativeObject.ImagePressed; } set { OnPropertyChanging("ImagePressed"); NativeObject.ImagePressed = value; } } [Category(CategoryName.AppearancePressed), PropertyOrder(30)] [Description("The background tiled image used for pressed button")] [EditorAttribute(typeof(TiledImgTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WUITiledImage TiledImagePressed { get { return NativeObject.BackPressed; } set { OnPropertyChanging("TiledImagePressed"); NativeObject.BackPressed = value; } } ////////////////////////////////////////////////////////////////////////// // hover ////////////////////////////////////////////////////////////////////////// [Category(CategoryName.AppearanceHover), PropertyOrder(10)] [Description("The font used for hovered button")] [EditorAttribute(typeof(FontTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WFont FontHover { get { return NativeObject.FontHover; } set { OnPropertyChanging("FontHover"); NativeObject.FontHover = value; } } [Category(CategoryName.AppearanceHover), PropertyOrder(20)] [Description("The background image used for hovered button")] [EditorAttribute(typeof(SpriteTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WSprite ImageHover { get { return NativeObject.ImageHover; } set { OnPropertyChanging("ImageHover"); NativeObject.ImageHover = value; } } [Category(CategoryName.AppearanceHover), PropertyOrder(30)] [Description("The background tiled image used for hovered button")] [EditorAttribute(typeof(TiledImgTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WUITiledImage TiledImageHover { get { return NativeObject.BackHover; } set { OnPropertyChanging("TiledImageHover"); NativeObject.BackHover = value; } } ////////////////////////////////////////////////////////////////////////// // disabled ////////////////////////////////////////////////////////////////////////// [Category(CategoryName.AppearanceDisabled), PropertyOrder(10)] [Description("The font used for disabled button")] [EditorAttribute(typeof(FontTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WFont FontDisabled { get { return NativeObject.FontDisabled; } set { OnPropertyChanging("FontDisabled"); NativeObject.FontDisabled = value; } } [Category(CategoryName.AppearanceDisabled), PropertyOrder(20)] [Description("The background image used for disabled button")] [EditorAttribute(typeof(SpriteTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WSprite ImageDisabled { get { return NativeObject.ImageDisabled; } set { OnPropertyChanging("ImageDisabled"); NativeObject.ImageDisabled = value; } } [Category(CategoryName.AppearanceDisabled), PropertyOrder(30)] [Description("The background tiled image used for disabled button")] [EditorAttribute(typeof(TiledImgTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WUITiledImage TiledImageDisabled { get { return NativeObject.BackDisabled; } set { OnPropertyChanging("TiledImageDisabled"); NativeObject.BackDisabled = value; } } ////////////////////////////////////////////////////////////////////////// // focused ////////////////////////////////////////////////////////////////////////// [Category(CategoryName.AppearanceFocused), PropertyOrder(10)] [Description("The font used for focused button")] [EditorAttribute(typeof(FontTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WFont FontFocused { get { return NativeObject.FontFocused; } set { OnPropertyChanging("FontFocused"); NativeObject.FontFocused = value; } } [Category(CategoryName.AppearanceFocused), PropertyOrder(20)] [Description("The background image used for focused button")] [EditorAttribute(typeof(SpriteTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WSprite ImageFocused { get { return NativeObject.ImageFocused; } set { OnPropertyChanging("ImageFocused"); NativeObject.ImageFocused = value; } } [Category(CategoryName.AppearanceFocused), PropertyOrder(30)] [Description("The background tiled image used for focused button")] [EditorAttribute(typeof(TiledImgTypeEditor), typeof(UITypeEditor))] ////////////////////////////////////////////////////////////////////////// public WUITiledImage TiledImageFocused { get { return NativeObject.BackFocused; } set { OnPropertyChanging("TiledImageFocused"); NativeObject.BackFocused = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using EventMetadata = System.Diagnostics.Tracing.EventSource.EventMetadata; namespace System.Diagnostics.Tracing { #if FEATURE_PERFTRACING internal sealed class EventPipeMetadataGenerator { public static EventPipeMetadataGenerator Instance = new EventPipeMetadataGenerator(); private EventPipeMetadataGenerator() { } public byte[]? GenerateEventMetadata(EventMetadata eventMetadata) { ParameterInfo[] parameters = eventMetadata.Parameters; EventParameterInfo[] eventParams = new EventParameterInfo[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { eventParams[i].SetInfo(parameters[i].Name!, parameters[i].ParameterType); } return GenerateMetadata( eventMetadata.Descriptor.EventId, eventMetadata.Name, eventMetadata.Descriptor.Keywords, eventMetadata.Descriptor.Level, eventMetadata.Descriptor.Version, eventParams); } public byte[]? GenerateEventMetadata( int eventId, string eventName, EventKeywords keywords, EventLevel level, uint version, TraceLoggingEventTypes eventTypes) { TraceLoggingTypeInfo[] typeInfos = eventTypes.typeInfos; string[]? paramNames = eventTypes.paramNames; EventParameterInfo[] eventParams = new EventParameterInfo[typeInfos.Length]; for (int i = 0; i < typeInfos.Length; i++) { string paramName = string.Empty; if (paramNames != null) { paramName = paramNames[i]; } eventParams[i].SetInfo(paramName, typeInfos[i].DataType, typeInfos[i]); } return GenerateMetadata(eventId, eventName, (long)keywords, (uint)level, version, eventParams); } private unsafe byte[]? GenerateMetadata( int eventId, string eventName, long keywords, uint level, uint version, EventParameterInfo[] parameters) { byte[]? metadata = null; try { // eventID : 4 bytes // eventName : (eventName.Length + 1) * 2 bytes // keywords : 8 bytes // eventVersion : 4 bytes // level : 4 bytes // parameterCount : 4 bytes uint metadataLength = 24 + ((uint)eventName.Length + 1) * 2; uint defaultMetadataLength = metadataLength; // Check for an empty payload. // Write<T> calls with no arguments by convention have a parameter of // type NullTypeInfo which is serialized as nothing. if ((parameters.Length == 1) && (parameters[0].ParameterType == typeof(EmptyStruct))) { parameters = Array.Empty<EventParameterInfo>(); } // Increase the metadataLength for parameters. foreach (EventParameterInfo parameter in parameters) { int pMetadataLength = parameter.GetMetadataLength(); // The call above may return -1 which means we failed to get the metadata length. // We then return a default metadata blob (with parameterCount of 0) to prevent it from generating malformed metadata. if (pMetadataLength < 0) { parameters = Array.Empty<EventParameterInfo>(); metadataLength = defaultMetadataLength; break; } metadataLength += (uint)pMetadataLength; } metadata = new byte[metadataLength]; // Write metadata: eventID, eventName, keywords, eventVersion, level, parameterCount, param1 type, param1 name... fixed (byte* pMetadata = metadata) { uint offset = 0; WriteToBuffer(pMetadata, metadataLength, ref offset, (uint)eventId); fixed (char* pEventName = eventName) { WriteToBuffer(pMetadata, metadataLength, ref offset, (byte*)pEventName, ((uint)eventName.Length + 1) * 2); } WriteToBuffer(pMetadata, metadataLength, ref offset, keywords); WriteToBuffer(pMetadata, metadataLength, ref offset, version); WriteToBuffer(pMetadata, metadataLength, ref offset, level); WriteToBuffer(pMetadata, metadataLength, ref offset, (uint)parameters.Length); foreach (EventParameterInfo parameter in parameters) { if (!parameter.GenerateMetadata(pMetadata, ref offset, metadataLength)) { // If we fail to generate metadata for any parameter, we should return the "default" metadata without any parameters return GenerateMetadata(eventId, eventName, keywords, level, version, Array.Empty<EventParameterInfo>()); } } Debug.Assert(metadataLength == offset); } } catch { // If a failure occurs during metadata generation, make sure that we don't return // malformed metadata. Instead, return a null metadata blob. // Consumers can either build in knowledge of the event or skip it entirely. metadata = null; } return metadata; } // Copy src to buffer and modify the offset. // Note: We know the buffer size ahead of time to make sure no buffer overflow. internal static unsafe void WriteToBuffer(byte* buffer, uint bufferLength, ref uint offset, byte* src, uint srcLength) { Debug.Assert(bufferLength >= (offset + srcLength)); for (int i = 0; i < srcLength; i++) { *(byte*)(buffer + offset + i) = *(byte*)(src + i); } offset += srcLength; } // Copy uint value to buffer. internal static unsafe void WriteToBuffer(byte* buffer, uint bufferLength, ref uint offset, uint value) { Debug.Assert(bufferLength >= (offset + 4)); *(uint*)(buffer + offset) = value; offset += 4; } // Copy long value to buffer. internal static unsafe void WriteToBuffer(byte* buffer, uint bufferLength, ref uint offset, long value) { Debug.Assert(bufferLength >= (offset + 8)); *(long*)(buffer + offset) = value; offset += 8; } // Copy char value to buffer. internal static unsafe void WriteToBuffer(byte* buffer, uint bufferLength, ref uint offset, char value) { Debug.Assert(bufferLength >= (offset + 2)); *(char*)(buffer + offset) = value; offset += 2; } } internal struct EventParameterInfo { internal string ParameterName; internal Type ParameterType; internal TraceLoggingTypeInfo? TypeInfo; internal void SetInfo(string name, Type type, TraceLoggingTypeInfo? typeInfo = null) { ParameterName = name; ParameterType = type; TypeInfo = typeInfo; } internal unsafe bool GenerateMetadata(byte* pMetadataBlob, ref uint offset, uint blobSize) { TypeCode typeCode = GetTypeCodeExtended(ParameterType); if (typeCode == TypeCode.Object) { // Each nested struct is serialized as: // TypeCode.Object : 4 bytes // Number of properties : 4 bytes // Property description 0...N // Nested struct property name : NULL-terminated string. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)TypeCode.Object); if (!(TypeInfo is InvokeTypeInfo invokeTypeInfo)) { return false; } // Get the set of properties to be serialized. PropertyAnalysis[]? properties = invokeTypeInfo.properties; if (properties != null) { // Write the count of serializable properties. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)properties.Length); foreach (PropertyAnalysis prop in properties) { if (!GenerateMetadataForProperty(prop, pMetadataBlob, ref offset, blobSize)) { return false; } } } else { // This struct has zero serializable properties so we just write the property count. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)0); } // Top-level structs don't have a property name, but for simplicity we write a NULL-char to represent the name. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, '\0'); } else { // Write parameter type. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)typeCode); // Write parameter name. fixed (char* pParameterName = ParameterName) { EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (byte*)pParameterName, ((uint)ParameterName.Length + 1) * 2); } } return true; } private static unsafe bool GenerateMetadataForProperty(PropertyAnalysis property, byte* pMetadataBlob, ref uint offset, uint blobSize) { Debug.Assert(property != null); Debug.Assert(pMetadataBlob != null); // Check if this property is a nested struct. if (property.typeInfo is InvokeTypeInfo invokeTypeInfo) { // Each nested struct is serialized as: // TypeCode.Object : 4 bytes // Number of properties : 4 bytes // Property description 0...N // Nested struct property name : NULL-terminated string. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)TypeCode.Object); // Get the set of properties to be serialized. PropertyAnalysis[]? properties = invokeTypeInfo.properties; if (properties != null) { // Write the count of serializable properties. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)properties.Length); foreach (PropertyAnalysis prop in properties) { if (!GenerateMetadataForProperty(prop, pMetadataBlob, ref offset, blobSize)) { return false; } } } else { // This struct has zero serializable properties so we just write the property count. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)0); } // Write the property name. fixed (char* pPropertyName = property.name) { EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (byte*)pPropertyName, ((uint)property.name.Length + 1) * 2); } } else { // Each primitive type is serialized as: // TypeCode : 4 bytes // PropertyName : NULL-terminated string TypeCode typeCode = GetTypeCodeExtended(property.typeInfo.DataType); // EventPipe does not support this type. Throw, which will cause no metadata to be registered for this event. if (typeCode == TypeCode.Object) { return false; } // Write the type code. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)typeCode); // Write the property name. fixed (char* pPropertyName = property.name) { EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (byte*)pPropertyName, ((uint)property.name.Length + 1) * 2); } } return true; } internal int GetMetadataLength() { int ret = 0; TypeCode typeCode = GetTypeCodeExtended(ParameterType); if (typeCode == TypeCode.Object) { if (!(TypeInfo is InvokeTypeInfo typeInfo)) { return -1; } // Each nested struct is serialized as: // TypeCode.Object : 4 bytes // Number of properties : 4 bytes // Property description 0...N // Nested struct property name : NULL-terminated string. ret += sizeof(uint) // TypeCode + sizeof(uint); // Property count // Get the set of properties to be serialized. PropertyAnalysis[]? properties = typeInfo.properties; if (properties != null) { foreach (PropertyAnalysis prop in properties) { ret += (int)GetMetadataLengthForProperty(prop); } } // For simplicity when writing a reader, we write a NULL char // after the metadata for a top-level struct (for its name) so that // readers don't have do special case the outer-most struct. ret += sizeof(char); } else { ret += (int)(sizeof(uint) + ((ParameterName.Length + 1) * 2)); } return ret; } private static uint GetMetadataLengthForProperty(PropertyAnalysis property) { Debug.Assert(property != null); uint ret = 0; // Check if this property is a nested struct. if (property.typeInfo is InvokeTypeInfo invokeTypeInfo) { // Each nested struct is serialized as: // TypeCode.Object : 4 bytes // Number of properties : 4 bytes // Property description 0...N // Nested struct property name : NULL-terminated string. ret += sizeof(uint) // TypeCode + sizeof(uint); // Property count // Get the set of properties to be serialized. PropertyAnalysis[]? properties = invokeTypeInfo.properties; if (properties != null) { foreach (PropertyAnalysis prop in properties) { ret += GetMetadataLengthForProperty(prop); } } // Add the size of the property name. ret += (uint)((property.name.Length + 1) * 2); } else { ret += (uint)(sizeof(uint) + ((property.name.Length + 1) * 2)); } return ret; } private static TypeCode GetTypeCodeExtended(Type parameterType) { // Guid is not part of TypeCode, we decided to use 17 to represent it, as it's the "free slot" // see https://github.com/dotnet/coreclr/issues/16105#issuecomment-361749750 for more const TypeCode GuidTypeCode = (TypeCode)17; if (parameterType == typeof(Guid)) // Guid is not a part of TypeCode enum return GuidTypeCode; // IntPtr and UIntPtr are converted to their non-pointer types. if (parameterType == typeof(IntPtr)) return IntPtr.Size == 4 ? TypeCode.Int32 : TypeCode.Int64; if (parameterType == typeof(UIntPtr)) return UIntPtr.Size == 4 ? TypeCode.UInt32 : TypeCode.UInt64; return Type.GetTypeCode(parameterType); } } #endif // FEATURE_PERFTRACING }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Net.Http.Headers { public static class __CacheControlHeaderValue { public static IObservable<System.String> ToString(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.ToString()); } public static IObservable<System.Boolean> Equals(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Object> obj) { return Observable.Zip(CacheControlHeaderValueValue, obj, (CacheControlHeaderValueValueLambda, objLambda) => CacheControlHeaderValueValueLambda.Equals(objLambda)); } public static IObservable<System.Int32> GetHashCode(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.GetHashCode()); } public static IObservable<System.Net.Http.Headers.CacheControlHeaderValue> Parse(IObservable<System.String> input) { return Observable.Select(input, (inputLambda) => System.Net.Http.Headers.CacheControlHeaderValue.Parse(inputLambda)); } public static IObservable<Tuple<System.Boolean, System.Net.Http.Headers.CacheControlHeaderValue>> TryParse(IObservable<System.String> input) { return Observable.Select(input, (inputLambda) => { System.Net.Http.Headers.CacheControlHeaderValue parsedValueOutput = default(System.Net.Http.Headers.CacheControlHeaderValue); var result = System.Net.Http.Headers.CacheControlHeaderValue.TryParse(inputLambda, out parsedValueOutput); return Tuple.Create(result, parsedValueOutput); }); } public static IObservable<System.Boolean> get_NoCache(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.NoCache); } public static IObservable<System.Collections.Generic.ICollection<System.String>> get_NoCacheHeaders(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.NoCacheHeaders); } public static IObservable<System.Boolean> get_NoStore(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.NoStore); } public static IObservable<System.Nullable<System.TimeSpan>> get_MaxAge(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.MaxAge); } public static IObservable<System.Nullable<System.TimeSpan>> get_SharedMaxAge(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.SharedMaxAge); } public static IObservable<System.Boolean> get_MaxStale(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.MaxStale); } public static IObservable<System.Nullable<System.TimeSpan>> get_MaxStaleLimit(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.MaxStaleLimit); } public static IObservable<System.Nullable<System.TimeSpan>> get_MinFresh(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.MinFresh); } public static IObservable<System.Boolean> get_NoTransform(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.NoTransform); } public static IObservable<System.Boolean> get_OnlyIfCached(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.OnlyIfCached); } public static IObservable<System.Boolean> get_Public(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.Public); } public static IObservable<System.Boolean> get_Private(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.Private); } public static IObservable<System.Collections.Generic.ICollection<System.String>> get_PrivateHeaders(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.PrivateHeaders); } public static IObservable<System.Boolean> get_MustRevalidate(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.MustRevalidate); } public static IObservable<System.Boolean> get_ProxyRevalidate(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.ProxyRevalidate); } public static IObservable<System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>> get_Extensions(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue) { return Observable.Select(CacheControlHeaderValueValue, (CacheControlHeaderValueValueLambda) => CacheControlHeaderValueValueLambda.Extensions); } public static IObservable<System.Reactive.Unit> set_NoCache(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.NoCache = valueLambda); } public static IObservable<System.Reactive.Unit> set_NoStore(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.NoStore = valueLambda); } public static IObservable<System.Reactive.Unit> set_MaxAge(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Nullable<System.TimeSpan>> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.MaxAge = valueLambda); } public static IObservable<System.Reactive.Unit> set_SharedMaxAge(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Nullable<System.TimeSpan>> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.SharedMaxAge = valueLambda); } public static IObservable<System.Reactive.Unit> set_MaxStale(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.MaxStale = valueLambda); } public static IObservable<System.Reactive.Unit> set_MaxStaleLimit(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Nullable<System.TimeSpan>> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.MaxStaleLimit = valueLambda); } public static IObservable<System.Reactive.Unit> set_MinFresh(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Nullable<System.TimeSpan>> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.MinFresh = valueLambda); } public static IObservable<System.Reactive.Unit> set_NoTransform(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.NoTransform = valueLambda); } public static IObservable<System.Reactive.Unit> set_OnlyIfCached(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.OnlyIfCached = valueLambda); } public static IObservable<System.Reactive.Unit> set_Public(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.Public = valueLambda); } public static IObservable<System.Reactive.Unit> set_Private(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.Private = valueLambda); } public static IObservable<System.Reactive.Unit> set_MustRevalidate(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.MustRevalidate = valueLambda); } public static IObservable<System.Reactive.Unit> set_ProxyRevalidate(this IObservable<System.Net.Http.Headers.CacheControlHeaderValue> CacheControlHeaderValueValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(CacheControlHeaderValueValue, value, (CacheControlHeaderValueValueLambda, valueLambda) => CacheControlHeaderValueValueLambda.ProxyRevalidate = valueLambda); } } }
#region File Description //----------------------------------------------------------------------------- // ParticleSystem.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics.PackedVector; #endregion namespace Particle3DSample { /// <summary> /// The main component in charge of displaying particles. /// </summary> public abstract class ParticleSystem : DrawableGameComponent { #region Fields // Settings class controls the appearance and animation of this particle system. ParticleSettings settings = new ParticleSettings(); // For loading the effect and particle texture. ContentManager content; // Custom effect for drawing particles. This computes the particle // animation entirely in the vertex shader: no per-particle CPU work required! Effect particleEffect; // Shortcuts for accessing frequently changed effect parameters. EffectParameter effectViewParameter; EffectParameter effectProjectionParameter; EffectParameter effectViewportScaleParameter; EffectParameter effectTimeParameter; // An array of particles, treated as a circular queue. ParticleVertex[] particles; // A vertex buffer holding our particles. This contains the same data as // the particles array, but copied across to where the GPU can access it. DynamicVertexBuffer vertexBuffer; // Index buffer turns sets of four vertices into particle quads (pairs of triangles). IndexBuffer indexBuffer; // The particles array and vertex buffer are treated as a circular queue. // Initially, the entire contents of the array are free, because no particles // are in use. When a new particle is created, this is allocated from the // beginning of the array. If more than one particle is created, these will // always be stored in a consecutive block of array elements. Because all // particles last for the same amount of time, old particles will always be // removed in order from the start of this active particle region, so the // active and free regions will never be intermingled. Because the queue is // circular, there can be times when the active particle region wraps from the // end of the array back to the start. The queue uses modulo arithmetic to // handle these cases. For instance with a four entry queue we could have: // // 0 // 1 - first active particle // 2 // 3 - first free particle // // In this case, particles 1 and 2 are active, while 3 and 4 are free. // Using modulo arithmetic we could also have: // // 0 // 1 - first free particle // 2 // 3 - first active particle // // Here, 3 and 0 are active, while 1 and 2 are free. // // But wait! The full story is even more complex. // // When we create a new particle, we add them to our managed particles array. // We also need to copy this new data into the GPU vertex buffer, but we don't // want to do that straight away, because setting new data into a vertex buffer // can be an expensive operation. If we are going to be adding several particles // in a single frame, it is faster to initially just store them in our managed // array, and then later upload them all to the GPU in one single call. So our // queue also needs a region for storing new particles that have been added to // the managed array but not yet uploaded to the vertex buffer. // // Another issue occurs when old particles are retired. The CPU and GPU run // asynchronously, so the GPU will often still be busy drawing the previous // frame while the CPU is working on the next frame. This can cause a // synchronization problem if an old particle is retired, and then immediately // overwritten by a new one, because the CPU might try to change the contents // of the vertex buffer while the GPU is still busy drawing the old data from // it. Normally the graphics driver will take care of this by waiting until // the GPU has finished drawing inside the VertexBuffer.SetData call, but we // don't want to waste time waiting around every time we try to add a new // particle! To avoid this delay, we can specify the SetDataOptions.NoOverwrite // flag when we write to the vertex buffer. This basically means "I promise I // will never try to overwrite any data that the GPU might still be using, so // you can just go ahead and update the buffer straight away". To keep this // promise, we must avoid reusing vertices immediately after they are drawn. // // So in total, our queue contains four different regions: // // Vertices between firstActiveParticle and firstNewParticle are actively // being drawn, and exist in both the managed particles array and the GPU // vertex buffer. // // Vertices between firstNewParticle and firstFreeParticle are newly created, // and exist only in the managed particles array. These need to be uploaded // to the GPU at the start of the next draw call. // // Vertices between firstFreeParticle and firstRetiredParticle are free and // waiting to be allocated. // // Vertices between firstRetiredParticle and firstActiveParticle are no longer // being drawn, but were drawn recently enough that the GPU could still be // using them. These need to be kept around for a few more frames before they // can be reallocated. int firstActiveParticle; int firstNewParticle; int firstFreeParticle; int firstRetiredParticle; // Store the current time, in seconds. float currentTime; // Count how many times Draw has been called. This is used to know // when it is safe to retire old particles back into the free list. int drawCounter; // Shared random number generator. static Random random = new Random(); #endregion #region Initialization /// <summary> /// Constructor. /// </summary> protected ParticleSystem(Game game, ContentManager content) : base(game) { this.content = content; } /// <summary> /// Initializes the component. /// </summary> public override void Initialize() { InitializeSettings(settings); // Allocate the particle array, and fill in the corner fields (which never change). particles = new ParticleVertex[settings.MaxParticles * 4]; for (int i = 0; i < settings.MaxParticles; i++) { particles[i * 4 + 0].Corner = new Short2(-1, -1); particles[i * 4 + 1].Corner = new Short2(1, -1); particles[i * 4 + 2].Corner = new Short2(1, 1); particles[i * 4 + 3].Corner = new Short2(-1, 1); } base.Initialize(); } /// <summary> /// Derived particle system classes should override this method /// and use it to initalize their tweakable settings. /// </summary> protected abstract void InitializeSettings(ParticleSettings settings); /// <summary> /// Loads graphics for the particle system. /// </summary> protected override void LoadContent() { LoadParticleEffect(); // Create a dynamic vertex buffer. vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, ParticleVertex.VertexDeclaration, settings.MaxParticles * 4, BufferUsage.WriteOnly); // Create and populate the index buffer. ushort[] indices = new ushort[settings.MaxParticles * 6]; for (int i = 0; i < settings.MaxParticles; i++) { indices[i * 6 + 0] = (ushort)(i * 4 + 0); indices[i * 6 + 1] = (ushort)(i * 4 + 1); indices[i * 6 + 2] = (ushort)(i * 4 + 2); indices[i * 6 + 3] = (ushort)(i * 4 + 0); indices[i * 6 + 4] = (ushort)(i * 4 + 2); indices[i * 6 + 5] = (ushort)(i * 4 + 3); } indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly); indexBuffer.SetData(indices); } /// <summary> /// Helper for loading and initializing the particle effect. /// </summary> void LoadParticleEffect() { Effect effect = content.Load<Effect>("ParticleEffect"); // If we have several particle systems, the content manager will return // a single shared effect instance to them all. But we want to preconfigure // the effect with parameters that are specific to this particular // particle system. By cloning the effect, we prevent one particle system // from stomping over the parameter settings of another. particleEffect = effect.Clone(); EffectParameterCollection parameters = particleEffect.Parameters; // Look up shortcuts for parameters that change every frame. effectViewParameter = parameters["View"]; effectProjectionParameter = parameters["Projection"]; effectViewportScaleParameter = parameters["ViewportScale"]; effectTimeParameter = parameters["CurrentTime"]; // Set the values of parameters that do not change. parameters["Duration"].SetValue((float)settings.Duration.TotalSeconds); parameters["DurationRandomness"].SetValue(settings.DurationRandomness); parameters["Gravity"].SetValue(settings.Gravity); parameters["EndVelocity"].SetValue(settings.EndVelocity); parameters["MinColor"].SetValue(settings.MinColor.ToVector4()); parameters["MaxColor"].SetValue(settings.MaxColor.ToVector4()); parameters["RotateSpeed"].SetValue( new Vector2(settings.MinRotateSpeed, settings.MaxRotateSpeed)); parameters["StartSize"].SetValue( new Vector2(settings.MinStartSize, settings.MaxStartSize)); parameters["EndSize"].SetValue( new Vector2(settings.MinEndSize, settings.MaxEndSize)); // Load the particle texture, and set it onto the effect. Texture2D texture = content.Load<Texture2D>(settings.TextureName); parameters["Texture"].SetValue(texture); } #endregion #region Update and Draw /// <summary> /// Updates the particle system. /// </summary> public override void Update(GameTime gameTime) { if (gameTime == null) throw new ArgumentNullException("gameTime"); currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; RetireActiveParticles(); FreeRetiredParticles(); // If we let our timer go on increasing for ever, it would eventually // run out of floating point precision, at which point the particles // would render incorrectly. An easy way to prevent this is to notice // that the time value doesn't matter when no particles are being drawn, // so we can reset it back to zero any time the active queue is empty. if (firstActiveParticle == firstFreeParticle) currentTime = 0; if (firstRetiredParticle == firstActiveParticle) drawCounter = 0; } /// <summary> /// Helper for checking when active particles have reached the end of /// their life. It moves old particles from the active area of the queue /// to the retired section. /// </summary> void RetireActiveParticles() { float particleDuration = (float)settings.Duration.TotalSeconds; while (firstActiveParticle != firstNewParticle) { // Is this particle old enough to retire? // We multiply the active particle index by four, because each // particle consists of a quad that is made up of four vertices. float particleAge = currentTime - particles[firstActiveParticle * 4].Time; if (particleAge < particleDuration) break; // Remember the time at which we retired this particle. particles[firstActiveParticle * 4].Time = drawCounter; // Move the particle from the active to the retired queue. firstActiveParticle++; if (firstActiveParticle >= settings.MaxParticles) firstActiveParticle = 0; } } /// <summary> /// Helper for checking when retired particles have been kept around long /// enough that we can be sure the GPU is no longer using them. It moves /// old particles from the retired area of the queue to the free section. /// </summary> void FreeRetiredParticles() { while (firstRetiredParticle != firstActiveParticle) { // Has this particle been unused long enough that // the GPU is sure to be finished with it? // We multiply the retired particle index by four, because each // particle consists of a quad that is made up of four vertices. int age = drawCounter - (int)particles[firstRetiredParticle * 4].Time; // The GPU is never supposed to get more than 2 frames behind the CPU. // We add 1 to that, just to be safe in case of buggy drivers that // might bend the rules and let the GPU get further behind. if (age < 3) break; // Move the particle from the retired to the free queue. firstRetiredParticle++; if (firstRetiredParticle >= settings.MaxParticles) firstRetiredParticle = 0; } } /// <summary> /// Draws the particle system. /// </summary> public override void Draw(GameTime gameTime) { GraphicsDevice device = GraphicsDevice; // Restore the vertex buffer contents if the graphics device was lost. if (vertexBuffer.IsContentLost) { vertexBuffer.SetData(particles); } // If there are any particles waiting in the newly added queue, // we'd better upload them to the GPU ready for drawing. if (firstNewParticle != firstFreeParticle) { AddNewParticlesToVertexBuffer(); } // If there are any active particles, draw them now! if (firstActiveParticle != firstFreeParticle) { device.BlendState = settings.BlendState; device.DepthStencilState = DepthStencilState.DepthRead; // Set an effect parameter describing the viewport size. This is // needed to convert particle sizes into screen space point sizes. effectViewportScaleParameter.SetValue(new Vector2(0.5f / device.Viewport.AspectRatio, -0.5f)); // Set an effect parameter describing the current time. All the vertex // shader particle animation is keyed off this value. effectTimeParameter.SetValue(currentTime); // Set the particle vertex and index buffer. device.SetVertexBuffer(vertexBuffer); device.Indices = indexBuffer; // Activate the particle effect. foreach (EffectPass pass in particleEffect.CurrentTechnique.Passes) { pass.Apply(); if (firstActiveParticle < firstFreeParticle) { // If the active particles are all in one consecutive range, // we can draw them all in a single call. device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, firstActiveParticle * 4, (firstFreeParticle - firstActiveParticle) * 4, firstActiveParticle * 6, (firstFreeParticle - firstActiveParticle) * 2); } else { // If the active particle range wraps past the end of the queue // back to the start, we must split them over two draw calls. device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, firstActiveParticle * 4, (settings.MaxParticles - firstActiveParticle) * 4, firstActiveParticle * 6, (settings.MaxParticles - firstActiveParticle) * 2); if (firstFreeParticle > 0) { device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, firstFreeParticle * 4, 0, firstFreeParticle * 2); } } } // Reset some of the renderstates that we changed, // so as not to mess up any other subsequent drawing. device.DepthStencilState = DepthStencilState.Default; } drawCounter++; } /// <summary> /// Helper for uploading new particles from our managed /// array to the GPU vertex buffer. /// </summary> void AddNewParticlesToVertexBuffer() { int stride = ParticleVertex.SizeInBytes; if (firstNewParticle < firstFreeParticle) { // If the new particles are all in one consecutive range, // we can upload them all in a single call. vertexBuffer.SetData(firstNewParticle * stride * 4, particles, firstNewParticle * 4, (firstFreeParticle - firstNewParticle) * 4, stride, SetDataOptions.NoOverwrite); } else { // If the new particle range wraps past the end of the queue // back to the start, we must split them over two upload calls. vertexBuffer.SetData(firstNewParticle * stride * 4, particles, firstNewParticle * 4, (settings.MaxParticles - firstNewParticle) * 4, stride, SetDataOptions.NoOverwrite); if (firstFreeParticle > 0) { vertexBuffer.SetData(0, particles, 0, firstFreeParticle * 4, stride, SetDataOptions.NoOverwrite); } } // Move the particles we just uploaded from the new to the active queue. firstNewParticle = firstFreeParticle; } #endregion #region Public Methods /// <summary> /// Sets the camera view and projection matrices /// that will be used to draw this particle system. /// </summary> public void SetCamera(Matrix view, Matrix projection) { effectViewParameter.SetValue(view); effectProjectionParameter.SetValue(projection); } /// <summary> /// Adds a new particle to the system. /// </summary> public void AddParticle(Vector3 position, Vector3 velocity) { // Figure out where in the circular queue to allocate the new particle. int nextFreeParticle = firstFreeParticle + 1; if (nextFreeParticle >= settings.MaxParticles) nextFreeParticle = 0; // If there are no free particles, we just have to give up. if (nextFreeParticle == firstRetiredParticle) return; // Adjust the input velocity based on how much // this particle system wants to be affected by it. velocity *= settings.EmitterVelocitySensitivity; // Add in some random amount of horizontal velocity. float horizontalVelocity = MathHelper.Lerp(settings.MinHorizontalVelocity, settings.MaxHorizontalVelocity, (float)random.NextDouble()); double horizontalAngle = random.NextDouble() * MathHelper.TwoPi; velocity.X += horizontalVelocity * (float)Math.Cos(horizontalAngle); velocity.Z += horizontalVelocity * (float)Math.Sin(horizontalAngle); // Add in some random amount of vertical velocity. velocity.Y += MathHelper.Lerp(settings.MinVerticalVelocity, settings.MaxVerticalVelocity, (float)random.NextDouble()); // Choose four random control values. These will be used by the vertex // shader to give each particle a different size, rotation, and color. Color randomValues = new Color((byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255)); // Fill in the particle vertex structure. for (int i = 0; i < 4; i++) { particles[firstFreeParticle * 4 + i].Position = position; particles[firstFreeParticle * 4 + i].Velocity = velocity; particles[firstFreeParticle * 4 + i].Random = randomValues; particles[firstFreeParticle * 4 + i].Time = currentTime; } firstFreeParticle = nextFreeParticle; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** Purpose: Generic hash table implementation ** ** #DictionaryVersusHashtableThreadSafety ** Hashtable has multiple reader/single writer (MR/SW) thread safety built into ** certain methods and properties, whereas Dictionary doesn't. If you're ** converting framework code that formerly used Hashtable to Dictionary, it's ** important to consider whether callers may have taken a dependence on MR/SW ** thread safety. If a reader writer lock is available, then that may be used ** with a Dictionary to get the same thread safety guarantee. ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Collections; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; /// <summary> /// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>. /// </summary> internal enum InsertionBehavior : byte { /// <summary> /// The default insertion behavior. /// </summary> None = 0, /// <summary> /// Specifies that an existing entry with the same key should be overwritten if encountered. /// </summary> OverwriteExisting = 1, /// <summary> /// Specifies that if an existing entry with the same key is encountered, an exception should be thrown. /// </summary> ThrowOnExisting = 2 } [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback { private struct Entry { public int hashCode; // Lower 31 bits of hash code, -1 if unused public int next; // Index of next entry, -1 if last public TKey key; // Key of entry public TValue value; // Value of entry } private int[] buckets; private Entry[] entries; private int count; private int version; private int freeList; private int freeCount; private IEqualityComparer<TKey> comparer; private KeyCollection keys; private ValueCollection values; private Object _syncRoot; // constants for serialization private const String VersionName = "Version"; // Do not rename (binary serialization) private const String HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length private const String KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization) private const String ComparerName = "Comparer"; // Do not rename (binary serialization) public Dictionary() : this(0, null) { } public Dictionary(int capacity) : this(capacity, null) { } public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { } public Dictionary(int capacity, IEqualityComparer<TKey> comparer) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); if (capacity > 0) Initialize(capacity); this.comparer = comparer ?? EqualityComparer<TKey>.Default; if (this.comparer == EqualityComparer<string>.Default) { this.comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default; } } public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : this(dictionary != null ? dictionary.Count : 0, comparer) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } // It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case, // avoid the enumerator allocation and overhead by looping through the entries array directly. // We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain // back-compat with subclasses that may have overridden the enumerator behavior. if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>)) { Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary; int count = d.count; Entry[] entries = d.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { Add(entries[i].key, entries[i].value); } } return; } foreach (KeyValuePair<TKey, TValue> pair in dictionary) { Add(pair.Key, pair.Value); } } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer) : this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } foreach (KeyValuePair<TKey, TValue> pair in collection) { Add(pair.Key, pair.Value); } } protected Dictionary(SerializationInfo info, StreamingContext context) { //We can't do anything with the keys and values until the entire graph has been deserialized //and we have a resonable estimate that GetHashCode is not going to fail. For the time being, //we'll just cache this. The graph is not valid until OnDeserialization has been called. HashHelpers.SerializationInfoTable.Add(this, info); } public IEqualityComparer<TKey> Comparer { get { return comparer; } } public int Count { get { return count - freeCount; } } public KeyCollection Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } public ValueCollection Values { get { if (values == null) values = new ValueCollection(this); return values; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { if (values == null) values = new ValueCollection(this); return values; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { if (values == null) values = new ValueCollection(this); return values; } } public TValue this[TKey key] { get { int i = FindEntry(key); if (i >= 0) return entries[i].value; ThrowHelper.ThrowKeyNotFoundException(); return default(TValue); } set { bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting); Debug.Assert(modified); } } public void Add(TKey key, TValue value) { bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting); Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown. } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) { Remove(keyValuePair.Key); return true; } return false; } public void Clear() { if (count > 0) { for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; Array.Clear(entries, 0, count); freeList = -1; count = 0; freeCount = 0; version++; } } public bool ContainsKey(TKey key) { return FindEntry(key) >= 0; } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && entries[i].value == null) return true; } } else { EqualityComparer<TValue> c = EqualityComparer<TValue>.Default; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true; } } return false; } private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = this.count; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } public Enumerator GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue(VersionName, version); info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>)); info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array. if (buckets != null) { KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[Count]; CopyTo(array, 0); info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[])); } } private int FindEntry(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i; } } return -1; } private void Initialize(int capacity) { int size = HashHelpers.GetPrime(capacity); buckets = new int[size]; for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; entries = new Entry[size]; freeList = -1; } private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets == null) Initialize(0); int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int targetBucket = hashCode % buckets.Length; int collisionCount = 0; for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (behavior == InsertionBehavior.OverwriteExisting) { entries[i].value = value; version++; return true; } if (behavior == InsertionBehavior.ThrowOnExisting) { ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); } return false; } collisionCount++; } int index; if (freeCount > 0) { index = freeList; freeList = entries[index].next; freeCount--; } else { if (count == entries.Length) { Resize(); targetBucket = hashCode % buckets.Length; } index = count; count++; } entries[index].hashCode = hashCode; entries[index].next = buckets[targetBucket]; entries[index].key = key; entries[index].value = value; buckets[targetBucket] = index; version++; // If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing // i.e. EqualityComparer<string>.Default. if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default) { comparer = (IEqualityComparer<TKey>)EqualityComparer<string>.Default; Resize(entries.Length, true); } return true; } public virtual void OnDeserialization(Object sender) { SerializationInfo siInfo; HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo); if (siInfo == null) { // It might be necessary to call OnDeserialization from a container if the container object also implements // OnDeserialization. However, remoting will call OnDeserialization again. // We can return immediately if this function is called twice. // Note we set remove the serialization info from the table at the end of this method. return; } int realVersion = siInfo.GetInt32(VersionName); int hashsize = siInfo.GetInt32(HashSizeName); comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>)); if (hashsize != 0) { buckets = new int[hashsize]; for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; entries = new Entry[hashsize]; freeList = -1; KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[]) siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[])); if (array == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys); } for (int i = 0; i < array.Length; i++) { if (array[i].Key == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey); } Add(array[i].Key, array[i].Value); } } else { buckets = null; } version = realVersion; HashHelpers.SerializationInfoTable.Remove(this); } private void Resize() { Resize(HashHelpers.ExpandPrime(count), false); } private void Resize(int newSize, bool forceNewHashCodes) { Debug.Assert(newSize >= entries.Length); int[] newBuckets = new int[newSize]; for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1; Entry[] newEntries = new Entry[newSize]; Array.Copy(entries, 0, newEntries, 0, count); if (forceNewHashCodes) { for (int i = 0; i < count; i++) { if (newEntries[i].hashCode != -1) { newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF); } } } for (int i = 0; i < count; i++) { if (newEntries[i].hashCode >= 0) { int bucket = newEntries[i].hashCode % newSize; newEntries[i].next = newBuckets[bucket]; newBuckets[bucket] = i; } } buckets = newBuckets; entries = newEntries; } // The overload Remove(TKey key, out TValue value) is a copy of this method with one additional // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. public bool Remove(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int bucket = hashCode % buckets.Length; int last = -1; int i = buckets[bucket]; while (i >= 0) { ref Entry entry = ref entries[i]; if (entry.hashCode == hashCode && comparer.Equals(entry.key, key)) { if (last < 0) { buckets[bucket] = entry.next; } else { entries[last].next = entry.next; } entry.hashCode = -1; entry.next = freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { entry.key = default(TKey); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { entry.value = default(TValue); } freeList = i; freeCount++; version++; return true; } last = i; i = entry.next; } } return false; } // This overload is a copy of the overload Remove(TKey key) with one additional // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. public bool Remove(TKey key, out TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int bucket = hashCode % buckets.Length; int last = -1; int i = buckets[bucket]; while (i >= 0) { ref Entry entry = ref entries[i]; if (entry.hashCode == hashCode && comparer.Equals(entry.key, key)) { if (last < 0) { buckets[bucket] = entry.next; } else { entries[last].next = entry.next; } value = entry.value; entry.hashCode = -1; entry.next = freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { entry.key = default(TKey); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { entry.value = default(TValue); } freeList = i; freeCount++; version++; return true; } last = i; i = entry.next; } } value = default(TValue); return false; } public bool TryGetValue(TKey key, out TValue value) { int i = FindEntry(key); if (i >= 0) { value = entries[i].value; return true; } value = default(TValue); return false; } public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None); bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { CopyTo(array, index); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { CopyTo(pairs, index); } else if (array is DictionaryEntry[]) { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value); } } } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } try { int count = this.count; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } ICollection IDictionary.Keys { get { return (ICollection)Keys; } } ICollection IDictionary.Values { get { return (ICollection)Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { int i = FindEntry((TKey)key); if (i >= 0) { return entries[i].value; } } return null; } set { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } } private static bool IsCompatibleKey(object key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return (key is TKey); } void IDictionary.Add(object key, object value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { Add(tempKey, (TValue)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private Dictionary<TKey, TValue> dictionary; private int version; private int index; private KeyValuePair<TKey, TValue> current; private int getEnumeratorRetType; // What should Enumerator.Current return? internal const int DictEntry = 1; internal const int KeyValuePair = 2; internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType) { this.dictionary = dictionary; version = dictionary.version; index = 0; this.getEnumeratorRetType = getEnumeratorRetType; current = new KeyValuePair<TKey, TValue>(); } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue while ((uint)index < (uint)dictionary.count) { ref Entry entry = ref dictionary.entries[index++]; if (entry.hashCode >= 0) { current = new KeyValuePair<TKey, TValue>(entry.key, entry.value); return true; } } index = dictionary.count + 1; current = new KeyValuePair<TKey, TValue>(); return false; } public KeyValuePair<TKey, TValue> Current { get { return current; } } public void Dispose() { } object IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } if (getEnumeratorRetType == DictEntry) { return new System.Collections.DictionaryEntry(current.Key, current.Value); } else { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); } } } void IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } index = 0; current = new KeyValuePair<TKey, TValue>(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return new DictionaryEntry(current.Key, current.Value); } } object IDictionaryEnumerator.Key { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return current.Key; } } object IDictionaryEnumerator.Value { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return current.Value; } } } [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private Dictionary<TKey, TValue> dictionary; public KeyCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TKey[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; Entry[] entries = dictionary.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].key; } } public int Count { get { return dictionary.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } void ICollection<TKey>.Add(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Contains(TKey item) { return dictionary.ContainsKey(item); } bool ICollection<TKey>.Remove(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); return false; } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } TKey[] keys = array as TKey[]; if (keys != null) { CopyTo(keys, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = dictionary.count; Entry[] entries = dictionary.entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].key; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TKey currentKey; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentKey = default(TKey); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)index < (uint)dictionary.count) { ref Entry entry = ref dictionary.entries[index++]; if (entry.hashCode >= 0) { currentKey = entry.key; return true; } } index = dictionary.count + 1; currentKey = default(TKey); return false; } public TKey Current { get { return currentKey; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return currentKey; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } index = 0; currentKey = default(TKey); } } } [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private Dictionary<TKey, TValue> dictionary; public ValueCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TValue[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; Entry[] entries = dictionary.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].value; } } public int Count { get { return dictionary.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } void ICollection<TValue>.Add(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Remove(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); return false; } void ICollection<TValue>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Contains(TValue item) { return dictionary.ContainsValue(item); } IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < dictionary.Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); TValue[] values = array as TValue[]; if (values != null) { CopyTo(values, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = dictionary.count; Entry[] entries = dictionary.entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].value; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TValue currentValue; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentValue = default(TValue); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)index < (uint)dictionary.count) { ref Entry entry = ref dictionary.entries[index++]; if (entry.hashCode >= 0) { currentValue = entry.value; return true; } } index = dictionary.count + 1; currentValue = default(TValue); return false; } public TValue Current { get { return currentValue; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return currentValue; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } index = 0; currentValue = default(TValue); } } } } }
using Xunit; using Should; using System.Linq; namespace AutoMapper.UnitTests { namespace ReverseMapping { public class When_reverse_mapping_classes_with_simple_properties : AutoMapperSpecBase { private Source _source; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>() .ReverseMap(); }); } protected override void Because_of() { var dest = new Destination { Value = 10 }; _source = Mapper.Map<Destination, Source>(dest); } [Fact] public void Should_create_a_map_with_the_reverse_items() { _source.Value.ShouldEqual(10); } } public class When_validating_only_against_source_members_and_source_matches : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } public int Value2 { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source); }); } [Fact] public void Should_only_map_source_members() { var typeMap = Mapper.FindTypeMapFor<Source, Destination>(); typeMap.GetPropertyMaps().Count().ShouldEqual(1); } [Fact] public void Should_not_throw_any_configuration_validation_errors() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid); } } public class When_validating_only_against_source_members_and_source_does_not_match : NonValidatingSpecBase { public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Value { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source); }); } [Fact] public void Should_throw_a_configuration_validation_error() { typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid); } } public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped : NonValidatingSpecBase { public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Value { get; set; } public int Value3 { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source) .ForMember(dest => dest.Value3, opt => opt.MapFrom(src => src.Value2)); }); } [Fact] public void Should_not_throw_a_configuration_validation_error() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid); } } public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped_with_resolvers : NonValidatingSpecBase { public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Value { get; set; } public int Value3 { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source) .ForMember(dest => dest.Value3, opt => opt.ResolveUsing(src => src.Value2)) .ForSourceMember(src => src.Value2, opt => opt.Ignore()); }); } [Fact] public void Should_not_throw_a_configuration_validation_error() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid); } } public class When_reverse_mapping_and_ignoring_via_method : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Dest { public int Value { get; set; } public int Ignored { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Dest>() .ForMember(d => d.Ignored, opt => opt.Ignore()) .ReverseMap(); }); } [Fact] public void Should_show_valid() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Mapper.AssertConfigurationIsValid()); } } public class When_reverse_mapping_and_ignoring : AutoMapperSpecBase { public class Foo { public string Bar { get; set; } public string Baz { get; set; } } public class Foo2 { public string Bar { get; set; } public string Boo { get; set; } } [Fact] public void GetUnmappedPropertyNames_ShouldReturnBoo() { //Arrange Mapper.CreateMap<Foo, Foo2>(); var typeMap = Mapper.GetAllTypeMaps() .First(x => x.SourceType == typeof(Foo) && x.DestinationType == typeof(Foo2)); //Act var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames(); //Assert unmappedPropertyNames[0].ShouldEqual("Boo"); } [Fact] public void WhenSecondCallTo_GetUnmappedPropertyNames_ShouldReturnBoo() { //Arrange Mapper.CreateMap<Foo, Foo2>().ReverseMap(); var typeMap = Mapper.GetAllTypeMaps() .First(x => x.SourceType == typeof(Foo2) && x.DestinationType == typeof(Foo)); //Act var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames(); //Assert unmappedPropertyNames[0].ShouldEqual("Boo"); } [Fact] public void Should_not_throw_exception_for_unmapped_properties() { Mapper.CreateMap<Foo, Foo2>() .IgnoreAllNonExisting() .ReverseMap() .IgnoreAllNonExistingSource(); Mapper.AssertConfigurationIsValid(); } } public static class AutoMapperExtensions { // from http://stackoverflow.com/questions/954480/automapper-ignore-the-rest/6474397#6474397 public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this AutoMapper.IMappingExpression<TSource, TDestination> expression) { var sourceType = typeof(TSource); var destinationType = typeof(TDestination); var existingMaps = AutoMapper.Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType)); foreach (var property in existingMaps.GetUnmappedPropertyNames()) { expression.ForMember(property, opt => opt.Ignore()); } return expression; } public static IMappingExpression<TSource, TDestination> IgnoreAllNonExistingSource<TSource, TDestination>(this AutoMapper.IMappingExpression<TSource, TDestination> expression) { var sourceType = typeof(TSource); var destinationType = typeof(TDestination); var existingMaps = AutoMapper.Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType)); foreach (var property in existingMaps.GetUnmappedPropertyNames()) { expression.ForSourceMember(property, opt => opt.Ignore()); } return expression; } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Agent.Plugins.Log.TestResultParser.Contracts; using Agent.Sdk; using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; namespace Agent.Plugins.Log.TestResultParser.Plugin { public class TestResultLogPlugin : IAgentLogPlugin { /// <inheritdoc /> public string FriendlyName => "TestResultLogParser"; public TestResultLogPlugin() { // Default constructor } /// <summary> /// For UTs only /// </summary> public TestResultLogPlugin(ILogParserGateway inputDataParser, ITraceLogger logger, ITelemetryDataCollector telemetry) { _logger = logger; _telemetry = telemetry; _inputDataParser = inputDataParser; } /// <inheritdoc /> public async Task<bool> InitializeAsync(IAgentLogPluginContext context) { try { _logger = _logger ?? new TraceLogger(context); _clientFactory = new ClientFactory(context.VssConnection); _telemetry = _telemetry ?? new TelemetryDataCollector(_clientFactory, _logger); await PopulatePipelineConfig(context); if (DisablePlugin(context)) { _telemetry.AddOrUpdate(TelemetryConstants.PluginDisabled, true); await _telemetry.PublishCumulativeTelemetryAsync(); return false; // disable the plugin } await _inputDataParser.InitializeAsync(_clientFactory, _pipelineConfig, _logger, _telemetry); _telemetry.AddOrUpdate(TelemetryConstants.PluginInitialized, true); } catch (Exception ex) { context.Trace(ex.ToString()); _logger?.Warning($"Unable to initialize {FriendlyName}."); if (_telemetry != null) { _telemetry?.AddOrUpdate(TelemetryConstants.InitialzieFailed, ex); await _telemetry.PublishCumulativeTelemetryAsync(); } return false; } return true; } /// <inheritdoc /> public async Task ProcessLineAsync(IAgentLogPluginContext context, Pipelines.TaskStepDefinitionReference step, string line) { await _inputDataParser.ProcessDataAsync(line); } /// <inheritdoc /> public async Task FinalizeAsync(IAgentLogPluginContext context) { using (var timer = new SimpleTimer("Finalize", _logger, new TelemetryDataWrapper(_telemetry, TelemetryConstants.FinalizeAsync), TimeSpan.FromMilliseconds(Int32.MaxValue))) { await _inputDataParser.CompleteAsync(); } await _telemetry.PublishCumulativeTelemetryAsync(); } /// <summary> /// Return true if plugin needs to be disabled /// </summary> private bool DisablePlugin(IAgentLogPluginContext context) { // do we want to log that the plugin is disabled due to x reason here? if (context.Variables.TryGetValue("Agent.ForceEnable.TestResultLogPlugin", out var forceEnableTestResultParsers) && string.Equals("true", forceEnableTestResultParsers.Value, StringComparison.OrdinalIgnoreCase)) { return false; } // Enable only for build if (!context.Variables.TryGetValue("system.hosttype", out var hostType) || !string.Equals("Build", hostType.Value, StringComparison.OrdinalIgnoreCase)) { _telemetry.AddOrUpdate("PluginDisabledReason", hostType?.Value); return true; } // Disable for on-prem if (!context.Variables.TryGetValue("system.servertype", out var serverType) || !string.Equals("Hosted", serverType.Value, StringComparison.OrdinalIgnoreCase)) { _telemetry.AddOrUpdate("PluginDisabledReason", serverType?.Value); return true; } // check for PTR task or some other tasks to enable/disable if (context.Steps == null) { _telemetry.AddOrUpdate("PluginDisabledReason", "NoSteps"); return true; } if (context.Steps.Any(x => x.Id.Equals(new Guid("0B0F01ED-7DDE-43FF-9CBB-E48954DAF9B1")))) { _telemetry.AddOrUpdate("PluginDisabledReason", "ExplicitPublishTaskPresent"); return true; } if (_pipelineConfig.BuildId == 0) { _telemetry.AddOrUpdate("PluginDisabledReason", "BuildIdZero"); return true; } return false; } private async Task PopulatePipelineConfig(IAgentLogPluginContext context) { var props = new Dictionary<string, Object>(); if (context.Variables.TryGetValue("system.teamProjectId", out var projectGuid)) { _pipelineConfig.Project = new Guid(projectGuid.Value); _telemetry.AddOrUpdate("ProjectId", _pipelineConfig.Project); props.Add("ProjectId", _pipelineConfig.Project); } if (context.Variables.TryGetValue("build.buildId", out var buildIdVar) && int.TryParse(buildIdVar.Value, out var buildId)) { _pipelineConfig.BuildId = buildId; _telemetry.AddOrUpdate("BuildId", buildId); props.Add("BuildId", buildId); } if (context.Variables.TryGetValue("system.stageName", out var stageName)) { _pipelineConfig.StageName = stageName.Value; _telemetry.AddOrUpdate("StageName", stageName.Value); props.Add("StageName", stageName.Value); } if (context.Variables.TryGetValue("system.stageAttempt", out var stageAttemptVar) && int.TryParse(stageAttemptVar.Value, out var stageAttempt)) { _pipelineConfig.StageAttempt = stageAttempt; _telemetry.AddOrUpdate("StageAttempt", stageAttempt); props.Add("StageAttempt", stageAttempt); } if (context.Variables.TryGetValue("system.phaseName", out var phaseName)) { _pipelineConfig.PhaseName = phaseName.Value; _telemetry.AddOrUpdate("PhaseName", phaseName.Value); props.Add("PhaseName", phaseName.Value); } if (context.Variables.TryGetValue("system.phaseAttempt", out var phaseAttemptVar) && int.TryParse(phaseAttemptVar.Value, out var phaseAttempt)) { _pipelineConfig.PhaseAttempt = phaseAttempt; _telemetry.AddOrUpdate("PhaseAttempt", phaseAttempt); props.Add("PhaseAttempt", phaseAttempt); } if (context.Variables.TryGetValue("system.jobName", out var jobName)) { _pipelineConfig.JobName = jobName.Value; _telemetry.AddOrUpdate("JobName", jobName.Value); props.Add("JobName", jobName.Value); } if (context.Variables.TryGetValue("system.jobAttempt", out var jobAttemptVar) && int.TryParse(jobAttemptVar.Value, out var jobAttempt)) { _pipelineConfig.JobAttempt = jobAttempt; _telemetry.AddOrUpdate("JobAttempt", jobAttempt); props.Add("JobAttempt", jobAttempt); } if (context.Variables.TryGetValue("system.definitionid", out var buildDefinitionId)) { _telemetry.AddOrUpdate("BuildDefinitionId", buildDefinitionId.Value); props.Add("BuildDefinitionId", buildDefinitionId.Value); } if (context.Variables.TryGetValue("build.Repository.name", out var repositoryName)) { _telemetry.AddOrUpdate("RepositoryName", repositoryName.Value); props.Add("RepositoryName", repositoryName.Value); } if (context.Variables.TryGetValue("agent.version", out var agentVersion)) { _telemetry.AddOrUpdate("AgentVersion", agentVersion.Value); props.Add("AgentVersion", agentVersion.Value); } // Publish the initial telemetry event in case we are not able to fire the cumulative one for whatever reason await _telemetry.PublishTelemetryAsync("TestResultParserInitialize", props); } private readonly ILogParserGateway _inputDataParser = new LogParserGateway(); private IClientFactory _clientFactory; private ITraceLogger _logger; private ITelemetryDataCollector _telemetry; private readonly IPipelineConfig _pipelineConfig = new PipelineConfig(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.HttpSys.Internal; using Microsoft.Extensions.Logging; using static Microsoft.AspNetCore.HttpSys.Internal.UnsafeNclNativeMethods; namespace Microsoft.AspNetCore.Server.HttpSys { internal class ResponseBody : Stream { private readonly RequestContext _requestContext; private long _leftToWrite = long.MinValue; private bool _skipWrites; private bool _disposed; // The last write needs special handling to cancel. private ResponseStreamAsyncResult? _lastWrite; internal ResponseBody(RequestContext requestContext) { _requestContext = requestContext; } internal RequestContext RequestContext { get { return _requestContext; } } private SafeHandle RequestQueueHandle => RequestContext.Server.RequestQueue.Handle; private ulong RequestId => RequestContext.Request.RequestId; private ILogger Logger => RequestContext.Server.Logger; internal bool ThrowWriteExceptions => RequestContext.Server.Options.ThrowWriteExceptions; internal bool IsDisposed => _disposed; public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override bool CanRead { get { return false; } } public override long Length { get { throw new NotSupportedException(Resources.Exception_NoSeek); } } public override long Position { get { throw new NotSupportedException(Resources.Exception_NoSeek); } set { throw new NotSupportedException(Resources.Exception_NoSeek); } } // Send headers public override void Flush() { if (!RequestContext.AllowSynchronousIO) { throw new InvalidOperationException("Synchronous IO APIs are disabled, see AllowSynchronousIO."); } if (_disposed) { return; } FlushInternal(endOfRequest: false); } public void MarkDelegated() { _skipWrites = true; } // We never expect endOfRequest and data at the same time private unsafe void FlushInternal(bool endOfRequest, ArraySegment<byte> data = new ArraySegment<byte>()) { Debug.Assert(!(endOfRequest && data.Count > 0), "Data is not supported at the end of the request."); if (_skipWrites) { return; } var started = _requestContext.Response.HasStarted; if (data.Count == 0 && started && !endOfRequest) { // No data to send and we've already sent the headers return; } // Make sure all validation is performed before this computes the headers var flags = ComputeLeftToWrite(data.Count, endOfRequest); if (endOfRequest && _leftToWrite > 0) { if (!RequestContext.DisconnectToken.IsCancellationRequested) { // This is logged rather than thrown because it is too late for an exception to be visible in user code. Log.FewerBytesThanExpected(Logger); } _requestContext.Abort(); return; } uint statusCode = 0; HttpApiTypes.HTTP_DATA_CHUNK[] dataChunks; var pinnedBuffers = PinDataBuffers(endOfRequest, data, out dataChunks); try { if (!started) { statusCode = _requestContext.Response.SendHeaders(dataChunks, null, flags, false); } else { fixed (HttpApiTypes.HTTP_DATA_CHUNK* pDataChunks = dataChunks) { statusCode = HttpApi.HttpSendResponseEntityBody( RequestQueueHandle, RequestId, (uint)flags, (ushort)dataChunks.Length, pDataChunks, null, IntPtr.Zero, 0, SafeNativeOverlapped.Zero, IntPtr.Zero); } } } finally { FreeDataBuffers(pinnedBuffers); } if (statusCode != ErrorCodes.ERROR_SUCCESS && statusCode != ErrorCodes.ERROR_HANDLE_EOF // Don't throw for disconnects, we were already finished with the response. && (!endOfRequest || (statusCode != ErrorCodes.ERROR_CONNECTION_INVALID && statusCode != ErrorCodes.ERROR_INVALID_PARAMETER))) { if (ThrowWriteExceptions) { var exception = new IOException(string.Empty, new HttpSysException((int)statusCode)); Log.WriteError(Logger, exception); Abort(); throw exception; } else { // Abort the request but do not close the stream, let future writes complete silently Log.WriteErrorIgnored(Logger, statusCode); Abort(dispose: false); } } } private List<GCHandle> PinDataBuffers(bool endOfRequest, ArraySegment<byte> data, out HttpApiTypes.HTTP_DATA_CHUNK[] dataChunks) { var pins = new List<GCHandle>(); var hasData = data.Count > 0; var chunked = _requestContext.Response.BoundaryType == BoundaryType.Chunked; var addTrailers = endOfRequest && _requestContext.Response.HasTrailers; Debug.Assert(!(addTrailers && chunked), "Trailers aren't currently supported for HTTP/1.1 chunking."); var currentChunk = 0; // Figure out how many data chunks if (chunked && !hasData && endOfRequest) { dataChunks = new HttpApiTypes.HTTP_DATA_CHUNK[1]; SetDataChunk(dataChunks, ref currentChunk, pins, new ArraySegment<byte>(Helpers.ChunkTerminator)); return pins; } else if (!hasData && !addTrailers) { // No data dataChunks = Array.Empty<HttpApiTypes.HTTP_DATA_CHUNK>(); return pins; } var chunkCount = hasData ? 1 : 0; if (addTrailers) { chunkCount++; } else if (chunked) // HTTP/1.1 chunking, not currently supported with trailers { Debug.Assert(hasData); // Chunk framing chunkCount += 2; if (endOfRequest) { // Chunk terminator chunkCount += 1; } } dataChunks = new HttpApiTypes.HTTP_DATA_CHUNK[chunkCount]; if (chunked) { var chunkHeaderBuffer = Helpers.GetChunkHeader(data.Count); SetDataChunk(dataChunks, ref currentChunk, pins, chunkHeaderBuffer); } if (hasData) { SetDataChunk(dataChunks, ref currentChunk, pins, data); } if (chunked) { SetDataChunk(dataChunks, ref currentChunk, pins, new ArraySegment<byte>(Helpers.CRLF)); if (endOfRequest) { SetDataChunk(dataChunks, ref currentChunk, pins, new ArraySegment<byte>(Helpers.ChunkTerminator)); } } if (addTrailers) { _requestContext.Response.SerializeTrailers(dataChunks, currentChunk, pins); } else if (endOfRequest) { _requestContext.Response.MakeTrailersReadOnly(); } return pins; } private static void SetDataChunk(HttpApiTypes.HTTP_DATA_CHUNK[] chunks, ref int chunkIndex, List<GCHandle> pins, ArraySegment<byte> buffer) { var handle = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned); pins.Add(handle); chunks[chunkIndex].DataChunkType = HttpApiTypes.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory; chunks[chunkIndex].fromMemory.pBuffer = handle.AddrOfPinnedObject() + buffer.Offset; chunks[chunkIndex].fromMemory.BufferLength = (uint)buffer.Count; chunkIndex++; } private void FreeDataBuffers(List<GCHandle> pinnedBuffers) { foreach (var pin in pinnedBuffers) { if (pin.IsAllocated) { pin.Free(); } } } public override Task FlushAsync(CancellationToken cancellationToken) { if (_disposed) { return Task.CompletedTask; } return FlushInternalAsync(new ArraySegment<byte>(), cancellationToken); } // Simpler than Flush because it will never be called at the end of the request from Dispose. private unsafe Task FlushInternalAsync(ArraySegment<byte> data, CancellationToken cancellationToken) { if (_skipWrites) { return Task.CompletedTask; } var started = _requestContext.Response.HasStarted; if (data.Count == 0 && started) { // No data to send and we've already sent the headers return Task.CompletedTask; } if (cancellationToken.IsCancellationRequested) { Abort(ThrowWriteExceptions); return Task.FromCanceled<int>(cancellationToken); } // Make sure all validation is performed before this computes the headers var flags = ComputeLeftToWrite(data.Count); uint statusCode = 0; var chunked = _requestContext.Response.BoundaryType == BoundaryType.Chunked; var asyncResult = new ResponseStreamAsyncResult(this, data, chunked, cancellationToken); uint bytesSent = 0; try { if (!started) { statusCode = _requestContext.Response.SendHeaders(null, asyncResult, flags, false); bytesSent = asyncResult.BytesSent; } else { statusCode = HttpApi.HttpSendResponseEntityBody( RequestQueueHandle, RequestId, (uint)flags, asyncResult.DataChunkCount, asyncResult.DataChunks, &bytesSent, IntPtr.Zero, 0, asyncResult.NativeOverlapped!, IntPtr.Zero); } } catch (Exception e) { Log.ErrorWhenFlushAsync(Logger, e); asyncResult.Dispose(); Abort(); throw; } if (statusCode != ErrorCodes.ERROR_SUCCESS && statusCode != ErrorCodes.ERROR_IO_PENDING) { if (cancellationToken.IsCancellationRequested) { Log.WriteFlushCancelled(Logger, statusCode); asyncResult.Cancel(ThrowWriteExceptions); } else if (ThrowWriteExceptions) { asyncResult.Dispose(); Exception exception = new IOException(string.Empty, new HttpSysException((int)statusCode)); Log.ErrorWhenFlushAsync(Logger, exception); Abort(); throw exception; } else { // Abort the request but do not close the stream, let future writes complete silently Log.WriteErrorIgnored(Logger, statusCode); asyncResult.FailSilently(); } } if (statusCode == ErrorCodes.ERROR_SUCCESS && HttpSysListener.SkipIOCPCallbackOnSuccess) { // IO operation completed synchronously - callback won't be called to signal completion. asyncResult.IOCompleted(statusCode, bytesSent); } // Last write, cache it for special cancellation handling. if ((flags & HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA) == 0) { _lastWrite = asyncResult; } return asyncResult.Task; } #region NotSupported Read/Seek public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(Resources.Exception_NoSeek); } public override void SetLength(long value) { throw new NotSupportedException(Resources.Exception_NoSeek); } public override int Read([In, Out] byte[] buffer, int offset, int count) { throw new InvalidOperationException(Resources.Exception_WriteOnlyStream); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) { throw new InvalidOperationException(Resources.Exception_WriteOnlyStream); } public override int EndRead(IAsyncResult asyncResult) { throw new InvalidOperationException(Resources.Exception_WriteOnlyStream); } #endregion internal void Abort(bool dispose = true) { if (dispose) { _disposed = true; } else { _skipWrites = true; } _requestContext.Abort(); } private HttpApiTypes.HTTP_FLAGS ComputeLeftToWrite(long writeCount, bool endOfRequest = false) { var flags = HttpApiTypes.HTTP_FLAGS.NONE; if (!_requestContext.Response.HasComputedHeaders) { flags = _requestContext.Response.ComputeHeaders(writeCount, endOfRequest); } if (_leftToWrite == long.MinValue) { if (_requestContext.Request.IsHeadMethod) { _leftToWrite = 0; } else if (_requestContext.Response.BoundaryType == BoundaryType.ContentLength) { _leftToWrite = _requestContext.Response.ExpectedBodyLength; } else { _leftToWrite = -1; // unlimited } } if (endOfRequest && _requestContext.Response.BoundaryType == BoundaryType.Close) { flags |= HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT; } else if (!endOfRequest && (_leftToWrite != writeCount || _requestContext.Response.TrailersExpected)) { flags |= HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA; } // Update _leftToWrite now so we can queue up additional async writes. if (_leftToWrite > 0) { // keep track of the data transferred _leftToWrite -= writeCount; } if (_leftToWrite == 0 && !_requestContext.Response.TrailersExpected) { // in this case we already passed 0 as the flag, so we don't need to call HttpSendResponseEntityBody() when we Close() _requestContext.Response.MakeTrailersReadOnly(); _disposed = true; } // else -1 unlimited return flags; } public override void Write(byte[] buffer, int offset, int count) { ValidateBufferArguments(buffer, offset, count); if (!RequestContext.AllowSynchronousIO) { throw new InvalidOperationException("Synchronous IO APIs are disabled, see AllowSynchronousIO."); } // Validates for null and bounds. Allows count == 0. // TODO: Verbose log parameters var data = new ArraySegment<byte>(buffer, offset, count); CheckDisposed(); CheckWriteCount(count); FlushInternal(endOfRequest: false, data: data); } private void CheckWriteCount(long? count) { var contentLength = _requestContext.Response.ContentLength; // First write with more bytes written than the entire content-length if (!_requestContext.Response.HasComputedHeaders && contentLength < count) { throw new InvalidOperationException("More bytes written than specified in the Content-Length header."); } // A write in a response that has already started where the count exceeds the remainder of the content-length else if (_requestContext.Response.HasComputedHeaders && _requestContext.Response.BoundaryType == BoundaryType.ContentLength && _leftToWrite < count) { throw new InvalidOperationException("More bytes written than specified in the Content-Length header."); } } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) { return TaskToApm.Begin(WriteAsync(buffer, offset, count), callback, state); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } TaskToApm.End(asyncResult); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { ValidateBufferArguments(buffer, offset, count); // Validates for null and bounds. Allows count == 0. // TODO: Verbose log parameters var data = new ArraySegment<byte>(buffer, offset, count); CheckDisposed(); CheckWriteCount(count); return FlushInternalAsync(data, cancellationToken); } internal async Task SendFileAsync(string fileName, long offset, long? count, CancellationToken cancellationToken) { // It's too expensive to validate the file attributes before opening the file. Open the file and then check the lengths. // This all happens inside of ResponseStreamAsyncResult. // TODO: Verbose log parameters if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } CheckDisposed(); CheckWriteCount(count); // We can't mix await and unsafe so separate the unsafe code into another method. await SendFileAsyncCore(fileName, offset, count, cancellationToken); } internal unsafe Task SendFileAsyncCore(string fileName, long offset, long? count, CancellationToken cancellationToken) { if (_skipWrites) { return Task.CompletedTask; } var started = _requestContext.Response.HasStarted; if (count == 0 && started) { // No data to send and we've already sent the headers return Task.CompletedTask; } if (cancellationToken.IsCancellationRequested) { Abort(ThrowWriteExceptions); return Task.FromCanceled<int>(cancellationToken); } // We are setting buffer size to 1 to prevent FileStream from allocating it's internal buffer // It's too expensive to validate anything before opening the file. Open the file and then check the lengths. var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 1, options: FileOptions.Asynchronous | FileOptions.SequentialScan); // Extremely expensive. try { var length = fileStream.Length; // Expensive, only do it once if (!count.HasValue) { count = length - offset; } if (offset < 0 || offset > length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty); } if (count < 0 || count > length - offset) { throw new ArgumentOutOfRangeException(nameof(count), count, string.Empty); } CheckWriteCount(count); } catch { fileStream.Dispose(); throw; } // Make sure all validation is performed before this computes the headers var flags = ComputeLeftToWrite(count.Value); uint statusCode; uint bytesSent = 0; var chunked = _requestContext.Response.BoundaryType == BoundaryType.Chunked; var asyncResult = new ResponseStreamAsyncResult(this, fileStream, offset, count.Value, chunked, cancellationToken); try { if (!started) { statusCode = _requestContext.Response.SendHeaders(null, asyncResult, flags, false); bytesSent = asyncResult.BytesSent; } else { // TODO: If opaque then include the buffer data flag. statusCode = HttpApi.HttpSendResponseEntityBody( RequestQueueHandle, RequestId, (uint)flags, asyncResult.DataChunkCount, asyncResult.DataChunks, &bytesSent, IntPtr.Zero, 0, asyncResult.NativeOverlapped!, IntPtr.Zero); } } catch (Exception e) { Log.FileSendAsyncError(Logger, e); asyncResult.Dispose(); Abort(); throw; } if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING) { if (cancellationToken.IsCancellationRequested) { Log.FileSendAsyncCancelled(Logger, statusCode); asyncResult.Cancel(ThrowWriteExceptions); } else if (ThrowWriteExceptions) { asyncResult.Dispose(); var exception = new IOException(string.Empty, new HttpSysException((int)statusCode)); Log.FileSendAsyncError(Logger, exception); Abort(); throw exception; } else { // Abort the request but do not close the stream, let future writes complete Log.FileSendAsyncErrorIgnored(Logger, statusCode); asyncResult.FailSilently(); } } if (statusCode == ErrorCodes.ERROR_SUCCESS && HttpSysListener.SkipIOCPCallbackOnSuccess) { // IO operation completed synchronously - callback won't be called to signal completion. asyncResult.IOCompleted(statusCode, bytesSent); } // Last write, cache it for special cancellation handling. if ((flags & HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA) == 0) { _lastWrite = asyncResult; } return asyncResult.Task; } protected override unsafe void Dispose(bool disposing) { try { if (disposing) { if (_disposed) { return; } FlushInternal(endOfRequest: true); _disposed = true; } } finally { base.Dispose(disposing); } } internal void SwitchToOpaqueMode() { _leftToWrite = -1; } // The final Content-Length async write can only be Canceled by CancelIoEx. // Sync can only be Canceled by CancelSynchronousIo, but we don't attempt this right now. internal unsafe void CancelLastWrite() { ResponseStreamAsyncResult? asyncState = _lastWrite; if (asyncState != null && !asyncState.IsCompleted) { UnsafeNclNativeMethods.CancelIoEx(RequestQueueHandle, asyncState.NativeOverlapped!); } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private static class Log { private static readonly Action<ILogger, Exception?> _fewerBytesThanExpected = LoggerMessage.Define(LogLevel.Error, LoggerEventIds.FewerBytesThanExpected, "ResponseStream::Dispose; Fewer bytes were written than were specified in the Content-Length."); private static readonly Action<ILogger, Exception> _writeError = LoggerMessage.Define(LogLevel.Error, LoggerEventIds.WriteError, "Flush"); private static readonly Action<ILogger, uint, Exception?> _writeErrorIgnored = LoggerMessage.Define<uint>(LogLevel.Debug, LoggerEventIds.WriteErrorIgnored, "Flush; Ignored write exception: {StatusCode}"); private static readonly Action<ILogger, Exception> _errorWhenFlushAsync = LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.ErrorWhenFlushAsync, "FlushAsync"); private static readonly Action<ILogger, uint, Exception?> _writeFlushCancelled = LoggerMessage.Define<uint>(LogLevel.Debug, LoggerEventIds.WriteFlushCancelled, "FlushAsync; Write cancelled with error code: {StatusCode}"); private static readonly Action<ILogger, Exception> _fileSendAsyncError = LoggerMessage.Define(LogLevel.Error, LoggerEventIds.FileSendAsyncError, "SendFileAsync"); private static readonly Action<ILogger, uint, Exception?> _fileSendAsyncCancelled = LoggerMessage.Define<uint>(LogLevel.Debug, LoggerEventIds.FileSendAsyncCancelled, "SendFileAsync; Write cancelled with error code: {StatusCode}"); private static readonly Action<ILogger, uint, Exception?> _fileSendAsyncErrorIgnored = LoggerMessage.Define<uint>(LogLevel.Debug, LoggerEventIds.FileSendAsyncErrorIgnored, "SendFileAsync; Ignored write exception: {StatusCode}"); public static void FewerBytesThanExpected(ILogger logger) { _fewerBytesThanExpected(logger, null); } public static void WriteError(ILogger logger, IOException exception) { _writeError(logger, exception); } public static void WriteErrorIgnored(ILogger logger, uint statusCode) { _writeErrorIgnored(logger, statusCode, null); } public static void ErrorWhenFlushAsync(ILogger logger, Exception exception) { _errorWhenFlushAsync(logger, exception); } public static void WriteFlushCancelled(ILogger logger, uint statusCode) { _writeFlushCancelled(logger, statusCode, null); } public static void FileSendAsyncError(ILogger logger, Exception exception) { _fileSendAsyncError(logger, exception); } public static void FileSendAsyncCancelled(ILogger logger, uint statusCode) { _fileSendAsyncCancelled(logger, statusCode, null); } public static void FileSendAsyncErrorIgnored(ILogger logger, uint statusCode) { _fileSendAsyncErrorIgnored(logger, statusCode, null); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Diagnostics; namespace System.Net.Mime { /// <summary> /// This stream performs in-place decoding of quoted-printable /// encoded streams. Encoding requires copying into a separate /// buffer as the data being encoded will most likely grow. /// Encoding and decoding is done transparently to the caller. /// /// This stream should only be used for the e-mail content. /// Use QEncodedStream for encoding headers. /// </summary> internal class QuotedPrintableStream : DelegatedStream, IEncodableStream { //should we encode CRLF or not? private bool _encodeCRLF; //number of bytes needed for a soft CRLF in folding private const int SizeOfSoftCRLF = 3; //each encoded byte occupies three bytes when encoded private const int SizeOfEncodedChar = 3; //it takes six bytes to encode a CRLF character (a CRLF that does not indicate folding) private const int SizeOfEncodedCRLF = 6; //if we aren't encoding CRLF then it occupies two chars private const int SizeOfNonEncodedCRLF = 2; private static readonly byte[] s_hexDecodeMap = new byte[] { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 2 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,255,255,255,255,255,255, // 3 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 4 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 5 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 6 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 7 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // F }; private static readonly byte[] s_hexEncodeMap = new byte[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70 }; private int _lineLength; private ReadStateInfo _readState; private WriteStateInfoBase _writeState; /// <summary> /// ctor. /// </summary> /// <param name="stream">Underlying stream</param> /// <param name="lineLength">Preferred maximum line-length for writes</param> internal QuotedPrintableStream(Stream stream, int lineLength) : base(stream) { if (lineLength < 0) { throw new ArgumentOutOfRangeException(nameof(lineLength)); } _lineLength = lineLength; } internal QuotedPrintableStream(Stream stream, bool encodeCRLF) : this(stream, EncodedStreamFactory.DefaultMaxLineLength) { _encodeCRLF = encodeCRLF; } private ReadStateInfo ReadState => _readState ?? (_readState = new ReadStateInfo()); internal WriteStateInfoBase WriteState => _writeState ?? (_writeState = new WriteStateInfoBase(1024, null, null, _lineLength)); public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (offset + count > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } WriteAsyncResult result = new WriteAsyncResult(this, buffer, offset, count, callback, state); result.Write(); return result; } public override void Close() { FlushInternal(); base.Close(); } public unsafe int DecodeBytes(byte[] buffer, int offset, int count) { fixed (byte* pBuffer = buffer) { byte* start = pBuffer + offset; byte* source = start; byte* dest = start; byte* end = start + count; // if the last read ended in a partially decoded // sequence, pick up where we left off. if (ReadState.IsEscaped) { // this will be -1 if the previous read ended // with an escape character. if (ReadState.Byte == -1) { // if we only read one byte from the underlying // stream, we'll need to save the byte and // ask for more. if (count == 1) { ReadState.Byte = *source; return 0; } // '=\r\n' means a soft (aka. invisible) CRLF sequence... if (source[0] != '\r' || source[1] != '\n') { byte b1 = s_hexDecodeMap[source[0]]; byte b2 = s_hexDecodeMap[source[1]]; if (b1 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b1)); if (b2 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b2)); *dest++ = (byte)((b1 << 4) + b2); } source += 2; } else { // '=\r\n' means a soft (aka. invisible) CRLF sequence... if (ReadState.Byte != '\r' || *source != '\n') { byte b1 = s_hexDecodeMap[ReadState.Byte]; byte b2 = s_hexDecodeMap[*source]; if (b1 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b1)); if (b2 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b2)); *dest++ = (byte)((b1 << 4) + b2); } source++; } // reset state for next read. ReadState.IsEscaped = false; ReadState.Byte = -1; } // Here's where most of the decoding takes place. // We'll loop around until we've inspected all the // bytes read. while (source < end) { // if the source is not an escape character, then // just copy as-is. if (*source != '=') { *dest++ = *source++; } else { // determine where we are relative to the end // of the data. If we don't have enough data to // decode the escape sequence, save off what we // have and continue the decoding in the next // read. Otherwise, decode the data and copy // into dest. switch (end - source) { case 2: ReadState.Byte = source[1]; goto case 1; case 1: ReadState.IsEscaped = true; goto EndWhile; default: if (source[1] != '\r' || source[2] != '\n') { byte b1 = s_hexDecodeMap[source[1]]; byte b2 = s_hexDecodeMap[source[2]]; if (b1 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b1)); if (b2 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b2)); *dest++ = (byte)((b1 << 4) + b2); } source += 3; break; } } } EndWhile: return (int)(dest - start); } } public int EncodeBytes(byte[] buffer, int offset, int count) { int cur = offset; for (; cur < count + offset; cur++) { //only fold if we're before a whitespace or if we're at the line limit //add two to the encoded Byte Length to be conservative so that we guarantee that the line length is acceptable if ((_lineLength != -1 && WriteState.CurrentLineLength + SizeOfEncodedChar + 2 >= _lineLength && (buffer[cur] == ' ' || buffer[cur] == '\t' || buffer[cur] == '\r' || buffer[cur] == '\n')) || _writeState.CurrentLineLength + SizeOfEncodedChar + 2 >= EncodedStreamFactory.DefaultMaxLineLength) { if (WriteState.Buffer.Length - WriteState.Length < SizeOfSoftCRLF) { return cur - offset; //ok because folding happens externally } WriteState.Append((byte)'='); WriteState.AppendCRLF(false); } // We don't need to worry about RFC 2821 4.5.2 (encoding first dot on a line), // it is done by the underlying 7BitStream //detect a CRLF in the input and encode it. if (buffer[cur] == '\r' && cur + 1 < count + offset && buffer[cur + 1] == '\n') { if (WriteState.Buffer.Length - WriteState.Length < (_encodeCRLF ? SizeOfEncodedCRLF : SizeOfNonEncodedCRLF)) { return cur - offset; } cur++; if (_encodeCRLF) { // The encoding for CRLF is =0D=0A WriteState.Append((byte)'=', (byte)'0', (byte)'D', (byte)'=', (byte)'0', (byte)'A'); } else { WriteState.AppendCRLF(false); } } //ascii chars less than 32 (control chars) and greater than 126 (non-ascii) are not allowed so we have to encode else if ((buffer[cur] < 32 && buffer[cur] != '\t') || buffer[cur] == '=' || buffer[cur] > 126) { if (WriteState.Buffer.Length - WriteState.Length < SizeOfSoftCRLF) { return cur - offset; } //append an = to indicate an encoded character WriteState.Append((byte)'='); //shift 4 to get the first four bytes only and look up the hex digit WriteState.Append(s_hexEncodeMap[buffer[cur] >> 4]); //clear the first four bytes to get the last four and look up the hex digit WriteState.Append(s_hexEncodeMap[buffer[cur] & 0xF]); } else { if (WriteState.Buffer.Length - WriteState.Length < 1) { return cur - offset; } //detect special case: is whitespace at end of line? we must encode it if it is if ((buffer[cur] == (byte)'\t' || buffer[cur] == (byte)' ') && (cur + 1 >= count + offset)) { if (WriteState.Buffer.Length - WriteState.Length < SizeOfEncodedChar) { return cur - offset; } //append an = to indicate an encoded character WriteState.Append((byte)'='); //shift 4 to get the first four bytes only and look up the hex digit WriteState.Append(s_hexEncodeMap[buffer[cur] >> 4]); //clear the first four bytes to get the last four and look up the hex digit WriteState.Append(s_hexEncodeMap[buffer[cur] & 0xF]); } else { WriteState.Append(buffer[cur]); } } } return cur - offset; } public Stream GetStream() => this; public string GetEncodedString() => Encoding.ASCII.GetString(WriteState.Buffer, 0, WriteState.Length); public override void EndWrite(IAsyncResult asyncResult) => WriteAsyncResult.End(asyncResult); public override void Flush() { FlushInternal(); base.Flush(); } private void FlushInternal() { if (_writeState != null && _writeState.Length > 0) { base.Write(WriteState.Buffer, 0, WriteState.Length); WriteState.BufferFlushed(); } } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (offset + count > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } int written = 0; for (;;) { written += EncodeBytes(buffer, offset + written, count - written); if (written < count) { FlushInternal(); } else { break; } } } private sealed class ReadStateInfo { internal bool IsEscaped { get; set; } internal short Byte { get; set; } = -1; } private sealed class WriteAsyncResult : LazyAsyncResult { private readonly QuotedPrintableStream _parent; private readonly byte[] _buffer; private readonly int _offset; private readonly int _count; private static readonly AsyncCallback s_onWrite = new AsyncCallback(OnWrite); private int _written; internal WriteAsyncResult(QuotedPrintableStream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback) { _parent = parent; _buffer = buffer; _offset = offset; _count = count; } private void CompleteWrite(IAsyncResult result) { _parent.BaseStream.EndWrite(result); _parent.WriteState.BufferFlushed(); } internal static void End(IAsyncResult result) { WriteAsyncResult thisPtr = (WriteAsyncResult)result; thisPtr.InternalWaitForCompletion(); Debug.Assert(thisPtr._written == thisPtr._count); } private static void OnWrite(IAsyncResult result) { if (!result.CompletedSynchronously) { WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState; try { thisPtr.CompleteWrite(result); thisPtr.Write(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } internal void Write() { for (;;) { _written += _parent.EncodeBytes(_buffer, _offset + _written, _count - _written); if (_written < _count) { IAsyncResult result = _parent.BaseStream.BeginWrite(_parent.WriteState.Buffer, 0, _parent.WriteState.Length, s_onWrite, this); if (!result.CompletedSynchronously) break; CompleteWrite(result); } else { InvokeCallback(); break; } } } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Text; using System.Web.Hosting; using System.Web.Mvc; using Commencement.Controllers.Filters; using Commencement.Controllers.Helpers; using Commencement.Controllers.Services; using Commencement.Controllers.ViewModels; using Commencement.Core.Domain; using Commencement.Core.Resources; using Commencement.Mvc; using Commencement.Mvc.ReportDataSets; using Commencement.Mvc.ReportDataSets.CommencementDataSet_MajorCountByCeremonyReportTableAdapters; using Commencement.Mvc.ReportDataSets.CommencementDataSet_RegistrarsReportTableAdapters; using Commencement.Mvc.ReportDataSets.CommencementDataSet_RegistrationMajorMismatchReportTableAdapters; using Commencement.Mvc.ReportDataSets.CommencementDataSet_SpecialNeedsReportTableAdapters; using Commencement.Mvc.ReportDataSets.CommencementDataSet_SummaryReportTableAdapters; using Commencement.Mvc.ReportDataSets.CommencementDataSet_TotalRegisteredByMajorReportTableAdapters; using Commencement.Mvc.ReportDataSets.CommencementDataSet_TotalRegistrationReportTableAdapters; using Commencement.Mvc.ReportDataSets.CommencementDataSet_TotalRegStudentsForTermTableAdapters; using Microsoft.Reporting.WebForms; using Microsoft.WindowsAzure; using UCDArch.Core.PersistanceSupport; using UCDArch.Core.Utils; using UCDArch.Web.ActionResults; namespace Commencement.Controllers { [AnyoneWithRole] public class ReportController : ApplicationController { private readonly IRepositoryWithTypedId<TermCode, string> _termRepository; private readonly IUserService _userService; private readonly ICeremonyService _ceremonyService; private readonly IMajorService _majorService; private readonly IRepository<RegistrationParticipation> _registrationParticipationRepository; private readonly string _serverLocation = CloudConfigurationManager.GetSetting("ReportServer"); public ReportController(IRepositoryWithTypedId<TermCode, string> termRepository, IUserService userService, ICeremonyService ceremonyService, IMajorService majorService, IRepository<RegistrationParticipation> registrationParticipationRepository) { _termRepository = termRepository; _userService = userService; _ceremonyService = ceremonyService; _majorService = majorService; _registrationParticipationRepository = registrationParticipationRepository; } // // GET: /Report/ public ActionResult Index() { var viewModel = ReportViewModel.Create(Repository, _ceremonyService, CurrentUser.Identity.Name); viewModel.MajorCodes = GetMajorsForTerm(TermService.GetCurrent().Id); viewModel.Ceremonies = GetCeremoniesForTerm(TermService.GetCurrent().Id); return View(viewModel); } #region Microsoft Report Server Reports public FileResult GetReport(Report report, string termCode, string majorCode, string ceremony) { Check.Require(!string.IsNullOrEmpty(termCode), "Term code is required."); var name = string.Empty; var parameters = new Dictionary<string, string>(); parameters.Add("term", termCode); if (report != Report.TotalRegStudentsForTerm) { parameters.Add("userId", _userService.GetCurrentUser(CurrentUser).Id.ToString()); } DataTable data = null; ReportDataSource rs = null; switch (report) { case Report.TotalRegisteredStudents: name = "TotalRegistrationReport"; data = new usp_TotalRegisteredStudentsTableAdapter().GetData(parameters["term"], Convert.ToInt32(parameters["userId"])); rs = new ReportDataSource("TotalRegisteredStudents", data); break; case Report.TotalRegStudentsForTerm: name = "TotalRegistrationReportForTerm"; data = new usp_TotalRegisteredStudentsForTermTableAdapter().GetData(parameters["term"]); rs = new ReportDataSource("TotalRegStudentsForTerm", data); break; case Report.TotalRegisteredByMajor: name = "TotalRegistrationByMajorReport"; parameters.Add("major", majorCode); data = new usp_TotalRegisteredByMajorTableAdapter().GetData(parameters["term"], Convert.ToInt32(parameters["userId"]), parameters["major"]); rs = new ReportDataSource("TotalByMajorReport", data); break; //case Report.TotalRegistrationPetitions: // name = "TotalRegistrationPetitions"; // break; case Report.SumOfAllTickets: name = "SummaryReport"; data = new usp_SummaryReportTableAdapter().GetData(parameters["term"], Convert.ToInt32(parameters["userId"])); rs = new ReportDataSource("SumOfAllTickets", data); break; case Report.SpecialNeedsRequest: name = "SpecialNeedsRequest"; data = new usp_SpecialNeedsReportTableAdapter().GetData(parameters["term"], Convert.ToInt32(parameters["userId"])); rs = new ReportDataSource("SpecialNeeds", data); break; case Report.RegistrarsReport: name = "RegistrarReport"; data = new usp_RegistrarReportTableAdapter().GetData(parameters["term"], Convert.ToInt32(parameters["userId"])); rs = new ReportDataSource("RegistrarsReport", data); break; case Report.TicketSignOutSheet: throw new NotImplementedException(); name = "TicketSignOutSheet"; break; case Report.MajorCountByCeremony: name = "MajorCountByCeremony"; parameters.Remove("term"); parameters.Add("ceremonyId", ceremony); data = new usp_MajorCountByCeremonyTableAdapter().GetData(Convert.ToInt32(parameters["ceremonyId"]), Convert.ToInt32(parameters["userId"])); rs = new ReportDataSource("MajorCountByCeremony", data); break; case Report.RegistartionMajorMismatch: name = "RegistrationMajorMismatch"; data = new usp_RegistrationMajorMismatchTableAdapter().GetData(parameters["term"], Convert.ToInt32(parameters["userId"])); rs = new ReportDataSource("RegistrationMajorMismatch", data); break; }; return File(GetLocalReport(rs, name, parameters), "application/excel", string.Format("{0}.xls", name)); //return File(GetReport(string.Format("/commencement/{0}", name), parameters), "application/excel", string.Format("{0}.xls", name)); } private byte[] GetLocalReport(ReportDataSource rs, string reportName, Dictionary<string, string> parameters) { var rview = new ReportViewer(); rview.LocalReport.ReportPath = string.Format("{0}{1}.rdlc", HostingEnvironment.MapPath("~/Reports/"),reportName); rview.ProcessingMode = ProcessingMode.Local; rview.LocalReport.DataSources.Clear(); rview.LocalReport.DataSources.Add(rs); var paramList = new List<ReportParameter>(); if (parameters.Count > 0) { foreach (KeyValuePair<string, string> kvp in parameters) { paramList.Add(new ReportParameter(kvp.Key, kvp.Value)); } } rview.LocalReport.SetParameters(paramList); string mimeType, encoding, extension; string[] streamids; Warning[] warnings; string format = "Excel"; byte[] bytes = rview.LocalReport.Render(format, null, out mimeType, out encoding, out extension, out streamids, out warnings); return bytes; } [Obsolete] private byte[] GetReport(string ReportName, Dictionary<string, string> parameters) { string reportServer = _serverLocation; var rview = new ReportViewer(); rview.ServerReport.ReportServerUrl = new Uri(reportServer); rview.ServerReport.ReportPath = ReportName; var paramList = new List<ReportParameter>(); if (parameters.Count > 0) { foreach (KeyValuePair<string, string> kvp in parameters) { paramList.Add(new ReportParameter(kvp.Key, kvp.Value)); } } rview.ServerReport.SetParameters(paramList); string mimeType, encoding, extension, deviceInfo; string[] streamids; Warning[] warnings; string format = "Excel"; deviceInfo = "<DeviceInfo>" + "<SimplePageHeaders>True</SimplePageHeaders>" + "<HumanReadablePDF>True</HumanReadablePDF>" + // this line disables the compression done by SSRS 2008 so that it can be merged. "</DeviceInfo>"; byte[] bytes = rview.ServerReport.Render(format, deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings); return bytes; } public enum Report { TotalRegisteredStudents=0, TotalRegistrationPetitions , SumOfAllTickets, SpecialNeedsRequest, RegistrarsReport , TicketSignOutSheet, TotalRegisteredByMajor, MajorCountByCeremony, RegistartionMajorMismatch , TotalRegStudentsForTerm } #endregion #region Label Generator public ActionResult GenerateAveryLabels(string termCode, bool printMailing, bool printAll) { var term = _termRepository.GetNullableById(termCode); var query = from a in _registrationParticipationRepository.Queryable where _ceremonyService.GetCeremonies(CurrentUser.Identity.Name, term).Contains(a.Ceremony) && !a.Registration.Student.SjaBlock && a.Registration.MailTickets == printMailing select a; if (!printAll) { query = (IOrderedQueryable<RegistrationParticipation>) query.Where( a => !a.LabelPrinted || (a.ExtraTicketPetition != null && a.ExtraTicketPetition.IsApproved && !a.ExtraTicketPetition.IsPending && !a.ExtraTicketPetition.LabelPrinted)); } query = (IOrderedQueryable<RegistrationParticipation>) query.OrderBy(a => a.Registration.Student.LastName); var registrations = query.ToList(); var doc = GenerateLabelDoc(registrations, printAll); foreach(var r in registrations) { r.LabelPrinted = true; if (r.ExtraTicketPetition != null) r.ExtraTicketPetition.LabelPrinted = true; Repository.OfType<RegistrationParticipation>().EnsurePersistent(r); } ASCIIEncoding encoding = new ASCIIEncoding(); var bytes = encoding.GetBytes(doc); return File(bytes, "application/word", "labels.doc"); } private string GenerateLabelDoc(List<RegistrationParticipation> registrations, bool printAll) { var labels = new StringBuilder(); var rows = GenerateRows(registrations, printAll); foreach (var r in rows) { // put all 3 cells into a row labels.Append(string.Format(Labels.Avery5160_LabelRow, r.GetCell1, r.GetCell2, r.GetCell3)); } var doc = string.Format(Labels.Avery5160_Doc, labels); doc = doc.Replace("&", "&amp;"); return doc; } // create a list of the data broken down into rows private List<LabelRow> GenerateRows(List<RegistrationParticipation> registrations, bool printAll) { var rows = new List<LabelRow>(); var row = new LabelRow(); foreach (var rp in registrations) { // if no space is avaible add it to the list if (!row.HasSpace()) { rows.Add(row); row = new LabelRow(); } // calculate the number of tickets var tickets = !rp.LabelPrinted || printAll ? rp.NumberTickets : 0; // figure out if we need to print original ticket count // calculate any extra tickets tickets += rp.ExtraTicketPetition != null && !rp.ExtraTicketPetition.IsPending && rp.ExtraTicketPetition.IsApproved && (!rp.ExtraTicketPetition.LabelPrinted || printAll) ? rp.ExtraTicketPetition.NumberTickets.Value : 0; // calculate streaming var streaming = rp.ExtraTicketPetition != null && rp.ExtraTicketPetition.IsApprovedCompletely ? rp.ExtraTicketPetition.NumberTicketsStreaming : 0; var ticketString = string.Format("{0}-{1}", tickets, streaming); if (tickets > 0) { string cell = string.Empty; if (rp.TicketDistributionMethod != null && rp.TicketDistributionMethod.Id == StaticIndexes.Td_Mail) { var address2 = string.IsNullOrEmpty(rp.Registration.Address2) ? string.Empty : string.Format(Labels.Avergy5160_Mail_Address2, rp.Registration.Address2); cell = string.Format(Labels.Avery5160_MailCell, rp.Registration.Student.FullName, rp.Registration.Address1, address2, rp.Registration.City + ", " + rp.Registration.State.Id + " " + rp.Registration.Zip , rp.Registration.RegistrationParticipations[0].Ceremony.DateTime.ToString("t") + "-" + ticketString); } else if(rp.TicketDistributionMethod != null && rp.TicketDistributionMethod.Id == StaticIndexes.Td_Pickup) { cell = string.Format(Labels.Avery5160_PickupCell, rp.Registration.Student.FullName, rp.Registration.Student.StudentId, string.Format("{0} ({1})", rp.Registration.RegistrationParticipations[0].Major.Id, rp.Registration.RegistrationParticipations[0].Major.College.Id) , rp.Ceremony.DateTime.ToString("t") + "-" + ticketString); } row.AddCell(cell); } } rows.Add(row); return rows; } #endregion public ActionResult RegistrationData() { var viewModel = RegistrationDataViewModel.Create(Repository, _ceremonyService, CurrentUser.Identity.Name, TermService.GetCurrent()); return View(viewModel); } public ActionResult Honors() { var viewModel = new HonorsPostModel(); viewModel.TermCode = TermService.GetCurrent().Id; viewModel.Colleges = Repository.OfType<College>().Queryable.Where(a => a.Display).ToList(); viewModel.HonorsReports = Repository.OfType<HonorsReport>().Queryable.Where(a => a.User.LoginId == User.Identity.Name).ToList(); return View(viewModel); } [HttpPost] public ActionResult Honors(HonorsPostModel honorsPostModel) { if (honorsPostModel.Validate()) { ReportRequestHandler.ExecuteReportRequest(Repository, honorsPostModel, User.Identity.Name); //Message = "Request has been submitted, you will receive an email when it is ready."; Message = "Request has been submitted, Check back in a few minutes to see if it is ready."; } honorsPostModel.Colleges = Repository.OfType<College>().Queryable.Where(a => a.Display).ToList(); honorsPostModel.HonorsReports = Repository.OfType<HonorsReport>().Queryable.Where(a => a.User.LoginId == User.Identity.Name).ToList(); return View(honorsPostModel); } public FileResult DownloadHonors(int id) { var hr = Repository.OfType<HonorsReport>().GetNullableById(id); return File(hr.Contents, "application/excel", string.Format("{0}-Honors{1}.xls", hr.TermCode, hr.College.Id)); } public JsonNetResult LoadMajorsForTerm(string term) { var majors = GetMajorsForTerm(term); return new JsonNetResult(majors.Select(a => new { a.Id, Name = a.MajorName })); } private List<MajorCode> GetMajorsForTerm(string term) { var termCode = _termRepository.GetNullableById(term); var ceremonies = _ceremonyService.GetCeremonies(CurrentUser.Identity.Name, termCode); var majors = ceremonies.SelectMany(a => a.Majors).Where(a => a.ConsolidationMajor == null).ToList(); return majors; } public JsonNetResult LoadCeremoniesForTerm(string term) { var ceremonies = GetCeremoniesForTerm(term); return new JsonNetResult(ceremonies.Select(a => new {a.Id, Name=a.CeremonyName}).ToList()); } private List<Ceremony> GetCeremoniesForTerm(string term) { var termCode = _termRepository.GetNullableById(term); var ceremonies = _ceremonyService.GetCeremonies(CurrentUser.Identity.Name, termCode); return ceremonies; } public JsonNetResult GetCutOffs(int term, string college) { var cutoffs = Repository.OfType<HonorsCutoff>() .Queryable.Where(a => a.College == college && (a.StartTerm <= term && a.EndTerm >= term)) .OrderBy(a => a.MinUnits) .ToList(); var result = new HonorsCutoffModel(); if (cutoffs.Count != 3) return new JsonNetResult(result); if (college == "LS") { result.Tier1Honors = cutoffs[0].HonorsGpa; result.Tier2Honors = cutoffs[1].HonorsGpa; result.Tier3Honors = cutoffs[2].HonorsGpa; } else { result.Tier1Honors = cutoffs[0].HonorsGpa; result.Tier1HighHonors = cutoffs[0].HighHonorsGpa; result.Tier1HighestHonors = cutoffs[0].HighestHonorsGpa; result.Tier2Honors = cutoffs[1].HonorsGpa; result.Tier2HighHonors = cutoffs[1].HighHonorsGpa; result.Tier2HighestHonors = cutoffs[1].HighestHonorsGpa; result.Tier3Honors = cutoffs[2].HonorsGpa; result.Tier3HighHonors = cutoffs[2].HighHonorsGpa; result.Tier3HighestHonors = cutoffs[2].HighestHonorsGpa; } return new JsonNetResult(result); } } public class LabelRow { public LabelRow() { Cell1 = string.Empty; Cell2 = string.Empty; Cell3 = string.Empty; } public bool HasSpace() { return string.IsNullOrEmpty(Cell1) || string.IsNullOrEmpty(Cell2) || string.IsNullOrEmpty(Cell3); } public bool IsEmpty() { return string.IsNullOrEmpty(Cell1) && string.IsNullOrEmpty(Cell2) && string.IsNullOrEmpty(Cell3); } public bool AddCell(string contents) { if (string.IsNullOrEmpty(Cell1)) { Cell1 = contents; return true; } if (string.IsNullOrEmpty(Cell2)) { Cell2 = contents; return true; } if (string.IsNullOrEmpty(Cell3)) { Cell3 = contents; return true; } return false; } public string GetCell1 { get { return string.IsNullOrEmpty(Cell1) ? Labels.Avery5160_EmptyCell : Cell1; }} public string GetCell2 { get { return string.IsNullOrEmpty(Cell2) ? Labels.Avery5160_EmptyCell : Cell2; } } public string GetCell3 { get { return string.IsNullOrEmpty(Cell3) ? Labels.Avery5160_EmptyCell : Cell3; } } public string Cell1 { get; set; } public string Cell2 { get; set; } public string Cell3 { get; set; } } public class HonorsPostModel { public HonorsPostModel() { HonorsReports = new List<HonorsReport>(); } public College College { get; set; } public string TermCode { get; set; } public decimal Honors4590 { get; set; } public decimal? HighHonors4590 { get; set; } public decimal? HighestHonors4590 { get; set; } public decimal Honors90135 { get; set; } public decimal? HighHonors90135 { get; set; } public decimal? HighestHonors90135 { get; set; } public decimal Honors135 { get; set; } public decimal? HighHonors135 { get; set; } public decimal? HighestHonors135 { get; set; } public IEnumerable<HonorsReport> HonorsReports { get; set; } public IEnumerable<College> Colleges { get; set; } public bool Validate() { if (College == null) return false; if (Honors4590 == 0 || Honors90135 == 0 || Honors135 == 0) return false; if (College.Id != "LS") { return HighHonors4590.HasValue && HighestHonors4590.HasValue && HighHonors90135.HasValue && HighestHonors90135.HasValue && HighHonors135.HasValue && HighestHonors135.HasValue; } return true; } public HonorsReport Convert() { var hr = new HonorsReport(); hr.College = College; hr.TermCode = TermCode; hr.Honors4590 = Honors4590; hr.HighHonors4590 = HighHonors4590; hr.HighestHonors4590 = HighestHonors4590; hr.Honors90135 = Honors90135; hr.HighHonors90135 = HighHonors90135; hr.HighestHonors90135 = HighestHonors90135; hr.Honors135 = Honors135; hr.HighHonors135 = HighHonors135; hr.HighestHonors135 = HighestHonors135; return hr; } } public class HonorsCutoffModel { public decimal Tier1Honors { get; set; } public decimal Tier1HighHonors { get; set; } public decimal Tier1HighestHonors { get; set; } public decimal Tier2Honors { get; set; } public decimal Tier2HighHonors { get; set; } public decimal Tier2HighestHonors { get; set; } public decimal Tier3Honors { get; set; } public decimal Tier3HighHonors { get; set; } public decimal Tier3HighestHonors { get; set; } } }
using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using AllReady.Areas.Admin.Controllers; using AllReady.Areas.Admin.Features.Campaigns; using AllReady.Models; using AllReady.Services; using AllReady.UnitTest.Extensions; using MediatR; using Microsoft.AspNetCore.Http; using Moq; using Xunit; using Microsoft.AspNetCore.Mvc; using System.Linq; using System; using AllReady.Extensions; using System.ComponentModel.DataAnnotations; using System.Reflection; using AllReady.Areas.Admin.ViewModels.Campaign; using AllReady.Areas.Admin.ViewModels.Organization; using AllReady.Areas.Admin.ViewModels.Shared; namespace AllReady.UnitTest.Areas.Admin.Controllers { public class CampaignAdminControllerTests { [Fact] public void IndexSendsCampaignListQueryWithCorrectDataWhenUserIsOrgAdmin() { const int organizationId = 99; var mockMediator = new Mock<IMediator>(); var controller = new CampaignController(mockMediator.Object, null); controller.MakeUserAnOrgAdmin(organizationId.ToString()); controller.Index(); mockMediator.Verify(mock => mock.Send(It.Is<CampaignListQuery>(q => q.OrganizationId == organizationId))); } [Fact] public void IndexSendsCampaignListQueryWithCorrectDataWhenUserIsNotOrgAdmin() { var mockMediator = new Mock<IMediator>(); var controller = new CampaignController(mockMediator.Object, null); var claims = new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()), }; controller.SetClaims(claims); controller.Index(); mockMediator.Verify(mock => mock.Send(It.Is<CampaignListQuery>(q => q.OrganizationId == null))); } [Fact] public void IndexReturnsCorrectViewModel() { IndexReturnsCorrectDataWhenUserIsOrgAdmin(); IndexReturnsCorrectDataWhenUserIsNotOrgAdmin(); } private static void IndexReturnsCorrectDataWhenUserIsOrgAdmin() { const int organizationId = 99; var mockMediator = new Mock<IMediator>(); mockMediator.Setup(x => x.Send(It.Is<CampaignListQuery>(c => c.OrganizationId == organizationId))) .Returns((CampaignListQuery q) => { var ret = new List<CampaignSummaryViewModel> { new CampaignSummaryViewModel { OrganizationId = organizationId } }; return ret; } ); var controller = new CampaignController(mockMediator.Object, null); controller.MakeUserAnOrgAdmin(organizationId.ToString()); var view = (ViewResult)controller.Index(); mockMediator.Verify(mock => mock.Send(It.Is<CampaignListQuery>(c => c.OrganizationId == organizationId))); // Org admin should only see own campaigns var viewModel = (IEnumerable<CampaignSummaryViewModel>)view.ViewData.Model; Assert.NotNull(viewModel); Assert.Equal(viewModel.Count(), 1); Assert.Equal(viewModel.First().OrganizationId, organizationId); } private void IndexReturnsCorrectDataWhenUserIsNotOrgAdmin() { const int organizationId = 99; var mockMediator = new Mock<IMediator>(); mockMediator.Setup(x => x.Send(It.Is<CampaignListQuery>(c => c.OrganizationId == null))) .Returns((CampaignListQuery q) => { // return some models var ret = new List<CampaignSummaryViewModel> { new CampaignSummaryViewModel { OrganizationId = organizationId }, new CampaignSummaryViewModel { OrganizationId = organizationId + 1 } }; return ret; } ); var controller = new CampaignController(mockMediator.Object, null); var claims = new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, UserType.SiteAdmin.ToString()), }; controller.SetClaims(claims); // All campaigns returned when not OrgAdmin var view = (ViewResult)controller.Index(); // verify the fetch was called mockMediator.Verify(mock => mock.Send(It.Is<CampaignListQuery>(c => c.OrganizationId == null))); // Site admin should only see all campaigns var viewModel = (IEnumerable<CampaignSummaryViewModel>)view.ViewData.Model; Assert.NotNull(viewModel); Assert.Equal(viewModel.Count(), 2); } [Fact] public async Task DetailsSendsCampaignDetailQueryWithCorrectCampaignId() { var CAMPAIGN_ID = 100; var ORGANIZATION_ID = 99; var mockMediator = new Mock<IMediator>(); // model is not null mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c => c.CampaignId == CAMPAIGN_ID))).ReturnsAsync(new CampaignDetailViewModel { OrganizationId = ORGANIZATION_ID, Id = CAMPAIGN_ID }).Verifiable(); var controller = new CampaignController(mockMediator.Object, null); controller.SetClaims(new List<Claim>()); // create a User for the controller var view = await controller.Details(CAMPAIGN_ID); mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c => c.CampaignId == CAMPAIGN_ID))); } [Fact] public async Task DetailsReturnsHttpNotFoundResultWhenVieModelIsNull() { CampaignController controller; MockMediatorCampaignDetailQuery(out controller); Assert.IsType<NotFoundResult>(await controller.Details(It.IsAny<int>())); } [Fact] public async Task DetailsReturnsHttpUnauthorizedResultIfUserIsNotOrgAdmin() { var controller = CampaignControllerWithDetailQuery(UserType.BasicUser.ToString(), It.IsAny<int>()); Assert.IsType<UnauthorizedResult>(await controller.Details(It.IsAny<int>())); } [Fact] public async Task DetailsReturnsCorrectViewWhenViewModelIsNotNullAndUserIsOrgAdmin() { var controller = CampaignControllerWithDetailQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>()); Assert.IsType<ViewResult>(await controller.Details(It.IsAny<int>())); } [Fact] public async Task DetailsReturnsCorrectViewModelWhenViewModelIsNotNullAndUserIsOrgAdmin() { const int campaignId = 100; const int organizationId = 99; var mockMediator = new Mock<IMediator>(); // model is not null mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c=>c.CampaignId == campaignId))).ReturnsAsync(new CampaignDetailViewModel { OrganizationId = organizationId, Id = campaignId }).Verifiable(); // user is org admin var controller = new CampaignController(mockMediator.Object, null); controller.MakeUserAnOrgAdmin(organizationId.ToString()); var view = (ViewResult)(await controller.Details(campaignId)); var viewModel = (CampaignDetailViewModel)view.ViewData.Model; Assert.Equal(viewModel.Id, campaignId); Assert.Equal(viewModel.OrganizationId, organizationId); } [Fact] public void CreateReturnsCorrectViewWithCorrectViewModel() { var mockMediator = new Mock<IMediator>(); var controller = new CampaignController(mockMediator.Object, null); var view = (ViewResult) controller.Create(); var viewModel = (CampaignSummaryViewModel)view.ViewData.Model; Assert.Equal(view.ViewName, "Edit"); Assert.NotNull(viewModel); } [Fact] public async Task EditGetSendsCampaignSummaryQueryWithCorrectCampaignId() { var CAMPAIGN_ID = 100; var mockMediator = new Mock<IMediator>(); // model is not null mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == CAMPAIGN_ID))).ReturnsAsync(new CampaignSummaryViewModel { Id = CAMPAIGN_ID }); var controller = new CampaignController(mockMediator.Object, null); controller.SetClaims(new List<Claim>()); // create a User for the controller var view = await controller.Edit(CAMPAIGN_ID); mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == CAMPAIGN_ID))); } [Fact] public async Task EditGetReturnsHttpNotFoundResultWhenViewModelIsNull() { CampaignController controller; MockMediatorCampaignSummaryQuery(out controller); Assert.IsType<NotFoundResult>(await controller.Edit(It.IsAny<int>())); } [Fact] public async Task EditGetReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin() { var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>()); Assert.IsType<UnauthorizedResult>(await controller.Edit(It.IsAny<int>())); } [Fact] public async Task EditGetReturnsCorrectViewModelWhenUserIsOrgAdmin() { var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>()); Assert.IsType<ViewResult>(await controller.Edit(It.IsAny<int>())); } [Fact] public async Task EditPostReturnsBadRequestWhenCampaignIsNull() { var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>()); var result = await controller.Edit(null, null); Assert.IsType<BadRequestResult>(result); } [Fact] public async Task EditPostAddsCorrectKeyAndErrorMessageToModelStateWhenCampaignEndDateIsLessThanCampainStartDate() { var campaignSummaryModel = new CampaignSummaryViewModel { OrganizationId = 1, StartDate = DateTime.Now.AddDays(1), EndDate = DateTime.Now.AddDays(-1)}; var sut = new CampaignController(null, null); sut.MakeUserAnOrgAdmin(campaignSummaryModel.OrganizationId.ToString()); await sut.Edit(campaignSummaryModel, null); var modelStateErrorCollection = sut.ModelState.GetErrorMessagesByKey(nameof(CampaignSummaryViewModel.EndDate)); Assert.Equal(modelStateErrorCollection.Single().ErrorMessage, "The end date must fall on or after the start date."); } [Fact] public async Task EditPostInsertsCampaign() { var OrganizationId = 99; var NewCampaignId = 100; var mockMediator = new Mock<IMediator>(); mockMediator.Setup(x => x.SendAsync(It.IsAny<EditCampaignCommand>())) .Returns((EditCampaignCommand q) => Task.FromResult<int>(NewCampaignId) ); var mockImageService = new Mock<IImageService>(); var controller = new CampaignController(mockMediator.Object, mockImageService.Object); controller.MakeUserAnOrgAdmin(OrganizationId.ToString()); var model = MassiveTrafficLightOutage_model; model.OrganizationId = OrganizationId; // verify the model is valid var validationContext = new ValidationContext(model, null, null); var validationResults = new List<ValidationResult>(); Validator.TryValidateObject(model, validationContext, validationResults); Assert.Equal(0, validationResults.Count()); var file = FormFile("image/jpeg"); var view = (RedirectToActionResult) await controller.Edit(model, file); // verify the edit(add) is called mockMediator.Verify(mock => mock.SendAsync(It.Is<EditCampaignCommand>(c => c.Campaign.OrganizationId == OrganizationId))); // verify that the next route Assert.Equal(view.RouteValues["area"], "Admin"); Assert.Equal(view.RouteValues["id"], NewCampaignId); } [Fact] public async Task EditPostReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin() { var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>()); var result = await controller.Edit(new CampaignSummaryViewModel { OrganizationId = It.IsAny<int>() }, null); Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task EditPostRedirectsToCorrectActionWithCorrectRouteValuesWhenModelStateIsValid() { var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>()); var result = await controller.Edit(new CampaignSummaryViewModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, null); //TODO: test result for correct Action name and Route values Assert.IsType<RedirectToActionResult>(result); } [Fact] public async Task EditPostAddsErrorToModelStateWhenInvalidImageFormatIsSupplied() { var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>()); var file = FormFile(""); await controller.Edit(new CampaignSummaryViewModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, file); Assert.False(controller.ModelState.IsValid); Assert.True(controller.ModelState.ContainsKey("ImageUrl")); //TODO: test that the value associated with the key is correct } [Fact] public async Task EditPostReturnsCorrectViewModelWhenInvalidImageFormatIsSupplied() { const int organizationId = 100; var mockMediator = new Mock<IMediator>(); var mockImageService = new Mock<IImageService>(); var sut = new CampaignController(mockMediator.Object, mockImageService.Object); sut.MakeUserAnOrgAdmin(organizationId.ToString()); var file = FormFile("audio/mpeg3"); var model = MassiveTrafficLightOutage_model; model.OrganizationId = organizationId; var view = (ViewResult)(await sut.Edit(model, file)); var viewModel = (CampaignSummaryViewModel)view.ViewData.Model; Assert.True(Object.ReferenceEquals(model, viewModel)); } [Fact] public async Task EditPostUploadsImageToImageService() { const int organizationId = 1; const int campaignId = 100; var mockMediator = new Mock<IMediator>(); var mockImageService = new Mock<IImageService>(); var sut = new CampaignController(mockMediator.Object, mockImageService.Object); sut.MakeUserAnOrgAdmin(organizationId.ToString()); var file = FormFile("image/jpeg"); await sut.Edit(new CampaignSummaryViewModel { Name = "Foo", OrganizationId = organizationId, Id = campaignId}, file); mockImageService.Verify(mock => mock.UploadCampaignImageAsync( It.Is<int>(i => i == organizationId), It.Is<int>(i => i == campaignId), It.Is<IFormFile>(i => i == file)), Times.Once); } [Fact] public void EditPostHasHttpPostAttribute() { var attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.Edit), new Type[] { typeof(CampaignSummaryViewModel), typeof(IFormFile) }).GetCustomAttribute(typeof(HttpPostAttribute)); Assert.NotNull(attr); } [Fact] public void EditPostHasValidateAntiForgeryTokenttribute() { var attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.Edit), new Type[] { typeof(CampaignSummaryViewModel), typeof(IFormFile) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute)); Assert.NotNull(attr); } [Fact] public async Task DeleteSendsCampaignSummaryQueryWithCorrectCampaignId() { var ORGANIZATION_ID = 99; var CAMPAIGN_ID = 100; var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == CAMPAIGN_ID))).ReturnsAsync(new CampaignSummaryViewModel { Id = CAMPAIGN_ID, OrganizationId = ORGANIZATION_ID }); var controller = new CampaignController(mockMediator.Object, null); controller.SetClaims(new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()), new Claim(AllReady.Security.ClaimTypes.Organization, ORGANIZATION_ID.ToString()) }); var view = (ViewResult)(await controller.Delete(CAMPAIGN_ID)); mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == CAMPAIGN_ID)), Times.Once); } [Fact] public async Task DeleteReturnsHttpNotFoundResultWhenCampaignIsNotFound() { CampaignController controller; MockMediatorCampaignSummaryQuery(out controller); Assert.IsType<NotFoundResult>(await controller.Delete(It.IsAny<int>())); } [Fact] public async Task DeleteReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin() { var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>()); Assert.IsType<UnauthorizedResult>(await controller.Delete(It.IsAny<int>())); } [Fact] public async Task DeleteReturnsCorrectViewWhenUserIsOrgAdmin() { var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>()); Assert.IsType<ViewResult>(await controller.Delete(It.IsAny<int>())); } [Fact] public async Task DeleteReturnsCorrectViewModelWhenUserIsOrgAdmin() { const int organizationId = 99; const int campaignId = 100; var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == campaignId))).ReturnsAsync(new CampaignSummaryViewModel { Id = campaignId, OrganizationId = organizationId }); var controller = new CampaignController(mockMediator.Object, null); controller.MakeUserAnOrgAdmin(organizationId.ToString()); var view = (ViewResult)await controller.Delete(campaignId); var viewModel = (CampaignSummaryViewModel)view.ViewData.Model; Assert.Equal(viewModel.Id, campaignId); } public async Task DeleteConfirmedSendsCampaignSummaryQueryWithCorrectCampaignId() { const int campaignId = 1; var mediator = new Mock<IMediator>(); var sut = new CampaignController(mediator.Object, null); await sut.DeleteConfirmed(campaignId); mediator.Verify(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(i => i.CampaignId == campaignId)), Times.Once); } [Fact] public async Task DetailConfirmedReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin() { var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>()); Assert.IsType<UnauthorizedResult>(await controller.DeleteConfirmed(It.IsAny<int>())); } [Fact] public async Task DetailConfirmedSendsDeleteCampaignCommandWithCorrectCampaignIdWhenUserIsOrgAdmin() { const int organizationId = 1; const int campaignId = 100; var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(new CampaignSummaryViewModel { OrganizationId = organizationId }); var sut = new CampaignController(mockMediator.Object, null); sut.MakeUserAnOrgAdmin(organizationId.ToString()); await sut.DeleteConfirmed(campaignId); mockMediator.Verify(mock => mock.SendAsync(It.Is<DeleteCampaignCommand>(i => i.CampaignId == campaignId)), Times.Once); } [Fact] public async Task DetailConfirmedRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsOrgAdmin() { const int organizationId = 1; const int campaignId = 100; var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(new CampaignSummaryViewModel { OrganizationId = organizationId }); var sut = new CampaignController(mockMediator.Object, null); sut.MakeUserAnOrgAdmin(organizationId.ToString()); var routeValues = new Dictionary<string, object> { ["area"] = "Admin" }; var result = await sut.DeleteConfirmed(campaignId) as RedirectToActionResult; Assert.Equal(result.ActionName, nameof(CampaignController.Index)); Assert.Equal(result.RouteValues, routeValues); } [Fact] public void DeleteConfirmedHasHttpPostAttribute() { var attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.DeleteConfirmed), new Type[] { typeof(int) }).GetCustomAttribute(typeof(HttpPostAttribute)); Assert.NotNull(attr); } [Fact] public void DeleteConfirmedHasActionNameAttributeWithCorrectName() { var attr = (ActionNameAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.DeleteConfirmed), new Type[] { typeof(int) }).GetCustomAttribute(typeof(ActionNameAttribute)); Assert.Equal(attr.Name, "Delete"); } [Fact] public void DeleteConfirmedHasValidateAntiForgeryTokenAttribute() { var attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.DeleteConfirmed), new Type[] { typeof(int) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute)); Assert.NotNull(attr); } [Fact] public async Task LockUnlockReturnsHttpUnauthorizedResultWhenUserIsNotSiteAdmin() { var controller = new CampaignController(null, null); controller.SetClaims(new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()) }); Assert.IsType<UnauthorizedResult>(await controller.LockUnlock(100)); } [Fact] public async Task LockUnlockSendsLockUnlockCampaignCommandWithCorrectCampaignIdWhenUserIsSiteAdmin() { var CAMPAIGN_ID = 99; var mockMediator = new Mock<IMediator>(); var controller = new CampaignController(mockMediator.Object, null); var claims = new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, UserType.SiteAdmin.ToString()) }; controller.SetClaims(claims); await controller.LockUnlock(CAMPAIGN_ID); mockMediator.Verify(mock => mock.SendAsync(It.Is<LockUnlockCampaignCommand>(q => q.CampaignId == CAMPAIGN_ID)), Times.Once); } [Fact] public async Task LockUnlockRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsSiteAdmin() { var CAMPAIGN_ID = 100; var mockMediator = new Mock<IMediator>(); var controller = new CampaignController(mockMediator.Object, null); var claims = new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, UserType.SiteAdmin.ToString()), }; controller.SetClaims(claims); var view = (RedirectToActionResult)await controller.LockUnlock(CAMPAIGN_ID); // verify the next route Assert.Equal(view.ActionName, nameof(CampaignController.Details)); Assert.Equal(view.RouteValues["area"], "Admin"); Assert.Equal(view.RouteValues["id"], CAMPAIGN_ID); } [Fact] public void LockUnlockHasHttpPostAttribute() { var attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.LockUnlock), new Type[] { typeof(int) }).GetCustomAttribute(typeof(HttpPostAttribute)); Assert.NotNull(attr); } [Fact] public void LockUnlockdHasValidateAntiForgeryTokenAttribute() { var attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.LockUnlock), new Type[] { typeof(int) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute)); Assert.NotNull(attr); } #region Helper Methods private static Mock<IMediator> MockMediatorCampaignDetailQuery(out CampaignController controller) { var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(null).Verifiable(); controller = new CampaignController(mockMediator.Object, null); return mockMediator; } private static Mock<IMediator> MockMediatorCampaignSummaryQuery(out CampaignController controller) { var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(null).Verifiable(); controller = new CampaignController(mockMediator.Object, null); return mockMediator; } private static CampaignController CampaignControllerWithDetailQuery(string userType, int organizationId) { var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(new CampaignDetailViewModel { OrganizationId = organizationId }).Verifiable(); var controller = new CampaignController(mockMediator.Object, null); controller.SetClaims(new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, userType), new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString()) }); return controller; } private static CampaignController CampaignControllerWithSummaryQuery(string userType, int organizationId) { var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())) .ReturnsAsync(new CampaignSummaryViewModel { OrganizationId = organizationId, Location = new LocationEditViewModel() }).Verifiable(); var mockImageService = new Mock<IImageService>(); var controller = new CampaignController(mockMediator.Object, mockImageService.Object); controller.SetClaims(new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, userType), new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString()) }); return controller; } private static IFormFile FormFile(string fileType) { var mockFormFile = new Mock<IFormFile>(); mockFormFile.Setup(mock => mock.ContentType).Returns(fileType); return mockFormFile.Object; } #endregion #region "Test Models" public static LocationEditViewModel BogusAve_model { get { return new LocationEditViewModel() { Address1 = "25 Bogus Ave", City = "Agincourt", State = "Ontario", Country = "Canada", PostalCode = "M1T2T9" }; } } public static OrganizationEditViewModel AgincourtAware_model { get { return new OrganizationEditViewModel() { Name = "Agincourt Awareness", Location = BogusAve_model, WebUrl = "http://www.AgincourtAwareness.ca", LogoUrl = "http://www.AgincourtAwareness.ca/assets/LogoLarge.png" }; } } public static CampaignSummaryViewModel MassiveTrafficLightOutage_model { get { return new CampaignSummaryViewModel() { Description = "Preparations to be ready to deal with a wide-area traffic outage.", EndDate = DateTime.Today.AddMonths(1), ExternalUrl = "http://agincourtaware.trafficlightoutage.com", ExternalUrlText = "Agincourt Aware: Traffic Light Outage", Featured = false, FileUpload = null, FullDescription = "<h1><strong>Massive Traffic Light Outage Plan</strong></h1>\r\n<p>The Massive Traffic Light Outage Plan (MTLOP) is the official plan to handle a major traffic light failure.</p>\r\n<p>In the event of a wide-area traffic light outage, an alternative method of controlling traffic flow will be necessary. The MTLOP calls for the recruitment and training of volunteers to be ready to direct traffic at designated intersections and to schedule and follow-up with volunteers in the event of an outage.</p>", Id = 0, ImageUrl = null, Location = BogusAve_model, Locked = false, Name = "Massive Traffic Light Outage Plan", PrimaryContactEmail = "mlong@agincourtawareness.com", PrimaryContactFirstName = "Miles", PrimaryContactLastName = "Long", PrimaryContactPhoneNumber = "416-555-0119", StartDate = DateTime.Today, TimeZoneId = "Eastern Standard Time", }; } } #endregion } }
//--------------------------------------------------------------------------- // // <copyright file="WindowProviderWrapper.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Window pattern provider wrapper for WCP // // History: // 07/21/2003 : BrendanM Ported to WCP // //--------------------------------------------------------------------------- using System; using System.Windows.Threading; using System.Windows.Media; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Windows.Automation.Peers; namespace MS.Internal.Automation { // Automation/WCP Wrapper class: Implements that UIAutomation I...Provider // interface, and calls through to a WCP AutomationPeer which implements the corresponding // I...Provider inteface. Marshalls the call from the RPC thread onto the // target AutomationPeer's context. // // Class has two major parts to it: // * Implementation of the I...Provider, which uses Dispatcher.Invoke // to call a private method (lives in second half of the class) via a delegate, // if necessary, packages any params into an object param. Return type of Invoke // must be cast from object to appropriate type. // * private methods - one for each interface entry point - which get called back // on the right context. These call through to the peer that's actually // implenting the I...Provider version of the interface. internal class WindowProviderWrapper: MarshalByRefObject, IWindowProvider { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors private WindowProviderWrapper( AutomationPeer peer, IWindowProvider iface) { _peer = peer; _iface = iface; } #endregion Constructors //------------------------------------------------------ // // Interface IWindowProvider // //------------------------------------------------------ #region Interface IWindowProvider public void SetVisualState( WindowVisualState state ) { ElementUtil.Invoke( _peer, new DispatcherOperationCallback( SetVisualState ), state ); } public void Close() { ElementUtil.Invoke( _peer, new DispatcherOperationCallback( Close ), null ); } public bool WaitForInputIdle( int milliseconds ) { return (bool)ElementUtil.Invoke( _peer, new DispatcherOperationCallback( WaitForInputIdle ), milliseconds ); } public bool Maximizable { get { return (bool) ElementUtil.Invoke( _peer, new DispatcherOperationCallback( GetMaximizable ), null ); } } public bool Minimizable { get { return (bool) ElementUtil.Invoke( _peer, new DispatcherOperationCallback( GetMinimizable ), null ); } } public bool IsModal { get { return (bool) ElementUtil.Invoke( _peer, new DispatcherOperationCallback( GetIsModal ), null ); } } public WindowVisualState VisualState { get { return (WindowVisualState) ElementUtil.Invoke( _peer, new DispatcherOperationCallback( GetVisualState ), null ); } } public WindowInteractionState InteractionState { get { return (WindowInteractionState) ElementUtil.Invoke( _peer, new DispatcherOperationCallback( GetInteractionState ), null ); } } public bool IsTopmost { get { return (bool) ElementUtil.Invoke( _peer, new DispatcherOperationCallback( GetIsTopmost ), null ); } } #endregion Interface IWindowProvider //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal static object Wrap( AutomationPeer peer, object iface) { return new WindowProviderWrapper( peer, (IWindowProvider) iface ); } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods private object SetVisualState( object arg ) { _iface.SetVisualState( (WindowVisualState) arg ); return null; } private object WaitForInputIdle( object arg ) { return _iface.WaitForInputIdle( (int) arg ); } private object Close( object unused ) { _iface.Close(); return null; } private object GetMaximizable( object unused ) { return _iface.Maximizable; } private object GetMinimizable( object unused ) { return _iface.Minimizable; } private object GetIsModal( object unused ) { return _iface.IsModal; } private object GetVisualState( object unused ) { return _iface.VisualState; } private object GetInteractionState( object unused ) { return _iface.InteractionState; } private object GetIsTopmost( object unused ) { return _iface.IsTopmost; } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private AutomationPeer _peer; private IWindowProvider _iface; #endregion Private Fields } }
namespace NodesMapEditor { partial class EditForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditForm)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem10 = new System.Windows.Forms.ToolStripMenuItem(); this.actionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.generateFullMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.generateMazeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.randomizeIntegerPositionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.generateFloatPositionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.refreshRToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator(); this.colorThePathToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.nodeColorNToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pathNodeColorPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.selectedNodeColorSToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.lineColorLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.selectBoxColorBToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.lineWidthSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pictureBoxToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.saveToolStripButton = new System.Windows.Forms.ToolStripButton(); this.openToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.pointerToolStripButton = new System.Windows.Forms.ToolStripButton(); this.nodeToolStripButton = new System.Windows.Forms.ToolStripButton(); this.connectionToolStripButton = new System.Windows.Forms.ToolStripButton(); this.doubleConnectionToolStripButton = new System.Windows.Forms.ToolStripButton(); this.eraserToolStripButton = new System.Windows.Forms.ToolStripButton(); this.clearToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.startPositionToolStripButton = new System.Windows.Forms.ToolStripButton(); this.endPositionToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripLabel4 = new System.Windows.Forms.ToolStripLabel(); this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); this.blockSizeToolStripTextBox = new System.Windows.Forms.ToolStripTextBox(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.mapWidthToolStripTextBox = new System.Windows.Forms.ToolStripTextBox(); this.mapHeightoolStripTextBox = new System.Windows.Forms.ToolStripTextBox(); this.toolStripSplitButton1 = new System.Windows.Forms.ToolStripSplitButton(); this.doubleSizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.halfSizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton8 = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.loadMapDialog = new System.Windows.Forms.OpenFileDialog(); this.saveMapDialog = new System.Windows.Forms.SaveFileDialog(); this.panel2 = new System.Windows.Forms.Panel(); this.panel1 = new System.Windows.Forms.Panel(); this.savePathDialog = new System.Windows.Forms.SaveFileDialog(); this.colorDialog1 = new System.Windows.Forms.ColorDialog(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.menuStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripToolStripMenuItem, this.actionToolStripMenuItem, this.toolStripMenuItem1, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1002, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripToolStripMenuItem // this.fileToolStripToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem3, this.toolStripMenuItem2, this.toolStripSeparator9, this.toolStripMenuItem7, this.toolStripSeparator3, this.toolStripMenuItem10}); this.fileToolStripToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("fileToolStripToolStripMenuItem.Image"))); this.fileToolStripToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.fileToolStripToolStripMenuItem.Name = "fileToolStripToolStripMenuItem"; this.fileToolStripToolStripMenuItem.Size = new System.Drawing.Size(65, 20); this.fileToolStripToolStripMenuItem.Text = "File(&F)"; // // toolStripMenuItem3 // this.toolStripMenuItem3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem3.Image"))); this.toolStripMenuItem3.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(187, 22); this.toolStripMenuItem3.Text = "Save map to file(&S)..."; this.toolStripMenuItem3.Click += new System.EventHandler(this.saveToolStripButton_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem2.Image"))); this.toolStripMenuItem2.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(187, 22); this.toolStripMenuItem2.Text = "Load map from file(&L)..."; this.toolStripMenuItem2.Click += new System.EventHandler(this.openToolStripButton_Click); // // toolStripSeparator9 // this.toolStripSeparator9.Name = "toolStripSeparator9"; this.toolStripSeparator9.Size = new System.Drawing.Size(184, 6); // // toolStripMenuItem7 // this.toolStripMenuItem7.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem7.Image"))); this.toolStripMenuItem7.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.toolStripMenuItem7.Name = "toolStripMenuItem7"; this.toolStripMenuItem7.Size = new System.Drawing.Size(187, 22); this.toolStripMenuItem7.Text = "Save path to file(&P)..."; this.toolStripMenuItem7.Click += new System.EventHandler(this.toolStripMenuItem7_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(184, 6); // // toolStripMenuItem10 // this.toolStripMenuItem10.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem10.Image"))); this.toolStripMenuItem10.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.toolStripMenuItem10.Name = "toolStripMenuItem10"; this.toolStripMenuItem10.Size = new System.Drawing.Size(187, 22); this.toolStripMenuItem10.Text = "Exit(&x)"; this.toolStripMenuItem10.Click += new System.EventHandler(this.toolStripMenuItem10_Click); // // actionToolStripMenuItem // this.actionToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.generateMazeToolStripMenuItem, this.randomizeIntegerPositionsToolStripMenuItem, this.generateFloatPositionsToolStripMenuItem, this.generateFullMapToolStripMenuItem}); this.actionToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("actionToolStripMenuItem.Image"))); this.actionToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.actionToolStripMenuItem.Name = "actionToolStripMenuItem"; this.actionToolStripMenuItem.Size = new System.Drawing.Size(118, 20); this.actionToolStripMenuItem.Text = "Generate map(&G)"; // // generateFullMapToolStripMenuItem // this.generateFullMapToolStripMenuItem.Name = "generateFullMapToolStripMenuItem"; this.generateFullMapToolStripMenuItem.Size = new System.Drawing.Size(264, 22); this.generateFullMapToolStripMenuItem.Text = "Generate full map(&F)"; this.generateFullMapToolStripMenuItem.Click += new System.EventHandler(this.generateFullMapToolStripMenuItem_Click); // // generateMazeToolStripMenuItem // this.generateMazeToolStripMenuItem.Name = "generateMazeToolStripMenuItem"; this.generateMazeToolStripMenuItem.Size = new System.Drawing.Size(264, 22); this.generateMazeToolStripMenuItem.Text = "Generate random maze(&M)"; this.generateMazeToolStripMenuItem.Click += new System.EventHandler(this.generateMazeToolStripMenuItem_Click); // // randomizeIntegerPositionsToolStripMenuItem // this.randomizeIntegerPositionsToolStripMenuItem.Name = "randomizeIntegerPositionsToolStripMenuItem"; this.randomizeIntegerPositionsToolStripMenuItem.Size = new System.Drawing.Size(264, 22); this.randomizeIntegerPositionsToolStripMenuItem.Text = "Generate random integer positions(&I)..."; this.randomizeIntegerPositionsToolStripMenuItem.Click += new System.EventHandler(this.randomizeMapToolStripMenuItem_Click); // // generateFloatPositionsToolStripMenuItem // this.generateFloatPositionsToolStripMenuItem.Name = "generateFloatPositionsToolStripMenuItem"; this.generateFloatPositionsToolStripMenuItem.Size = new System.Drawing.Size(264, 22); this.generateFloatPositionsToolStripMenuItem.Text = "Generate random float positions(&F)..."; this.generateFloatPositionsToolStripMenuItem.Click += new System.EventHandler(this.randomizePositionsToolStripMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.refreshRToolStripMenuItem, this.toolStripSeparator11, this.colorThePathToolStripMenuItem, this.toolStripSeparator4, this.nodeColorNToolStripMenuItem, this.pathNodeColorPToolStripMenuItem, this.selectedNodeColorSToolStripMenuItem, this.lineColorLToolStripMenuItem, this.selectBoxColorBToolStripMenuItem, this.toolStripSeparator10, this.lineWidthSettingsToolStripMenuItem}); this.toolStripMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem1.Image"))); this.toolStripMenuItem1.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(88, 20); this.toolStripMenuItem1.Text = "Options(&O)"; // // refreshRToolStripMenuItem // this.refreshRToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("refreshRToolStripMenuItem.Image"))); this.refreshRToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.refreshRToolStripMenuItem.Name = "refreshRToolStripMenuItem"; this.refreshRToolStripMenuItem.Size = new System.Drawing.Size(200, 22); this.refreshRToolStripMenuItem.Text = "Refresh Drawing(&R)"; this.refreshRToolStripMenuItem.Click += new System.EventHandler(this.refreshRToolStripMenuItem_Click); // // toolStripSeparator11 // this.toolStripSeparator11.Name = "toolStripSeparator11"; this.toolStripSeparator11.Size = new System.Drawing.Size(197, 6); // // colorThePathToolStripMenuItem // this.colorThePathToolStripMenuItem.Checked = true; this.colorThePathToolStripMenuItem.CheckOnClick = true; this.colorThePathToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.colorThePathToolStripMenuItem.Name = "colorThePathToolStripMenuItem"; this.colorThePathToolStripMenuItem.Size = new System.Drawing.Size(200, 22); this.colorThePathToolStripMenuItem.Text = "Color the path(&C)"; this.colorThePathToolStripMenuItem.Click += new System.EventHandler(this.colorThePathToolStripMenuItem_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(197, 6); // // nodeColorNToolStripMenuItem // this.nodeColorNToolStripMenuItem.Name = "nodeColorNToolStripMenuItem"; this.nodeColorNToolStripMenuItem.Size = new System.Drawing.Size(200, 22); this.nodeColorNToolStripMenuItem.Text = "Node Color(&N)..."; this.nodeColorNToolStripMenuItem.Click += new System.EventHandler(this.nodeColorNToolStripMenuItem_Click); // // pathNodeColorPToolStripMenuItem // this.pathNodeColorPToolStripMenuItem.Name = "pathNodeColorPToolStripMenuItem"; this.pathNodeColorPToolStripMenuItem.Size = new System.Drawing.Size(200, 22); this.pathNodeColorPToolStripMenuItem.Text = "Path Node Color(&P)..."; this.pathNodeColorPToolStripMenuItem.Click += new System.EventHandler(this.pathNodeColorPToolStripMenuItem_Click); // // selectedNodeColorSToolStripMenuItem // this.selectedNodeColorSToolStripMenuItem.Name = "selectedNodeColorSToolStripMenuItem"; this.selectedNodeColorSToolStripMenuItem.Size = new System.Drawing.Size(200, 22); this.selectedNodeColorSToolStripMenuItem.Text = "Selected Node Color(&S)..."; this.selectedNodeColorSToolStripMenuItem.Click += new System.EventHandler(this.selectedNodeColorSToolStripMenuItem_Click); // // lineColorLToolStripMenuItem // this.lineColorLToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; this.lineColorLToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlText; this.lineColorLToolStripMenuItem.Name = "lineColorLToolStripMenuItem"; this.lineColorLToolStripMenuItem.Size = new System.Drawing.Size(200, 22); this.lineColorLToolStripMenuItem.Text = "Connection line Color(&L)..."; this.lineColorLToolStripMenuItem.Click += new System.EventHandler(this.lineColorLToolStripMenuItem_Click); // // selectBoxColorBToolStripMenuItem // this.selectBoxColorBToolStripMenuItem.Name = "selectBoxColorBToolStripMenuItem"; this.selectBoxColorBToolStripMenuItem.Size = new System.Drawing.Size(200, 22); this.selectBoxColorBToolStripMenuItem.Text = "Select Box Color(&B)..."; this.selectBoxColorBToolStripMenuItem.Click += new System.EventHandler(this.selectBoxColorBToolStripMenuItem_Click); // // toolStripSeparator10 // this.toolStripSeparator10.Name = "toolStripSeparator10"; this.toolStripSeparator10.Size = new System.Drawing.Size(197, 6); // // lineWidthSettingsToolStripMenuItem // this.lineWidthSettingsToolStripMenuItem.Name = "lineWidthSettingsToolStripMenuItem"; this.lineWidthSettingsToolStripMenuItem.Size = new System.Drawing.Size(200, 22); this.lineWidthSettingsToolStripMenuItem.Text = "Line Width Settings(&W)..."; this.lineWidthSettingsToolStripMenuItem.Click += new System.EventHandler(this.lineWidthSettingsToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutToolStripMenuItem, this.pictureBoxToolStripMenuItem}); this.helpToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("helpToolStripMenuItem.Image"))); this.helpToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(71, 20); this.helpToolStripMenuItem.Text = "Help(&H)"; // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("aboutToolStripMenuItem.Image"))); this.aboutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(140, 22); this.aboutToolStripMenuItem.Text = "About(&A)"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // pictureBoxToolStripMenuItem // this.pictureBoxToolStripMenuItem.CheckOnClick = true; this.pictureBoxToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxToolStripMenuItem.Image"))); this.pictureBoxToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.pictureBoxToolStripMenuItem.Name = "pictureBoxToolStripMenuItem"; this.pictureBoxToolStripMenuItem.Size = new System.Drawing.Size(140, 22); this.pictureBoxToolStripMenuItem.Tag = "0"; this.pictureBoxToolStripMenuItem.Text = "Easter Egg(&E)"; this.pictureBoxToolStripMenuItem.Visible = false; this.pictureBoxToolStripMenuItem.Click += new System.EventHandler(this.pictureBoxToolStripMenuItem_Click); // // toolStrip1 // this.toolStrip1.BackColor = System.Drawing.SystemColors.Control; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.saveToolStripButton, this.openToolStripButton, this.toolStripSeparator5, this.pointerToolStripButton, this.nodeToolStripButton, this.connectionToolStripButton, this.doubleConnectionToolStripButton, this.eraserToolStripButton, this.clearToolStripButton, this.toolStripSeparator8, this.startPositionToolStripButton, this.endPositionToolStripButton, this.toolStripSeparator1, this.toolStripLabel4, this.toolStripDropDownButton1, this.toolStripSeparator7, this.toolStripLabel2, this.mapWidthToolStripTextBox, this.mapHeightoolStripTextBox, this.toolStripSplitButton1, this.toolStripSeparator6, this.toolStripButton1, this.toolStripButton2, this.toolStripButton8, this.toolStripSeparator2, this.toolStripLabel3, this.toolStripLabel1}); this.toolStrip1.Location = new System.Drawing.Point(0, 24); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(1002, 25); this.toolStrip1.TabIndex = 1; this.toolStrip1.Text = "toolStrip1"; // // saveToolStripButton // this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.saveToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripButton.Image"))); this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.saveToolStripButton.Name = "saveToolStripButton"; this.saveToolStripButton.Size = new System.Drawing.Size(23, 22); this.saveToolStripButton.Text = "&Save"; this.saveToolStripButton.ToolTipText = "Save map to file"; this.saveToolStripButton.Click += new System.EventHandler(this.saveToolStripButton_Click); // // openToolStripButton // this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.openToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripButton.Image"))); this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.openToolStripButton.Name = "openToolStripButton"; this.openToolStripButton.Size = new System.Drawing.Size(23, 22); this.openToolStripButton.Text = "&Open"; this.openToolStripButton.ToolTipText = "Load map from file"; this.openToolStripButton.Click += new System.EventHandler(this.openToolStripButton_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25); // // pointerToolStripButton // this.pointerToolStripButton.Checked = true; this.pointerToolStripButton.CheckState = System.Windows.Forms.CheckState.Checked; this.pointerToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.pointerToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("pointerToolStripButton.Image"))); this.pointerToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.pointerToolStripButton.Name = "pointerToolStripButton"; this.pointerToolStripButton.Size = new System.Drawing.Size(23, 22); this.pointerToolStripButton.Text = "toolStripButton8"; this.pointerToolStripButton.ToolTipText = "Pointer"; this.pointerToolStripButton.Click += new System.EventHandler(this.pointerToolStripButton_Click); // // nodeToolStripButton // this.nodeToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.nodeToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("nodeToolStripButton.Image"))); this.nodeToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.nodeToolStripButton.Name = "nodeToolStripButton"; this.nodeToolStripButton.Size = new System.Drawing.Size(23, 22); this.nodeToolStripButton.Text = "toolStripButton1"; this.nodeToolStripButton.ToolTipText = "Add Node"; this.nodeToolStripButton.Click += new System.EventHandler(this.pointerToolStripButton_Click); // // connectionToolStripButton // this.connectionToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.connectionToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("connectionToolStripButton.Image"))); this.connectionToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.connectionToolStripButton.Name = "connectionToolStripButton"; this.connectionToolStripButton.Size = new System.Drawing.Size(23, 22); this.connectionToolStripButton.Text = "toolStripButton9"; this.connectionToolStripButton.ToolTipText = "Add Single Connection"; this.connectionToolStripButton.Click += new System.EventHandler(this.pointerToolStripButton_Click); // // doubleConnectionToolStripButton // this.doubleConnectionToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.doubleConnectionToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("doubleConnectionToolStripButton.Image"))); this.doubleConnectionToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.doubleConnectionToolStripButton.Name = "doubleConnectionToolStripButton"; this.doubleConnectionToolStripButton.Size = new System.Drawing.Size(23, 22); this.doubleConnectionToolStripButton.Text = "toolStripButton10"; this.doubleConnectionToolStripButton.ToolTipText = "Add Double Connection"; this.doubleConnectionToolStripButton.Click += new System.EventHandler(this.pointerToolStripButton_Click); // // eraserToolStripButton // this.eraserToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.eraserToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("eraserToolStripButton.Image"))); this.eraserToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.eraserToolStripButton.Name = "eraserToolStripButton"; this.eraserToolStripButton.Size = new System.Drawing.Size(23, 22); this.eraserToolStripButton.Text = "toolStripButton3"; this.eraserToolStripButton.ToolTipText = "Remove Node"; this.eraserToolStripButton.Click += new System.EventHandler(this.pointerToolStripButton_Click); // // clearToolStripButton // this.clearToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.clearToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("clearToolStripButton.Image"))); this.clearToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.clearToolStripButton.Name = "clearToolStripButton"; this.clearToolStripButton.Size = new System.Drawing.Size(23, 22); this.clearToolStripButton.Text = "toolStripButton4"; this.clearToolStripButton.ToolTipText = "Clear Map"; this.clearToolStripButton.Click += new System.EventHandler(this.clearToolStripButton_Click); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(6, 25); // // startPositionToolStripButton // this.startPositionToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.startPositionToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("startPositionToolStripButton.Image"))); this.startPositionToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.startPositionToolStripButton.Name = "startPositionToolStripButton"; this.startPositionToolStripButton.Size = new System.Drawing.Size(23, 22); this.startPositionToolStripButton.Text = "toolStripButton2"; this.startPositionToolStripButton.ToolTipText = "Set Start Point"; this.startPositionToolStripButton.Click += new System.EventHandler(this.pointerToolStripButton_Click); // // endPositionToolStripButton // this.endPositionToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.endPositionToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("endPositionToolStripButton.Image"))); this.endPositionToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.endPositionToolStripButton.Name = "endPositionToolStripButton"; this.endPositionToolStripButton.Size = new System.Drawing.Size(23, 22); this.endPositionToolStripButton.Text = "toolStripButton1"; this.endPositionToolStripButton.ToolTipText = "Set End Point"; this.endPositionToolStripButton.Click += new System.EventHandler(this.pointerToolStripButton_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // toolStripLabel4 // this.toolStripLabel4.Name = "toolStripLabel4"; this.toolStripLabel4.Size = new System.Drawing.Size(54, 22); this.toolStripLabel4.Text = "View size:"; // // toolStripDropDownButton1 // this.toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem4, this.toolStripMenuItem5, this.blockSizeToolStripTextBox}); this.toolStripDropDownButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripDropDownButton1.Image"))); this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripDropDownButton1.Name = "toolStripDropDownButton1"; this.toolStripDropDownButton1.Size = new System.Drawing.Size(29, 22); this.toolStripDropDownButton1.Text = "Zoom"; this.toolStripDropDownButton1.ToolTipText = "Block Size(in pixel)"; // // toolStripMenuItem4 // this.toolStripMenuItem4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem4.Image"))); this.toolStripMenuItem4.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(181, 22); this.toolStripMenuItem4.Text = "Double Size(200%)(&D)"; this.toolStripMenuItem4.Click += new System.EventHandler(this.toolStripMenuItem4_Click); // // toolStripMenuItem5 // this.toolStripMenuItem5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem5.Image"))); this.toolStripMenuItem5.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.toolStripMenuItem5.Name = "toolStripMenuItem5"; this.toolStripMenuItem5.Size = new System.Drawing.Size(181, 22); this.toolStripMenuItem5.Text = "Half Size(50%)(&H)"; this.toolStripMenuItem5.Click += new System.EventHandler(this.toolStripMenuItem5_Click); // // blockSizeToolStripTextBox // this.blockSizeToolStripTextBox.Name = "blockSizeToolStripTextBox"; this.blockSizeToolStripTextBox.Size = new System.Drawing.Size(100, 21); this.blockSizeToolStripTextBox.ToolTipText = "Input Block Size(in pixel)"; this.blockSizeToolStripTextBox.TextChanged += new System.EventHandler(this.toolStripTextBox1_TextChanged); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25); // // toolStripLabel2 // this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(53, 22); this.toolStripLabel2.Text = "Map Size:"; this.toolStripLabel2.ToolTipText = "(Row,Column)"; // // mapWidthToolStripTextBox // this.mapWidthToolStripTextBox.MaxLength = 10; this.mapWidthToolStripTextBox.Name = "mapWidthToolStripTextBox"; this.mapWidthToolStripTextBox.Size = new System.Drawing.Size(40, 25); this.mapWidthToolStripTextBox.Text = "60"; this.mapWidthToolStripTextBox.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.mapWidthToolStripTextBox.ToolTipText = "Row Count"; // // mapHeightoolStripTextBox // this.mapHeightoolStripTextBox.MaxLength = 10; this.mapHeightoolStripTextBox.Name = "mapHeightoolStripTextBox"; this.mapHeightoolStripTextBox.Size = new System.Drawing.Size(40, 25); this.mapHeightoolStripTextBox.Text = "40"; this.mapHeightoolStripTextBox.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.mapHeightoolStripTextBox.ToolTipText = "Column Count"; // // toolStripSplitButton1 // this.toolStripSplitButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripSplitButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.doubleSizeToolStripMenuItem, this.halfSizeToolStripMenuItem}); this.toolStripSplitButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripSplitButton1.Image"))); this.toolStripSplitButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripSplitButton1.Name = "toolStripSplitButton1"; this.toolStripSplitButton1.Size = new System.Drawing.Size(32, 22); this.toolStripSplitButton1.Text = "Change map size"; this.toolStripSplitButton1.ButtonClick += new System.EventHandler(this.toolStripSplitButton1_ButtonClick); // // doubleSizeToolStripMenuItem // this.doubleSizeToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("doubleSizeToolStripMenuItem.Image"))); this.doubleSizeToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.doubleSizeToolStripMenuItem.Name = "doubleSizeToolStripMenuItem"; this.doubleSizeToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.doubleSizeToolStripMenuItem.Text = "Double Size(200%)(&D)"; this.doubleSizeToolStripMenuItem.Click += new System.EventHandler(this.doubleSizeToolStripMenuItem_Click); // // halfSizeToolStripMenuItem // this.halfSizeToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("halfSizeToolStripMenuItem.Image"))); this.halfSizeToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.halfSizeToolStripMenuItem.Name = "halfSizeToolStripMenuItem"; this.halfSizeToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.halfSizeToolStripMenuItem.Text = "Half Size(50%)(&H)"; this.halfSizeToolStripMenuItem.Click += new System.EventHandler(this.halfSizeToolStripMenuItem_Click); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25); // // toolStripButton1 // this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(63, 22); this.toolStripButton1.Text = "Dijkstra"; this.toolStripButton1.ToolTipText = "Search for path"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // toolStripButton2 // this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image"))); this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(40, 22); this.toolStripButton2.Text = "A*"; this.toolStripButton2.Click += new System.EventHandler(this.toolStripButton2_Click); // // toolStripButton8 // this.toolStripButton8.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton8.Image"))); this.toolStripButton8.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton8.Name = "toolStripButton8"; this.toolStripButton8.Size = new System.Drawing.Size(54, 22); this.toolStripButton8.Text = "Detail"; this.toolStripButton8.ToolTipText = "Show detail about the nodes and the path"; this.toolStripButton8.Click += new System.EventHandler(this.toolStripButton8_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25); this.toolStripSeparator2.Click += new System.EventHandler(this.toolStripSeparator2_Click); // // toolStripLabel3 // this.toolStripLabel3.Name = "toolStripLabel3"; this.toolStripLabel3.Size = new System.Drawing.Size(48, 22); this.toolStripLabel3.Text = "Position:"; // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(165, 22); this.toolStripLabel1.Text = "Mouse Position(row,column)(x,y)"; this.toolStripLabel1.ToolTipText = "Mouse Position(row,column)(x,y)"; // // loadMapDialog // this.loadMapDialog.DefaultExt = "map"; this.loadMapDialog.Filter = "map|*.map|all|*.*"; this.loadMapDialog.Title = "Load map from file"; // // saveMapDialog // this.saveMapDialog.Filter = "map|*.map|all|*.*"; this.saveMapDialog.Title = "Save map to file"; // // panel2 // this.panel2.AutoScroll = true; this.panel2.AutoSize = true; this.panel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.panel2.Controls.Add(this.panel1); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(0, 49); this.panel2.Margin = new System.Windows.Forms.Padding(0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(1002, 603); this.panel2.TabIndex = 2; // // panel1 // this.panel1.BackColor = System.Drawing.Color.Black; this.panel1.ForeColor = System.Drawing.SystemColors.Control; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(1001, 601); this.panel1.TabIndex = 4; this.panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.panel1_MouseMove); this.panel1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.panel1_MouseClick); this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint); // // savePathDialog // this.savePathDialog.Filter = "path|*.path|all|*.*"; this.savePathDialog.Title = "Save path to file"; // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(899, -64); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(32, 32); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; this.pictureBox1.Visible = false; // // EditForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1002, 652); this.Controls.Add(this.panel2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.menuStrip1); this.DoubleBuffered = true; this.MainMenuStrip = this.menuStrip1; this.Name = "EditForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Nodes Map Editor"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripToolStripMenuItem; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton nodeToolStripButton; private System.Windows.Forms.ToolStripButton startPositionToolStripButton; private System.Windows.Forms.ToolStripButton eraserToolStripButton; private System.Windows.Forms.ToolStripButton clearToolStripButton; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripTextBox blockSizeToolStripTextBox; private System.Windows.Forms.ToolStripTextBox mapWidthToolStripTextBox; private System.Windows.Forms.ToolStripTextBox mapHeightoolStripTextBox; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem10; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripButton openToolStripButton; private System.Windows.Forms.ToolStripButton saveToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripLabel toolStripLabel3; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.OpenFileDialog loadMapDialog; private System.Windows.Forms.SaveFileDialog saveMapDialog; private System.Windows.Forms.ToolStripButton pointerToolStripButton; private System.Windows.Forms.ToolStripButton toolStripButton8; private System.Windows.Forms.ToolStripButton connectionToolStripButton; private System.Windows.Forms.ToolStripButton doubleConnectionToolStripButton; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.ToolStripMenuItem pictureBoxToolStripMenuItem; private System.Windows.Forms.ToolStripButton endPositionToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator9; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem7; private System.Windows.Forms.SaveFileDialog savePathDialog; private System.Windows.Forms.ToolStripMenuItem actionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem generateMazeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem randomizeIntegerPositionsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem generateFloatPositionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem colorThePathToolStripMenuItem; private System.Windows.Forms.ColorDialog colorDialog1; private System.Windows.Forms.ToolStripMenuItem lineColorLToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem nodeColorNToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pathNodeColorPToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem selectedNodeColorSToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem selectBoxColorBToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripSeparator toolStripSeparator10; private System.Windows.Forms.ToolStripMenuItem lineWidthSettingsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem refreshRToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator11; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripSplitButton toolStripSplitButton1; private System.Windows.Forms.ToolStripMenuItem doubleSizeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem halfSizeToolStripMenuItem; private System.Windows.Forms.ToolStripLabel toolStripLabel4; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripMenuItem generateFullMapToolStripMenuItem; } }
using NAME.Core.Exceptions; using System; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using NAME.Json; using NAME.Core.Utils; namespace NAME.Core { /// <summary> /// Represents a version. /// </summary> public class DependencyVersion : IComparable<DependencyVersion>, IComparable { /// <summary> /// Gets the major version. /// </summary> /// <value> /// The major version. /// </value> public virtual uint Major { get; } /// <summary> /// Gets the minor version. /// </summary> /// <value> /// The minor version. /// </value> public virtual uint Minor { get; } /// <summary> /// Gets the patch version. /// </summary> /// <value> /// The patch version. /// </value> public virtual uint Patch { get; } /// <summary> /// Gets or sets the manifest jsonnode for this dependency. /// </summary> /// <value> /// The manifest. /// </value> internal JsonNode ManifestNode { get; set; } /// <summary> /// Initializes a new instance of the <see cref="DependencyVersion"/> class. /// </summary> /// <param name="major">The major.</param> /// <param name="minor">The minor.</param> /// <param name="patch">The patch.</param> public DependencyVersion(uint major, uint minor = 0, uint patch = 0) { this.Major = major; this.Minor = minor; this.Patch = patch; } /// <summary> /// Parses a <see cref="DependencyVersion" /> from the specified version string. /// This method is deprecated. Please use <see cref="DependencyVersionParser.Parse"/> instead./> /// </summary> /// <param name="version">The version string.</param> /// <returns> /// Returns a new instance of <see cref="DependencyVersion" />. /// </returns> [Obsolete("This method is deprecated. Please use DependencyVersionParser.Parse instead.")] public static DependencyVersion Parse(string version) { return DependencyVersionParser.Parse(version, false); } /// <summary> /// Tries to parse a <see cref="DependencyVersion" /> from the specified version string. /// This method is deprecated. Please use <see cref="DependencyVersionParser.TryParse"/> instead./> /// </summary> /// <param name="version">The version.</param> /// <param name="outVersion">The parsed version.</param> /// <returns> /// Returns true if the parsing was successfuly. Otherwise, returns false. /// </returns> [Obsolete("This method is deprecated. Please use DependencyVersionParser.TryParse instead.")] public static bool TryParse(string version, out DependencyVersion outVersion) { return DependencyVersionParser.TryParse(version, false, out outVersion); } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { return $"{this.Major}.{this.Minor}.{this.Patch}"; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="version1">The version1.</param> /// <param name="version2">The version2.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator <(DependencyVersion version1, DependencyVersion version2) { return Comparison(version1, version2) < 0; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="version1">The version1.</param> /// <param name="version2">The version2.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator >(DependencyVersion version1, DependencyVersion version2) { return Comparison(version1, version2) > 0; } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="version1">The version1.</param> /// <param name="version2">The version2.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator ==(DependencyVersion version1, DependencyVersion version2) { return Comparison(version1, version2) == 0; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="version1">The version1.</param> /// <param name="version2">The version2.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator !=(DependencyVersion version1, DependencyVersion version2) { return Comparison(version1, version2) != 0; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="version1">The version1.</param> /// <param name="version2">The version2.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator <=(DependencyVersion version1, DependencyVersion version2) { return Comparison(version1, version2) <= 0; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="version1">The version1.</param> /// <param name="version2">The version2.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator >=(DependencyVersion version1, DependencyVersion version2) { return Comparison(version1, version2) >= 0; } /// <summary> /// Determines whether the specified <see cref="object" />, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is DependencyVersion)) return false; return this.CompareTo((DependencyVersion)obj) == 0; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { int hash = 17; hash = (hash * 23) + this.Major.GetHashCode(); hash = (hash * 23) + this.Minor.GetHashCode(); hash = (hash * 23) + this.Patch.GetHashCode(); return hash; } /// <summary> /// Performs a comparision between two DependencyVersion objects. /// </summary> /// <param name="version1">The first version.</param> /// <param name="version2">The second version.</param> /// <returns>Returns 1 if the first version is bigger than the second version. /// Returns -1 if the first version is lesser than the second version. /// Return 0 if both versions are equal.</returns> public static int Comparison(DependencyVersion version1, DependencyVersion version2) { if (ReferenceEquals(version1, null) && ReferenceEquals(version2, null)) return 0; if (ReferenceEquals(version1, null)) return -1; return version1.CompareTo(version2); } /// <summary> /// Performs a comparision of this DependencyVersion with another object. /// </summary> /// <param name="obj">The object to compare this DependencyVersion to.</param> /// <returns>Returns 1 if the first version is bigger than the second version. /// Returns -1 if the first version is lesser than the second version. /// Return 0 if both versions are equal.</returns> public virtual int CompareTo(object obj) { if (!(obj is DependencyVersion)) return 1; return this.CompareTo((DependencyVersion)obj); } /// <summary> /// Performs a comparision of this DependencyVersion with another DependencyVersion object. /// </summary> /// <param name="other">The DependencyVersion to compare this DependencyVersion to.</param> /// <returns>Returns 1 if the first version is bigger than the second version. /// Returns -1 if the first version is lesser than the second version. /// Return 0 if both versions are equal.</returns> public virtual int CompareTo(DependencyVersion other) { if (ReferenceEquals(this, other)) return 0; if (ReferenceEquals(other, null)) return 1; var r = this.Major.CompareTo(other.Major); if (r != 0) return r; r = this.Minor.CompareTo(other.Minor); if (r != 0) return r; r = this.Patch.CompareTo(other.Patch); if (r != 0) return r; return 0; } } }
using System; using System.Collections.Generic; using System.IO; using Umbraco.Core.Models; namespace Umbraco.Core.Services { /// <summary> /// Defines the File Service, which is an easy access to operations involving <see cref="IFile"/> objects like Scripts, Stylesheets and Templates /// </summary> public interface IFileService : IService { IEnumerable<string> GetPartialViewSnippetNames(params string[] filterNames); void CreatePartialViewFolder(string folderPath); void CreatePartialViewMacroFolder(string folderPath); void DeletePartialViewFolder(string folderPath); void DeletePartialViewMacroFolder(string folderPath); IPartialView GetPartialView(string path); IPartialView GetPartialViewMacro(string path); [Obsolete("MacroScripts are obsolete - this is for backwards compatibility with upgraded sites.")] IPartialView GetMacroScript(string path); [Obsolete("UserControls are obsolete - this is for backwards compatibility with upgraded sites.")] IUserControl GetUserControl(string path); IEnumerable<IPartialView> GetPartialViewMacros(params string[] names); IXsltFile GetXsltFile(string path); IEnumerable<IXsltFile> GetXsltFiles(params string[] names); Attempt<IPartialView> CreatePartialView(IPartialView partialView, string snippetName = null, int userId = 0); Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, string snippetName = null, int userId = 0); bool DeletePartialView(string path, int userId = 0); bool DeletePartialViewMacro(string path, int userId = 0); Attempt<IPartialView> SavePartialView(IPartialView partialView, int userId = 0); Attempt<IPartialView> SavePartialViewMacro(IPartialView partialView, int userId = 0); bool ValidatePartialView(PartialView partialView); bool ValidatePartialViewMacro(PartialView partialView); /// <summary> /// Gets a list of all <see cref="Stylesheet"/> objects /// </summary> /// <returns>An enumerable list of <see cref="Stylesheet"/> objects</returns> IEnumerable<Stylesheet> GetStylesheets(params string[] names); /// <summary> /// Gets a <see cref="Stylesheet"/> object by its name /// </summary> /// <param name="name">Name of the stylesheet incl. extension</param> /// <returns>A <see cref="Stylesheet"/> object</returns> Stylesheet GetStylesheetByName(string name); /// <summary> /// Saves a <see cref="Stylesheet"/> /// </summary> /// <param name="stylesheet"><see cref="Stylesheet"/> to save</param> /// <param name="userId">Optional id of the user saving the stylesheet</param> void SaveStylesheet(Stylesheet stylesheet, int userId = 0); /// <summary> /// Deletes a stylesheet by its name /// </summary> /// <param name="path">Name incl. extension of the Stylesheet to delete</param> /// <param name="userId">Optional id of the user deleting the stylesheet</param> void DeleteStylesheet(string path, int userId = 0); /// <summary> /// Validates a <see cref="Stylesheet"/> /// </summary> /// <param name="stylesheet"><see cref="Stylesheet"/> to validate</param> /// <returns>True if Stylesheet is valid, otherwise false</returns> bool ValidateStylesheet(Stylesheet stylesheet); /// <summary> /// Gets a list of all <see cref="Script"/> objects /// </summary> /// <returns>An enumerable list of <see cref="Script"/> objects</returns> IEnumerable<Script> GetScripts(params string[] names); /// <summary> /// Gets a <see cref="Script"/> object by its name /// </summary> /// <param name="name">Name of the script incl. extension</param> /// <returns>A <see cref="Script"/> object</returns> Script GetScriptByName(string name); /// <summary> /// Saves a <see cref="Script"/> /// </summary> /// <param name="script"><see cref="Script"/> to save</param> /// <param name="userId">Optional id of the user saving the script</param> void SaveScript(Script script, int userId = 0); /// <summary> /// Deletes a script by its name /// </summary> /// <param name="path">Name incl. extension of the Script to delete</param> /// <param name="userId">Optional id of the user deleting the script</param> void DeleteScript(string path, int userId = 0); /// <summary> /// Validates a <see cref="Script"/> /// </summary> /// <param name="script"><see cref="Script"/> to validate</param> /// <returns>True if Script is valid, otherwise false</returns> bool ValidateScript(Script script); /// <summary> /// Creates a folder for scripts /// </summary> /// <param name="folderPath"></param> /// <returns></returns> void CreateScriptFolder(string folderPath); /// <summary> /// Deletes a folder for scripts /// </summary> /// <param name="folderPath"></param> void DeleteScriptFolder(string folderPath); /// <summary> /// Gets a list of all <see cref="ITemplate"/> objects /// </summary> /// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns> IEnumerable<ITemplate> GetTemplates(params string[] aliases); /// <summary> /// Gets a list of all <see cref="ITemplate"/> objects /// </summary> /// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns> IEnumerable<ITemplate> GetTemplates(int masterTemplateId); /// <summary> /// Gets a <see cref="ITemplate"/> object by its alias. /// </summary> /// <param name="alias">The alias of the template.</param> /// <returns>The <see cref="ITemplate"/> object matching the alias, or null.</returns> ITemplate GetTemplate(string alias); /// <summary> /// Gets a <see cref="ITemplate"/> object by its identifier. /// </summary> /// <param name="id">The identifer of the template.</param> /// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns> ITemplate GetTemplate(int id); /// <summary> /// Gets a <see cref="ITemplate"/> object by its guid identifier. /// </summary> /// <param name="id">The guid identifier of the template.</param> /// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns> ITemplate GetTemplate(Guid id); /// <summary> /// Gets the template descendants /// </summary> /// <param name="alias"></param> /// <returns></returns> IEnumerable<ITemplate> GetTemplateDescendants(string alias); /// <summary> /// Gets the template descendants /// </summary> /// <param name="masterTemplateId"></param> /// <returns></returns> IEnumerable<ITemplate> GetTemplateDescendants(int masterTemplateId); /// <summary> /// Gets the template children /// </summary> /// <param name="alias"></param> /// <returns></returns> IEnumerable<ITemplate> GetTemplateChildren(string alias); /// <summary> /// Gets the template children /// </summary> /// <param name="masterTemplateId"></param> /// <returns></returns> IEnumerable<ITemplate> GetTemplateChildren(int masterTemplateId); /// <summary> /// Returns a template as a template node which can be traversed (parent, children) /// </summary> /// <param name="alias"></param> /// <returns></returns> TemplateNode GetTemplateNode(string alias); /// <summary> /// Given a template node in a tree, this will find the template node with the given alias if it is found in the hierarchy, otherwise null /// </summary> /// <param name="anyNode"></param> /// <param name="alias"></param> /// <returns></returns> TemplateNode FindTemplateInTree(TemplateNode anyNode, string alias); /// <summary> /// Saves a <see cref="ITemplate"/> /// </summary> /// <param name="template"><see cref="ITemplate"/> to save</param> /// <param name="userId">Optional id of the user saving the template</param> void SaveTemplate(ITemplate template, int userId = 0); /// <summary> /// Creates a template for a content type /// </summary> /// <param name="contentTypeAlias"></param> /// <param name="contentTypeName"></param> /// <param name="userId"></param> /// <returns> /// The template created /// </returns> Attempt<OperationStatus<ITemplate, OperationStatusType>> CreateTemplateForContentType(string contentTypeAlias, string contentTypeName, int userId = 0); ITemplate CreateTemplateWithIdentity(string name, string content, ITemplate masterTemplate = null, int userId = 0); /// <summary> /// Deletes a template by its alias /// </summary> /// <param name="alias">Alias of the <see cref="ITemplate"/> to delete</param> /// <param name="userId">Optional id of the user deleting the template</param> void DeleteTemplate(string alias, int userId = 0); /// <summary> /// Validates a <see cref="ITemplate"/> /// </summary> /// <param name="template"><see cref="ITemplate"/> to validate</param> /// <returns>True if Script is valid, otherwise false</returns> bool ValidateTemplate(ITemplate template); /// <summary> /// Saves a collection of <see cref="Template"/> objects /// </summary> /// <param name="templates">List of <see cref="Template"/> to save</param> /// <param name="userId">Optional id of the user</param> void SaveTemplate(IEnumerable<ITemplate> templates, int userId = 0); /// <summary> /// This checks what the default rendering engine is set in config but then also ensures that there isn't already /// a template that exists in the opposite rendering engine's template folder, then returns the appropriate /// rendering engine to use. /// </summary> /// <returns></returns> /// <remarks> /// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx /// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml /// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page. /// This is mostly related to installing packages since packages install file templates to the file system and then create the /// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package. /// </remarks> RenderingEngine DetermineTemplateRenderingEngine(ITemplate template); /// <summary> /// Gets the content of a template as a stream. /// </summary> /// <param name="filepath">The filesystem path to the template.</param> /// <returns>The content of the template.</returns> Stream GetTemplateFileContentStream(string filepath); /// <summary> /// Sets the content of a template. /// </summary> /// <param name="filepath">The filesystem path to the template.</param> /// <param name="content">The content of the template.</param> void SetTemplateFileContent(string filepath, Stream content); /// <summary> /// Gets the size of a template. /// </summary> /// <param name="filepath">The filesystem path to the template.</param> /// <returns>The size of the template.</returns> long GetTemplateFileSize(string filepath); /// <summary> /// Gets the content of a macroscript as a stream. /// </summary> /// <param name="filepath">The filesystem path to the macroscript.</param> /// <returns>The content of the macroscript.</returns> Stream GetMacroScriptFileContentStream(string filepath); /// <summary> /// Sets the content of a macroscript. /// </summary> /// <param name="filepath">The filesystem path to the macroscript.</param> /// <param name="content">The content of the macroscript.</param> void SetMacroScriptFileContent(string filepath, Stream content); /// <summary> /// Gets the size of a macroscript. /// </summary> /// <param name="filepath">The filesystem path to the macroscript.</param> /// <returns>The size of the macroscript.</returns> long GetMacroScriptFileSize(string filepath); /// <summary> /// Gets the content of a stylesheet as a stream. /// </summary> /// <param name="filepath">The filesystem path to the stylesheet.</param> /// <returns>The content of the stylesheet.</returns> Stream GetStylesheetFileContentStream(string filepath); /// <summary> /// Sets the content of a stylesheet. /// </summary> /// <param name="filepath">The filesystem path to the stylesheet.</param> /// <param name="content">The content of the stylesheet.</param> void SetStylesheetFileContent(string filepath, Stream content); /// <summary> /// Gets the size of a stylesheet. /// </summary> /// <param name="filepath">The filesystem path to the stylesheet.</param> /// <returns>The size of the stylesheet.</returns> long GetStylesheetFileSize(string filepath); /// <summary> /// Gets the content of a script file as a stream. /// </summary> /// <param name="filepath">The filesystem path to the script.</param> /// <returns>The content of the script file.</returns> Stream GetScriptFileContentStream(string filepath); /// <summary> /// Sets the content of a script file. /// </summary> /// <param name="filepath">The filesystem path to the script.</param> /// <param name="content">The content of the script file.</param> void SetScriptFileContent(string filepath, Stream content); /// <summary> /// Gets the size of a script file. /// </summary> /// <param name="filepath">The filesystem path to the script file.</param> /// <returns>The size of the script file.</returns> long GetScriptFileSize(string filepath); /// <summary> /// Gets the content of a usercontrol as a stream. /// </summary> /// <param name="filepath">The filesystem path to the usercontrol.</param> /// <returns>The content of the usercontrol.</returns> Stream GetUserControlFileContentStream(string filepath); /// <summary> /// Sets the content of a usercontrol. /// </summary> /// <param name="filepath">The filesystem path to the usercontrol.</param> /// <param name="content">The content of the usercontrol.</param> void SetUserControlFileContent(string filepath, Stream content); /// <summary> /// Gets the size of a usercontrol. /// </summary> /// <param name="filepath">The filesystem path to the usercontrol.</param> /// <returns>The size of the usercontrol.</returns> long GetUserControlFileSize(string filepath); /// <summary> /// Gets the content of a XSLT file as a stream. /// </summary> /// <param name="filepath">The filesystem path to the XSLT file.</param> /// <returns>The content of the XSLT file.</returns> Stream GetXsltFileContentStream(string filepath); /// <summary> /// Sets the content of a XSLT file. /// </summary> /// <param name="filepath">The filesystem path to the XSLT file.</param> /// <param name="content">The content of the XSLT file.</param> void SetXsltFileContent(string filepath, Stream content); /// <summary> /// Gets the size of a XSLT file. /// </summary> /// <param name="filepath">The filesystem path to the XSLT file.</param> /// <returns>The size of the XSLT file.</returns> long GetXsltFileSize(string filepath); /// <summary> /// Gets the content of a macro partial view as a stream. /// </summary> /// <param name="filepath">The filesystem path to the macro partial view.</param> /// <returns>The content of the macro partial view.</returns> Stream GetPartialViewMacroFileContentStream(string filepath); /// <summary> /// Gets the content of a macro partial view snippet as a string /// </summary> /// <param name="snippetName">The name of the snippet</param> /// <returns></returns> string GetPartialViewMacroSnippetContent(string snippetName); /// <summary> /// Sets the content of a macro partial view. /// </summary> /// <param name="filepath">The filesystem path to the macro partial view.</param> /// <param name="content">The content of the macro partial view.</param> void SetPartialViewMacroFileContent(string filepath, Stream content); /// <summary> /// Gets the size of a macro partial view. /// </summary> /// <param name="filepath">The filesystem path to the macro partial view.</param> /// <returns>The size of the macro partial view.</returns> long GetPartialViewMacroFileSize(string filepath); /// <summary> /// Gets the content of a partial view as a stream. /// </summary> /// <param name="filepath">The filesystem path to the partial view.</param> /// <returns>The content of the partial view.</returns> Stream GetPartialViewFileContentStream(string filepath); /// <summary> /// Gets the content of a partial view snippet as a string. /// </summary> /// <param name="snippetName">The name of the snippet</param> /// <returns>The content of the partial view.</returns> string GetPartialViewSnippetContent(string snippetName); /// <summary> /// Sets the content of a partial view. /// </summary> /// <param name="filepath">The filesystem path to the partial view.</param> /// <param name="content">The content of the partial view.</param> void SetPartialViewFileContent(string filepath, Stream content); /// <summary> /// Gets the size of a partial view. /// </summary> /// <param name="filepath">The filesystem path to the partial view.</param> /// <returns>The size of the partial view.</returns> long GetPartialViewFileSize(string filepath); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; 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 System.Web; namespace HttpStress { /// <summary>Client context containing information pertaining to a single request.</summary> public sealed class RequestContext { private const string alphaNumeric = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private readonly Random _random; private readonly HttpClient _client; private readonly CancellationToken _globalToken; private readonly Configuration _config; public RequestContext(Configuration config, HttpClient httpClient, Random random, CancellationToken globalToken, int taskNum) { _random = random; _client = httpClient; _globalToken = globalToken; _config = config; TaskNum = taskNum; IsCancellationRequested = false; } public int TaskNum { get; } public bool IsCancellationRequested { get; private set; } public Version HttpVersion => _config.HttpVersion; public int MaxRequestParameters => _config.MaxParameters; public int MaxRequestUriSize => _config.MaxRequestUriSize; public int MaxRequestHeaderCount => _config.MaxRequestHeaderCount; public int MaxRequestHeaderTotalSize => _config.MaxRequestHeaderTotalSize; public int MaxContentLength => _config.MaxContentLength; public Uri BaseAddress => _client.BaseAddress; // HttpClient.SendAsync() wrapper that wires randomized cancellation public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption httpCompletion = HttpCompletionOption.ResponseContentRead, CancellationToken? token = null) { request.Version = HttpVersion; if (token != null) { // user-supplied cancellation token overrides random cancellation using var cts = CancellationTokenSource.CreateLinkedTokenSource(_globalToken, token.Value); return WithVersionValidation(await _client.SendAsync(request, httpCompletion, cts.Token)); } else if (GetRandomBoolean(_config.CancellationProbability)) { // trigger a random cancellation using var cts = CancellationTokenSource.CreateLinkedTokenSource(_globalToken); Task<HttpResponseMessage> task = _client.SendAsync(request, httpCompletion, cts.Token); // either spinwait or delay before triggering cancellation if (GetRandomBoolean(probability: 0.66)) { // bound spinning to 100 us double spinTimeMs = 0.1 * _random.NextDouble(); Stopwatch sw = Stopwatch.StartNew(); do { Thread.SpinWait(10); } while (!task.IsCompleted && sw.Elapsed.TotalMilliseconds < spinTimeMs); } else { // 60ms is the 99th percentile when // running the stress suite locally under default load await Task.WhenAny(task, Task.Delay(_random.Next(0, 60), cts.Token)); } cts.Cancel(); IsCancellationRequested = true; return WithVersionValidation(await task); } else { // no cancellation return WithVersionValidation(await _client.SendAsync(request, httpCompletion, _globalToken)); } HttpResponseMessage WithVersionValidation(HttpResponseMessage m) { // WinHttpHandler seems to not report HttpResponseMessage.Version correctly if (!_config.UseWinHttpHandler && m.Version != HttpVersion) { throw new Exception($"Expected response version {HttpVersion}, got {m.Version}"); } return m; } } /// Gets a random ASCII string within specified length range public string GetRandomString(int minLength, int maxLength, bool alphaNumericOnly = true) { int length = _random.Next(minLength, maxLength); var sb = new StringBuilder(length); for (int i = 0; i < length; i++) { if (alphaNumericOnly) { // alpha character sb.Append(alphaNumeric[_random.Next(alphaNumeric.Length)]); } else { // use a random ascii character sb.Append((char)_random.Next(0, 128)); } } return sb.ToString(); } public byte[] GetRandomBytes(int minBytes, int maxBytes) { byte[] bytes = new byte[_random.Next(minBytes, maxBytes)]; _random.NextBytes(bytes); return bytes; } public bool GetRandomBoolean(double probability = 0.5) { if (probability < 0 || probability > 1) throw new ArgumentOutOfRangeException(nameof(probability)); return _random.NextDouble() < probability; } public void PopulateWithRandomHeaders(HttpRequestHeaders headers) { int headerCount = _random.Next(MaxRequestHeaderCount); int totalSize = 0; for (int i = 0; i < headerCount; i++) { string name = $"header-{i}"; string CreateHeaderValue() => HttpUtility.UrlEncode(GetRandomString(1, 30, alphaNumericOnly: false)); string[] values = Enumerable.Range(0, _random.Next(1, 6)).Select(_ => CreateHeaderValue()).ToArray(); totalSize += name.Length + values.Select(v => v.Length + 2).Sum(); if (totalSize > MaxRequestHeaderTotalSize) { break; } headers.Add(name, values); } } // Generates a random expected response content length and adds it to the request headers public int SetExpectedResponseContentLengthHeader(HttpRequestHeaders headers, int minLength = 0) { int expectedResponseContentLength = _random.Next(minLength, Math.Max(minLength, MaxContentLength)); headers.Add(StressServer.ExpectedResponseContentLength, expectedResponseContentLength.ToString()); return expectedResponseContentLength; } public int GetRandomInt32(int minValueInclusive, int maxValueExclusive) => _random.Next(minValueInclusive, maxValueExclusive); } public static class ClientOperations { // Set of operations that the client can select from to run. Each item is a tuple of the operation's name // and the delegate to invoke for it, provided with the HttpClient instance on which to make the call and // returning asynchronously the retrieved response string from the server. Individual operations can be // commented out from here to turn them off, or additional ones can be added. public static (string name, Func<RequestContext, Task> operation)[] Operations => new (string, Func<RequestContext, Task>)[] { ("GET", async ctx => { using var req = new HttpRequestMessage(HttpMethod.Get, "/get"); int expectedLength = ctx.SetExpectedResponseContentLengthHeader(req.Headers); using HttpResponseMessage m = await ctx.SendAsync(req); ValidateStatusCode(m); ValidateServerContent(await m.Content.ReadAsStringAsync(), expectedLength); }), ("GET Partial", async ctx => { using var req = new HttpRequestMessage(HttpMethod.Get, "/slow"); int expectedLength = ctx.SetExpectedResponseContentLengthHeader(req.Headers, minLength: 2); using HttpResponseMessage m = await ctx.SendAsync(req, HttpCompletionOption.ResponseHeadersRead); ValidateStatusCode(m); using (Stream s = await m.Content.ReadAsStreamAsync()) { s.ReadByte(); // read single byte from response and throw the rest away } }), ("GET Headers", async ctx => { using var req = new HttpRequestMessage(HttpMethod.Get, "/headers"); ctx.PopulateWithRandomHeaders(req.Headers); ulong expectedChecksum = CRC.CalculateHeaderCrc(req.Headers.Select(x => (x.Key, x.Value))); using HttpResponseMessage res = await ctx.SendAsync(req); ValidateStatusCode(res); await res.Content.ReadAsStringAsync(); bool isValidChecksum = ValidateServerChecksum(res.Headers, expectedChecksum); string GetFailureDetails() => isValidChecksum ? "server checksum matches client checksum" : "server checksum mismatch"; // Validate that request headers are being echoed foreach (KeyValuePair<string, IEnumerable<string>> reqHeader in req.Headers) { if (!res.Headers.TryGetValues(reqHeader.Key, out IEnumerable<string> values)) { throw new Exception($"Expected response header name {reqHeader.Key} missing. {GetFailureDetails()}"); } else if (!reqHeader.Value.SequenceEqual(values)) { string FmtValues(IEnumerable<string> values) => string.Join(", ", values.Select(x => $"\"{x}\"")); throw new Exception($"Unexpected values for header {reqHeader.Key}. Expected {FmtValues(reqHeader.Value)} but got {FmtValues(values)}. {GetFailureDetails()}"); } } // Validate trailing headers are being echoed if (res.TrailingHeaders.Count() > 0) { foreach (KeyValuePair<string, IEnumerable<string>> reqHeader in req.Headers) { if (!res.TrailingHeaders.TryGetValues(reqHeader.Key + "-trailer", out IEnumerable<string> values)) { throw new Exception($"Expected trailing header name {reqHeader.Key}-trailer missing. {GetFailureDetails()}"); } else if (!reqHeader.Value.SequenceEqual(values)) { string FmtValues(IEnumerable<string> values) => string.Join(", ", values.Select(x => $"\"{x}\"")); throw new Exception($"Unexpected values for trailing header {reqHeader.Key}-trailer. Expected {FmtValues(reqHeader.Value)} but got {FmtValues(values)}. {GetFailureDetails()}"); } } } if (!isValidChecksum) { // Should not reach this block unless there's a bug in checksum validation logic. Do throw now throw new Exception("server checksum mismatch"); } }), ("GET Parameters", async ctx => { string uri = "/variables"; string expectedResponse = GetGetQueryParameters(ref uri, ctx.MaxRequestUriSize, ctx, ctx.MaxRequestParameters); using var req = new HttpRequestMessage(HttpMethod.Get, uri); using HttpResponseMessage m = await ctx.SendAsync(req); ValidateStatusCode(m); ValidateContent(expectedResponse, await m.Content.ReadAsStringAsync(), $"Uri: {uri}"); }), ("GET Aborted", async ctx => { try { using var req = new HttpRequestMessage(HttpMethod.Get, "/abort"); ctx.SetExpectedResponseContentLengthHeader(req.Headers, minLength: 2); await ctx.SendAsync(req); throw new Exception("Completed unexpectedly"); } catch (Exception e) { if (e is HttpRequestException hre && hre.InnerException is IOException) { e = hre.InnerException; } if (e is IOException ioe) { if (ctx.HttpVersion < HttpVersion.Version20) { return; } string? name = e.InnerException?.GetType().Name; switch (name) { case "Http2ProtocolException": case "Http2ConnectionException": case "Http2StreamException": if ((e.InnerException?.Message?.Contains("INTERNAL_ERROR") ?? false) || // UseKestrel (https://github.com/aspnet/AspNetCore/issues/12256) (e.InnerException?.Message?.Contains("CANCEL") ?? false)) // UseHttpSys { return; } break; } } throw; } }), ("POST", async ctx => { string content = ctx.GetRandomString(0, ctx.MaxContentLength); ulong checksum = CRC.CalculateCRC(content); using var req = new HttpRequestMessage(HttpMethod.Post, "/") { Content = new StringDuplexContent(content) }; using HttpResponseMessage m = await ctx.SendAsync(req); ValidateStatusCode(m); string checksumMessage = ValidateServerChecksum(m.Headers, checksum) ? "server checksum matches client checksum" : "server checksum mismatch"; ValidateContent(content, await m.Content.ReadAsStringAsync(), checksumMessage); }), ("POST Multipart Data", async ctx => { (string expected, MultipartContent formDataContent) formData = GetMultipartContent(ctx, ctx.MaxRequestParameters); ulong checksum = CRC.CalculateCRC(formData.expected); using var req = new HttpRequestMessage(HttpMethod.Post, "/") { Content = formData.formDataContent }; using HttpResponseMessage m = await ctx.SendAsync(req); ValidateStatusCode(m); string checksumMessage = ValidateServerChecksum(m.Headers, checksum) ? "server checksum matches client checksum" : "server checksum mismatch"; ValidateContent(formData.expected, await m.Content.ReadAsStringAsync(), checksumMessage); }), ("POST Duplex", async ctx => { string content = ctx.GetRandomString(0, ctx.MaxContentLength); ulong checksum = CRC.CalculateCRC(content); using var req = new HttpRequestMessage(HttpMethod.Post, "/duplex") { Content = new StringDuplexContent(content) }; using HttpResponseMessage m = await ctx.SendAsync(req, HttpCompletionOption.ResponseHeadersRead); ValidateStatusCode(m); string response = await m.Content.ReadAsStringAsync(); string checksumMessage = ValidateServerChecksum(m.TrailingHeaders, checksum, required: false) ? "server checksum matches client checksum" : "server checksum mismatch"; ValidateContent(content, await m.Content.ReadAsStringAsync(), checksumMessage); }), ("POST Duplex Slow", async ctx => { string content = ctx.GetRandomString(0, ctx.MaxContentLength); byte[] byteContent = Encoding.ASCII.GetBytes(content); ulong checksum = CRC.CalculateCRC(byteContent); using var req = new HttpRequestMessage(HttpMethod.Post, "/duplexSlow") { Content = new ByteAtATimeNoLengthContent(byteContent) }; using HttpResponseMessage m = await ctx.SendAsync(req, HttpCompletionOption.ResponseHeadersRead); ValidateStatusCode(m); string response = await m.Content.ReadAsStringAsync(); // trailing headers not supported for all servers, so do not require checksums bool isValidChecksum = ValidateServerChecksum(m.TrailingHeaders, checksum, required: false); ValidateContent(content, response, details: $"server checksum {(isValidChecksum ? "matches" : "does not match")} client value."); if (!isValidChecksum) { // Should not reach this block unless there's a bug in checksum validation logic. Do throw now throw new Exception("server checksum mismatch"); } }), ("POST Duplex Dispose", async ctx => { // try to reproduce conditions described in https://github.com/dotnet/corefx/issues/39819 string content = ctx.GetRandomString(0, ctx.MaxContentLength); using var req = new HttpRequestMessage(HttpMethod.Post, "/duplex") { Content = new StringDuplexContent(content) }; using HttpResponseMessage m = await ctx.SendAsync(req, HttpCompletionOption.ResponseHeadersRead); ValidateStatusCode(m); // Cause the response to be disposed without reading the response body, which will cause the client to cancel the request }), ("POST ExpectContinue", async ctx => { string content = ctx.GetRandomString(0, ctx.MaxContentLength); ulong checksum = CRC.CalculateCRC(content); using var req = new HttpRequestMessage(HttpMethod.Post, "/") { Content = new StringContent(content) }; req.Headers.ExpectContinue = true; using HttpResponseMessage m = await ctx.SendAsync(req, HttpCompletionOption.ResponseHeadersRead); ValidateStatusCode(m); string checksumMessage = ValidateServerChecksum(m.Headers, checksum) ? "server checksum matches client checksum" : "server checksum mismatch"; ValidateContent(content, await m.Content.ReadAsStringAsync(), checksumMessage); }), ("HEAD", async ctx => { using var req = new HttpRequestMessage(HttpMethod.Head, "/"); int expectedLength = ctx.SetExpectedResponseContentLengthHeader(req.Headers); using HttpResponseMessage m = await ctx.SendAsync(req); ValidateStatusCode(m); if (m.Content.Headers.ContentLength != expectedLength) { throw new Exception($"Expected {expectedLength}, got {m.Content.Headers.ContentLength}"); } string r = await m.Content.ReadAsStringAsync(); if (r.Length > 0) throw new Exception($"Got unexpected response: {r}"); }), ("PUT", async ctx => { string content = ctx.GetRandomString(0, ctx.MaxContentLength); using var req = new HttpRequestMessage(HttpMethod.Put, "/") { Content = new StringContent(content) }; using HttpResponseMessage m = await ctx.SendAsync(req); ValidateStatusCode(m); string r = await m.Content.ReadAsStringAsync(); if (r != "") throw new Exception($"Got unexpected response: {r}"); }), ("PUT Slow", async ctx => { string content = ctx.GetRandomString(0, ctx.MaxContentLength); using var req = new HttpRequestMessage(HttpMethod.Put, "/") { Content = new ByteAtATimeNoLengthContent(Encoding.ASCII.GetBytes(content)) }; using HttpResponseMessage m = await ctx.SendAsync(req); ValidateStatusCode(m); string r = await m.Content.ReadAsStringAsync(); if (r != "") throw new Exception($"Got unexpected response: {r}"); }), ("GET Slow", async ctx => { using var req = new HttpRequestMessage(HttpMethod.Get, "/slow"); int expectedLength = ctx.SetExpectedResponseContentLengthHeader(req.Headers); using HttpResponseMessage m = await ctx.SendAsync(req); ValidateStatusCode(m); ValidateServerContent(await m.Content.ReadAsStringAsync(), expectedLength); }), }; private static void ValidateStatusCode(HttpResponseMessage m, HttpStatusCode expectedStatus = HttpStatusCode.OK) { if (m.StatusCode != expectedStatus) { throw new Exception($"Expected status code {expectedStatus}, got {m.StatusCode}"); } } private static void ValidateContent(string expectedContent, string actualContent, string? details = null) { if (actualContent != expectedContent) { int divergentIndex = Enumerable .Zip(actualContent, expectedContent) .Select((x,i) => (x.First, x.Second, i)) .Where(x => x.First != x.Second) .Select(x => (int?) x.i) .FirstOrDefault() .GetValueOrDefault(Math.Min(actualContent.Length, expectedContent.Length)); throw new Exception($"Expected response content \"{expectedContent}\", got \"{actualContent}\".\n Diverging at index {divergentIndex}. {details}"); } } private static void ValidateServerContent(string content, int expectedLength) { if (content.Length != expectedLength) { throw new Exception($"Unexpected response content {content}. Should have length {expectedLength} long but was {content.Length}"); } if (!ServerContentUtils.IsValidServerContent(content)) { throw new Exception($"Unexpected response content {content}"); } } private static string GetGetQueryParameters(ref string uri, int maxRequestUriSize, RequestContext clientContext, int numParameters) { if (maxRequestUriSize < uri.Length) { throw new ArgumentOutOfRangeException(nameof(maxRequestUriSize)); } if (numParameters <= 0) { throw new ArgumentOutOfRangeException(nameof(numParameters)); } var expectedString = new StringBuilder(); var uriSb = new StringBuilder(uri); maxRequestUriSize -= clientContext.BaseAddress.OriginalString.Length + uri.Length + 1; int appxMaxValueLength = Math.Max(maxRequestUriSize / numParameters, 1); int num = clientContext.GetRandomInt32(1, numParameters + 1); for (int i = 0; i < num; i++) { string key = $"{(i == 0 ? "?" : "&")}Var{i}="; int remainingLength = maxRequestUriSize - uriSb.Length - key.Length; if (remainingLength <= 0) { break; } uriSb.Append(key); string value = clientContext.GetRandomString(0, Math.Min(appxMaxValueLength, remainingLength)); expectedString.Append(value); uriSb.Append(value); } uri = uriSb.ToString(); return expectedString.ToString(); } private static (string, MultipartContent) GetMultipartContent(RequestContext clientContext, int numFormFields) { var multipartContent = new MultipartContent("prefix" + clientContext.GetRandomString(0, clientContext.MaxContentLength), "test_boundary"); StringBuilder sb = new StringBuilder(); int num = clientContext.GetRandomInt32(1, numFormFields + 1); for (int i = 0; i < num; i++) { sb.Append("--test_boundary\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n"); string content = clientContext.GetRandomString(0, clientContext.MaxContentLength); sb.Append(content); sb.Append("\r\n"); multipartContent.Add(new StringContent(content)); } sb.Append("--test_boundary--\r\n"); return (sb.ToString(), multipartContent); } private static bool ValidateServerChecksum(HttpResponseHeaders headers, ulong expectedChecksum, bool required = true) { if (headers.TryGetValues("crc32", out IEnumerable<string> values) && uint.TryParse(values.First(), out uint serverChecksum)) { return serverChecksum == expectedChecksum; } else if (required) { throw new Exception("could not find checksum header in server response"); } else { return true; } } /// <summary>HttpContent that's similar to StringContent but that can be used with HTTP/2 duplex communication.</summary> private sealed class StringDuplexContent : HttpContent { private readonly byte[] _data; public StringDuplexContent(string value) => _data = Encoding.UTF8.GetBytes(value); protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) => stream.WriteAsync(_data, 0, _data.Length); protected override bool TryComputeLength(out long length) { length = _data.Length; return true; } } /// <summary>HttpContent that trickles out a byte at a time.</summary> private sealed class ByteAtATimeNoLengthContent : HttpContent { private readonly byte[] _buffer; public ByteAtATimeNoLengthContent(byte[] buffer) => _buffer = buffer; protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { for (int i = 0; i < _buffer.Length; i++) { await stream.WriteAsync(_buffer.AsMemory(i, 1)); await stream.FlushAsync(); } } protected override bool TryComputeLength(out long length) { length = 0; return false; } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Windows.Graphics.Imaging; using Windows.Media; using Windows.Media.Capture; using Windows.Media.FaceAnalysis; using Windows.Media.MediaProperties; using Windows.System.Threading; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Shapes; namespace SDKTemplate { /// <summary> /// Page for demonstrating FaceTracking. /// </summary> public sealed partial class Scenario1_TrackInWebcam : Page { /// <summary> /// Reference back to the "root" page of the app. /// </summary> private MainPage rootPage = MainPage.Current; /// <summary> /// Holds the current scenario state value. /// </summary> private ScenarioState currentState = ScenarioState.Idle; /// <summary> /// References a MediaCapture instance; is null when not in Streaming state. /// </summary> private MediaCapture mediaCapture; /// <summary> /// Cache of properties from the current MediaCapture device which is used for capturing the preview frame. /// </summary> private VideoEncodingProperties videoProperties; /// <summary> /// References a FaceTracker instance. /// </summary> private FaceTracker faceTracker; /// <summary> /// A periodic timer to execute FaceTracker on preview frames /// </summary> private ThreadPoolTimer frameProcessingTimer; /// <summary> /// Flag to ensure FaceTracking logic only executes one at a time /// </summary> private int busy = 0; /// <summary> /// Initializes a new instance of the <see cref="Scenario1_TrackInWebcam"/> class. /// </summary> public Scenario1_TrackInWebcam() { this.InitializeComponent(); } /// <summary> /// Values for identifying and controlling scenario states. /// </summary> private enum ScenarioState { /// <summary> /// Display is blank - default state. /// </summary> Idle, /// <summary> /// Webcam is actively engaged and a live video stream is displayed. /// </summary> Streaming } /// <summary> /// Responds when we navigate to this page. /// </summary> /// <param name="e">Event data</param> protected override void OnNavigatedTo(NavigationEventArgs e) { App.Current.Suspending += this.OnSuspending; } /// <summary> /// Responds when we navigate away from this page. /// </summary> /// <param name="e">Event data</param> protected override void OnNavigatedFrom(NavigationEventArgs e) { App.Current.Suspending -= this.OnSuspending; } /// <summary> /// Responds to App Suspend event to stop/release MediaCapture object if it's running and return to Idle state. /// </summary> /// <param name="sender">The source of the Suspending event</param> /// <param name="e">Event data</param> private async void OnSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) { if (this.currentState == ScenarioState.Streaming) { var deferral = e.SuspendingOperation.GetDeferral(); try { await this.ChangeScenarioStateAsync(ScenarioState.Idle); } finally { deferral.Complete(); } } } /// <summary> /// Creates the FaceTracker object which we will use for face detection and tracking. /// Initializes a new MediaCapture instance and starts the Preview streaming to the CamPreview UI element. /// </summary> /// <returns>Async Task object returning true if initialization and streaming were successful and false if an exception occurred.</returns> private async Task<bool> StartWebcamStreamingAsync() { bool successful = false; faceTracker = await FaceTracker.CreateAsync(); try { this.mediaCapture = new MediaCapture(); // For this scenario, we only need Video (not microphone) so specify this in the initializer. // NOTE: the appxmanifest only declares "webcam" under capabilities and if this is changed to include // microphone (default constructor) you must add "microphone" to the manifest or initialization will fail. MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings(); settings.StreamingCaptureMode = StreamingCaptureMode.Video; await this.mediaCapture.InitializeAsync(settings); this.mediaCapture.Failed += this.MediaCapture_CameraStreamFailed; // Cache the media properties as we'll need them later. var deviceController = this.mediaCapture.VideoDeviceController; this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; // Immediately start streaming to our CaptureElement UI. // NOTE: CaptureElement's Source must be set before streaming is started. this.CamPreview.Source = this.mediaCapture; await this.mediaCapture.StartPreviewAsync(); // Run the timer at 66ms, which is approximately 15 frames per second. TimeSpan timerInterval = TimeSpan.FromMilliseconds(66); this.frameProcessingTimer = ThreadPoolTimer.CreatePeriodicTimer(ProcessCurrentVideoFrame, timerInterval); successful = true; } catch (System.UnauthorizedAccessException) { // If the user has disabled their webcam this exception is thrown; provide a descriptive message to inform the user of this fact. this.rootPage.NotifyUser("Webcam is disabled or access to the webcam is disabled for this app.\nEnsure Privacy Settings allow webcam usage.", NotifyType.ErrorMessage); } catch (Exception ex) { this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); } return successful; } /// <summary> /// Safely stops webcam streaming (if running) and releases MediaCapture object. /// </summary> private async Task ShutdownWebcamAsync() { if(this.frameProcessingTimer != null) { this.frameProcessingTimer.Cancel(); } if (this.mediaCapture != null) { if (this.mediaCapture.CameraStreamState == Windows.Media.Devices.CameraStreamState.Streaming) { try { await this.mediaCapture.StopPreviewAsync(); } catch(Exception) { ; // Since we're going to destroy the MediaCapture object there's nothing to do here } } this.mediaCapture.Dispose(); } this.frameProcessingTimer = null; this.CamPreview.Source = null; this.mediaCapture = null; this.CameraStreamingButton.IsEnabled = true; } /// <summary> /// This method is invoked by a ThreadPoolTimer to execute the FaceTracker and Visualization logic. /// </summary> /// <param name="timer">Timer object invoking this call</param> private async void ProcessCurrentVideoFrame(ThreadPoolTimer timer) { if (this.currentState != ScenarioState.Streaming) { return; } // If busy is already 1, then the previous frame is still being processed, // in which case we skip the current frame. if (Interlocked.CompareExchange(ref busy, 1, 0) != 0) { return; } await ProcessCurrentVideoFrameAsync(); Interlocked.Exchange(ref busy, 0); } /// <summary> /// This method is called to execute the FaceTracker and Visualization logic at each timer tick. /// </summary> /// <remarks> /// Keep in mind this method is called from a Timer and not synchronized with the camera stream. Also, the processing time of FaceTracker /// will vary depending on the size of each frame and the number of faces being tracked. That is, a large image with several tracked faces may /// take longer to process. /// </remarks> private async Task ProcessCurrentVideoFrameAsync() { // Create a VideoFrame object specifying the pixel format we want our capture image to be (NV12 bitmap in this case). // GetPreviewFrame will convert the native webcam frame into this format. const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Nv12; using (VideoFrame previewFrame = new VideoFrame(InputPixelFormat, (int)this.videoProperties.Width, (int)this.videoProperties.Height)) { try { await this.mediaCapture.GetPreviewFrameAsync(previewFrame); } catch (UnauthorizedAccessException) { // Lost access to the camera. AbandonStreaming(); return; } catch (Exception) { this.rootPage.NotifyUser($"PreviewFrame with format '{InputPixelFormat}' is not supported by your Webcam", NotifyType.ErrorMessage); return; } // The returned VideoFrame should be in the supported NV12 format but we need to verify this. if (!FaceDetector.IsBitmapPixelFormatSupported(previewFrame.SoftwareBitmap.BitmapPixelFormat)) { this.rootPage.NotifyUser($"PixelFormat '{previewFrame.SoftwareBitmap.BitmapPixelFormat}' is not supported by FaceDetector", NotifyType.ErrorMessage); return; } IList<DetectedFace> faces; try { faces = await this.faceTracker.ProcessNextFrameAsync(previewFrame); } catch (Exception ex) { this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); return; } // Create our visualization using the frame dimensions and face results but run it on the UI thread. var previewFrameSize = new Windows.Foundation.Size(previewFrame.SoftwareBitmap.PixelWidth, previewFrame.SoftwareBitmap.PixelHeight); var ignored = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { this.SetupVisualization(previewFrameSize, faces); }); } } /// <summary> /// Takes the webcam image and FaceTracker results and assembles the visualization onto the Canvas. /// </summary> /// <param name="framePizelSize">Width and height (in pixels) of the video capture frame</param> /// <param name="foundFaces">List of detected faces; output from FaceTracker</param> private void SetupVisualization(Windows.Foundation.Size framePixelSize, IList<DetectedFace> foundFaces) { this.VisualizationCanvas.Children.Clear(); if (this.currentState == ScenarioState.Streaming && framePixelSize.Width != 0.0 && framePixelSize.Height != 0.0) { double widthScale = this.VisualizationCanvas.ActualWidth / framePixelSize.Width; double heightScale = this.VisualizationCanvas.ActualHeight / framePixelSize.Height; foreach (DetectedFace face in foundFaces) { // Create a rectangle element for displaying the face box but since we're using a Canvas // we must scale the rectangles according to the frames's actual size. Rectangle box = new Rectangle() { Width = face.FaceBox.Width * widthScale, Height = face.FaceBox.Height * heightScale, Margin = new Thickness(face.FaceBox.X * widthScale, face.FaceBox.Y * heightScale, 0, 0), Style = HighlightedFaceBoxStyle }; this.VisualizationCanvas.Children.Add(box); } } } /// <summary> /// Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the /// passed in state value. Handles failures and resets the state if necessary. /// </summary> /// <param name="newState">State to switch to</param> private async Task ChangeScenarioStateAsync(ScenarioState newState) { // Disable UI while state change is in progress this.CameraStreamingButton.IsEnabled = false; switch (newState) { case ScenarioState.Idle: this.currentState = newState; await this.ShutdownWebcamAsync(); this.VisualizationCanvas.Children.Clear(); this.CameraStreamingButton.Content = "Start Streaming"; break; case ScenarioState.Streaming: if (!await this.StartWebcamStreamingAsync()) { await this.ChangeScenarioStateAsync(ScenarioState.Idle); break; } this.VisualizationCanvas.Children.Clear(); this.CameraStreamingButton.Content = "Stop Streaming"; this.currentState = newState; this.CameraStreamingButton.IsEnabled = true; break; } } private void AbandonStreaming() { // MediaCapture is not Agile and so we cannot invoke its methods on this caller's thread // and instead need to schedule the state change on the UI thread. var ignored = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { await ChangeScenarioStateAsync(ScenarioState.Idle); }); } /// <summary> /// Handles MediaCapture stream failures by shutting down streaming and returning to Idle state. /// </summary> /// <param name="sender">The source of the event, i.e. our MediaCapture object</param> /// <param name="args">Event data</param> private void MediaCapture_CameraStreamFailed(MediaCapture sender, object args) { AbandonStreaming(); } /// <summary> /// Handles "streaming" button clicks to start/stop webcam streaming. /// </summary> /// <param name="sender">Button user clicked</param> /// <param name="e">Event data</param> private async void CameraStreamingButton_Click(object sender, RoutedEventArgs e) { if (this.currentState == ScenarioState.Streaming) { this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage); await this.ChangeScenarioStateAsync(ScenarioState.Idle); } else { this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage); await this.ChangeScenarioStateAsync(ScenarioState.Streaming); } } } }