context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace AutoMapper.Internal { using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using TypeInfo = AutoMapper.TypeInfo; public class MappingExpression : IMappingExpression, IMemberConfigurationExpression { private readonly TypeMap _typeMap; private readonly Func<Type, object> _typeConverterCtor; private PropertyMap _propertyMap; public MappingExpression(TypeMap typeMap, Func<Type, object> typeConverterCtor) { _typeMap = typeMap; _typeConverterCtor = typeConverterCtor; } public void ConvertUsing<TTypeConverter>() { ConvertUsing(typeof(TTypeConverter)); } public void ConvertUsing(Type typeConverterType) { var interfaceType = typeof(ITypeConverter<,>).MakeGenericType(_typeMap.SourceType, _typeMap.DestinationType); var convertMethodType = interfaceType.IsAssignableFrom(typeConverterType) ? interfaceType : typeConverterType; var converter = new DeferredInstantiatedConverter(convertMethodType, BuildCtor<object>(typeConverterType)); _typeMap.UseCustomMapper(converter.Convert); } public void As(Type typeOverride) { _typeMap.DestinationTypeOverride = typeOverride; } public IMappingExpression WithProfile(string profileName) { _typeMap.Profile = profileName; return this; } public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions) { IMemberAccessor destMember = null; var propertyInfo = _typeMap.DestinationType.GetProperty(name); if (propertyInfo != null) { destMember = new PropertyAccessor(propertyInfo); } if (destMember == null) { var fieldInfo = _typeMap.DestinationType.GetField(name); destMember = new FieldAccessor(fieldInfo); } ForDestinationMember(destMember, memberOptions); return new MappingExpression(_typeMap, _typeConverterCtor); } public IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions) { MemberInfo srcMember = _typeMap.SourceType.GetMember(sourceMemberName).First(); var srcConfig = new SourceMappingExpression(_typeMap, srcMember); memberOptions(srcConfig); return new MappingExpression(_typeMap, _typeConverterCtor); } private void ForDestinationMember(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression> memberOptions) { _propertyMap = _typeMap.FindOrCreatePropertyMapFor(destinationProperty); memberOptions(this); } public void MapFrom(string sourceMember) { var members = _typeMap.SourceType.GetMember(sourceMember); if (!members.Any()) throw new AutoMapperConfigurationException( $"Unable to find source member {sourceMember} on type {_typeMap.SourceType.FullName}"); if (members.Skip(1).Any()) throw new AutoMapperConfigurationException( $"Source member {sourceMember} is ambiguous on type {_typeMap.SourceType.FullName}"); var member = members.Single(); _propertyMap.SourceMember = member; _propertyMap.AssignCustomValueResolver(member.ToMemberGetter()); } public IResolutionExpression ResolveUsing(IValueResolver valueResolver) { _propertyMap.AssignCustomValueResolver(valueResolver); return new ResolutionExpression(_typeMap.SourceType, _propertyMap); } public IResolverConfigurationExpression ResolveUsing(Type valueResolverType) { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(valueResolverType)); ResolveUsing(resolver); return new ResolutionExpression(_typeMap.SourceType, _propertyMap); } public IResolverConfigurationExpression ResolveUsing<TValueResolver>() { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>((typeof(TValueResolver)))); ResolveUsing(resolver); return new ResolutionExpression(_typeMap.SourceType, _propertyMap); } public void Ignore() { _propertyMap.Ignore(); } public void UseDestinationValue() { _propertyMap.UseDestinationValue = true; } private Func<ResolutionContext, TServiceType> BuildCtor<TServiceType>(Type type) { return context => { if(type.IsGenericTypeDefinition()) { type = type.MakeGenericType(context.SourceType.GetGenericArguments()); } var obj = context.Options.ServiceCtor?.Invoke(type); if (obj != null) return (TServiceType)obj; return (TServiceType)_typeConverterCtor(type); }; } private class SourceMappingExpression : ISourceMemberConfigurationExpression { private readonly SourceMemberConfig _sourcePropertyConfig; public SourceMappingExpression(TypeMap typeMap, MemberInfo sourceMember) { _sourcePropertyConfig = typeMap.FindOrCreateSourceMemberConfigFor(sourceMember); } public void Ignore() { _sourcePropertyConfig.Ignore(); } } } public class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, IMemberConfigurationExpression<TSource> { private readonly Func<Type, object> _serviceCtor; private readonly IProfileExpression _configurationContainer; private PropertyMap _propertyMap; public MappingExpression(TypeMap typeMap, Func<Type, object> serviceCtor, IProfileExpression configurationContainer) { TypeMap = typeMap; _serviceCtor = serviceCtor; _configurationContainer = configurationContainer; } public TypeMap TypeMap { get; } public IMappingExpression<TSource, TDestination> ForMember(Expression<Func<TDestination, object>> destinationMember, Action<IMemberConfigurationExpression<TSource>> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(destinationMember); IMemberAccessor destProperty = memberInfo.ToMemberAccessor(); ForDestinationMember(destProperty, memberOptions); return new MappingExpression<TSource, TDestination>(TypeMap, _serviceCtor, _configurationContainer); } public IMappingExpression<TSource, TDestination> ForMember(string name, Action<IMemberConfigurationExpression<TSource>> memberOptions) { IMemberAccessor destMember = null; var propertyInfo = TypeMap.DestinationType.GetProperty(name); if (propertyInfo != null) { destMember = new PropertyAccessor(propertyInfo); } if (destMember == null) { var fieldInfo = TypeMap.DestinationType.GetField(name); if(fieldInfo == null) { throw new ArgumentOutOfRangeException("name", "Cannot find a field or property named " + name); } destMember = new FieldAccessor(fieldInfo); } ForDestinationMember(destMember, memberOptions); return new MappingExpression<TSource, TDestination>(TypeMap, _serviceCtor, _configurationContainer); } public void ForAllMembers(Action<IMemberConfigurationExpression<TSource>> memberOptions) { var typeInfo = new TypeInfo(TypeMap.DestinationType, _configurationContainer.ShouldMapProperty, _configurationContainer.ShouldMapField); typeInfo.PublicWriteAccessors.Each(acc => ForDestinationMember(acc.ToMemberAccessor(), memberOptions)); } public IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter() { var properties = typeof(TDestination).GetDeclaredProperties().Where(HasAnInaccessibleSetter); foreach (var property in properties) ForMember(property.Name, opt => opt.Ignore()); return new MappingExpression<TSource, TDestination>(TypeMap, _serviceCtor, _configurationContainer); } public IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter() { var properties = typeof(TSource).GetDeclaredProperties().Where(HasAnInaccessibleSetter); foreach (var property in properties) ForSourceMember(property.Name, opt => opt.Ignore()); return new MappingExpression<TSource, TDestination>(TypeMap, _serviceCtor, _configurationContainer); } private bool HasAnInaccessibleSetter(PropertyInfo property) { var setMethod = property.GetSetMethod(true); return setMethod == null || setMethod.IsPrivate || setMethod.IsFamily; } public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>() where TOtherSource : TSource where TOtherDestination : TDestination { return Include(typeof(TOtherSource), typeof(TOtherDestination)); } public IMappingExpression<TSource, TDestination> Include(Type otherSourceType, Type otherDestinationType) { TypeMap.IncludeDerivedTypes(otherSourceType, otherDestinationType); return this; } public IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>() { TypeMap baseTypeMap = _configurationContainer.CreateMap<TSourceBase, TDestinationBase>().TypeMap; baseTypeMap.IncludeDerivedTypes(typeof(TSource), typeof(TDestination)); TypeMap.ApplyInheritedMap(baseTypeMap); return this; } public IMappingExpression<TSource, TDestination> WithProfile(string profileName) { TypeMap.Profile = profileName; return this; } public void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression) { TypeMap.UseCustomProjection(projectionExpression); } public void NullSubstitute(object nullSubstitute) { _propertyMap.SetNullSubstitute(nullSubstitute); } public IResolverConfigurationExpression<TSource, TValueResolver> ResolveUsing<TValueResolver>() where TValueResolver : IValueResolver { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(typeof(TValueResolver))); ResolveUsing(resolver); return new ResolutionExpression<TSource, TValueResolver>(_propertyMap); } public IResolverConfigurationExpression<TSource> ResolveUsing(Type valueResolverType) { var resolver = new DeferredInstantiatedResolver(BuildCtor<IValueResolver>(valueResolverType)); ResolveUsing(resolver); return new ResolutionExpression<TSource>(_propertyMap); } public IResolutionExpression<TSource> ResolveUsing(IValueResolver valueResolver) { _propertyMap.AssignCustomValueResolver(valueResolver); return new ResolutionExpression<TSource>(_propertyMap); } public void ResolveUsing(Func<TSource, object> resolver) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(r => resolver((TSource)r.Value))); } public void ResolveUsing(Func<ResolutionResult, object> resolver) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(resolver)); } public void MapFrom<TMember>(Expression<Func<TSource, TMember>> sourceMember) { _propertyMap.SetCustomValueResolverExpression(sourceMember); } public void MapFrom<TMember>(string property) { var par = Expression.Parameter(typeof (TSource)); var prop = Expression.Property(par, property); var lambda = Expression.Lambda<Func<TSource, TMember>>(prop, par); _propertyMap.SetCustomValueResolverExpression(lambda); } public void UseValue<TValue>(TValue value) { MapFrom(src => value); } public void UseValue(object value) { _propertyMap.AssignCustomValueResolver(new DelegateBasedResolver<TSource>(src => value)); } public void Condition(Func<TSource, bool> condition) { Condition(context => condition((TSource)context.Parent.SourceValue)); } public void Condition(Func<ResolutionContext, bool> condition) { _propertyMap.ApplyCondition(condition); } public void PreCondition(Func<TSource, bool> condition) { PreCondition(context => condition((TSource)context.Parent.SourceValue)); } public void PreCondition(Func<ResolutionContext, bool> condition) { _propertyMap.ApplyPreCondition(condition); } public void ExplicitExpansion() { _propertyMap.ExplicitExpansion = true; } public IMappingExpression<TSource, TDestination> MaxDepth(int depth) { TypeMap.MaxDepth = depth; return this; } public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator() { TypeMap.ConstructDestinationUsingServiceLocator = true; return this; } public IMappingExpression<TDestination, TSource> ReverseMap() { var mappingExpression = _configurationContainer.CreateMap<TDestination, TSource>(MemberList.Source); foreach (var destProperty in TypeMap.GetPropertyMaps().Where(pm => pm.IsIgnored())) { mappingExpression.ForSourceMember(destProperty.DestinationProperty.Name, opt => opt.Ignore()); } foreach (var includedDerivedType in TypeMap.IncludedDerivedTypes) { mappingExpression.Include(includedDerivedType.DestinationType, includedDerivedType.SourceType); } return mappingExpression; } public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression<TSource>> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(sourceMember); var srcConfig = new SourceMappingExpression(TypeMap, memberInfo); memberOptions(srcConfig); return this; } public IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression<TSource>> memberOptions) { var memberInfo = TypeMap.SourceType.GetMember(sourceMemberName).First(); var srcConfig = new SourceMappingExpression(TypeMap, memberInfo); memberOptions(srcConfig); return this; } public IMappingExpression<TSource, TDestination> Substitute(Func<TSource, object> substituteFunc) { TypeMap.Substitution = src => substituteFunc((TSource) src); return this; } public void Ignore() { _propertyMap.Ignore(); } public void UseDestinationValue() { _propertyMap.UseDestinationValue = true; } public void DoNotUseDestinationValue() { _propertyMap.UseDestinationValue = false; } public void SetMappingOrder(int mappingOrder) { _propertyMap.SetMappingOrder(mappingOrder); } public void ConvertUsing(Func<TSource, TDestination> mappingFunction) { TypeMap.UseCustomMapper(source => mappingFunction((TSource)source.SourceValue)); } public void ConvertUsing(Func<ResolutionContext, TDestination> mappingFunction) { TypeMap.UseCustomMapper(context => mappingFunction(context)); } public void ConvertUsing(Func<ResolutionContext, TSource, TDestination> mappingFunction) { TypeMap.UseCustomMapper(source => mappingFunction(source, (TSource)source.SourceValue)); } public void ConvertUsing(ITypeConverter<TSource, TDestination> converter) { ConvertUsing(converter.Convert); } public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination> { var converter = new DeferredInstantiatedConverter<TSource, TDestination>(BuildCtor<ITypeConverter<TSource, TDestination>>(typeof(TTypeConverter))); ConvertUsing(converter.Convert); } public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction) { TypeMap.AddBeforeMapAction((src, dest) => beforeFunction((TSource)src, (TDestination)dest)); return this; } public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { Action<TSource, TDestination> beforeFunction = (src, dest) => ((TMappingAction)_serviceCtor(typeof(TMappingAction))).Process(src, dest); return BeforeMap(beforeFunction); } public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction) { TypeMap.AddAfterMapAction((src, dest) => afterFunction((TSource)src, (TDestination)dest)); return this; } public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { Action<TSource, TDestination> afterFunction = (src, dest) => ((TMappingAction)_serviceCtor(typeof(TMappingAction))).Process(src, dest); return AfterMap(afterFunction); } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor) { return ConstructUsing(ctxt => ctor((TSource)ctxt.SourceValue)); } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor) { TypeMap.DestinationCtor = ctxt => ctor(ctxt); return this; } public IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor) { var func = ctor.Compile(); TypeMap.ConstructExpression = ctor; return ConstructUsing(ctxt => func((TSource)ctxt.SourceValue)); } private void ForDestinationMember(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression<TSource>> memberOptions) { _propertyMap = TypeMap.FindOrCreatePropertyMapFor(destinationProperty); memberOptions(this); } public void As<T>() { TypeMap.DestinationTypeOverride = typeof(T); } public IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions) { var param = TypeMap.ConstructorMap.CtorParams.Single(p => p.Parameter.Name == ctorParamName); var ctorParamExpression = new CtorParamConfigurationExpression<TSource>(param); param.CanResolve = true; paramOptions(ctorParamExpression); return this; } private Func<ResolutionContext, TServiceType> BuildCtor<TServiceType>(Type type) { return context => { var obj = context.Options.ServiceCtor?.Invoke(type); if (obj != null) return (TServiceType)obj; return (TServiceType)_serviceCtor(type); }; } private class SourceMappingExpression : ISourceMemberConfigurationExpression<TSource> { private readonly SourceMemberConfig _sourcePropertyConfig; public SourceMappingExpression(TypeMap typeMap, MemberInfo memberInfo) { _sourcePropertyConfig = typeMap.FindOrCreateSourceMemberConfigFor(memberInfo); } public void Ignore() { _sourcePropertyConfig.Ignore(); } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using Moq; using Xunit; namespace Avalonia.Base.UnitTests { public class PriorityValueTests { private static readonly AvaloniaProperty TestProperty = new StyledProperty<string>( "Test", typeof(PriorityValueTests), new StyledPropertyMetadata<string>()); [Fact] public void Initial_Value_Should_Be_UnsetValue() { var target = new PriorityValue(null, TestProperty, typeof(string)); Assert.Same(AvaloniaProperty.UnsetValue, target.Value); } [Fact] public void First_Binding_Sets_Value() { var target = new PriorityValue(null, TestProperty, typeof(string)); target.Add(Single("foo"), 0); Assert.Equal("foo", target.Value); } [Fact] public void Changing_Binding_Should_Set_Value() { var target = new PriorityValue(null, TestProperty, typeof(string)); var subject = new BehaviorSubject<string>("foo"); target.Add(subject, 0); Assert.Equal("foo", target.Value); subject.OnNext("bar"); Assert.Equal("bar", target.Value); } [Fact] public void Setting_Direct_Value_Should_Override_Binding() { var target = new PriorityValue(null, TestProperty, typeof(string)); target.Add(Single("foo"), 0); target.SetValue("bar", 0); Assert.Equal("bar", target.Value); } [Fact] public void Binding_Firing_Should_Override_Direct_Value() { var target = new PriorityValue(null, TestProperty, typeof(string)); var source = new BehaviorSubject<object>("initial"); target.Add(source, 0); Assert.Equal("initial", target.Value); target.SetValue("first", 0); Assert.Equal("first", target.Value); source.OnNext("second"); Assert.Equal("second", target.Value); } [Fact] public void Earlier_Binding_Firing_Should_Not_Override_Later() { var target = new PriorityValue(null, TestProperty, typeof(string)); var nonActive = new BehaviorSubject<object>("na"); var source = new BehaviorSubject<object>("initial"); target.Add(nonActive, 1); target.Add(source, 1); Assert.Equal("initial", target.Value); target.SetValue("first", 1); Assert.Equal("first", target.Value); nonActive.OnNext("second"); Assert.Equal("first", target.Value); } [Fact] public void Binding_Completing_Should_Revert_To_Direct_Value() { var target = new PriorityValue(null, TestProperty, typeof(string)); var source = new BehaviorSubject<object>("initial"); target.Add(source, 0); Assert.Equal("initial", target.Value); target.SetValue("first", 0); Assert.Equal("first", target.Value); source.OnNext("second"); Assert.Equal("second", target.Value); source.OnCompleted(); Assert.Equal("first", target.Value); } [Fact] public void Binding_With_Lower_Priority_Has_Precedence() { var target = new PriorityValue(null, TestProperty, typeof(string)); target.Add(Single("foo"), 1); target.Add(Single("bar"), 0); target.Add(Single("baz"), 1); Assert.Equal("bar", target.Value); } [Fact] public void Later_Binding_With_Same_Priority_Should_Take_Precedence() { var target = new PriorityValue(null, TestProperty, typeof(string)); target.Add(Single("foo"), 1); target.Add(Single("bar"), 0); target.Add(Single("baz"), 0); target.Add(Single("qux"), 1); Assert.Equal("baz", target.Value); } [Fact] public void Changing_Binding_With_Lower_Priority_Should_Set_Not_Value() { var target = new PriorityValue(null, TestProperty, typeof(string)); var subject = new BehaviorSubject<string>("bar"); target.Add(Single("foo"), 0); target.Add(subject, 1); Assert.Equal("foo", target.Value); subject.OnNext("baz"); Assert.Equal("foo", target.Value); } [Fact] public void UnsetValue_Should_Fall_Back_To_Next_Binding() { var target = new PriorityValue(null, TestProperty, typeof(string)); var subject = new BehaviorSubject<object>("bar"); target.Add(subject, 0); target.Add(Single("foo"), 1); Assert.Equal("bar", target.Value); subject.OnNext(AvaloniaProperty.UnsetValue); Assert.Equal("foo", target.Value); } [Fact] public void Adding_Value_Should_Call_OnNext() { var owner = new Mock<IPriorityValueOwner>(); var target = new PriorityValue(owner.Object, TestProperty, typeof(string)); target.Add(Single("foo"), 0); owner.Verify(x => x.Changed(target, AvaloniaProperty.UnsetValue, "foo")); } [Fact] public void Changing_Value_Should_Call_OnNext() { var owner = new Mock<IPriorityValueOwner>(); var target = new PriorityValue(owner.Object, TestProperty, typeof(string)); var subject = new BehaviorSubject<object>("foo"); target.Add(subject, 0); subject.OnNext("bar"); owner.Verify(x => x.Changed(target, "foo", "bar")); } [Fact] public void Disposing_A_Binding_Should_Revert_To_Next_Value() { var target = new PriorityValue(null, TestProperty, typeof(string)); target.Add(Single("foo"), 0); var disposable = target.Add(Single("bar"), 0); Assert.Equal("bar", target.Value); disposable.Dispose(); Assert.Equal("foo", target.Value); } [Fact] public void Disposing_A_Binding_Should_Remove_BindingEntry() { var target = new PriorityValue(null, TestProperty, typeof(string)); target.Add(Single("foo"), 0); var disposable = target.Add(Single("bar"), 0); Assert.Equal(2, target.GetBindings().Count()); disposable.Dispose(); Assert.Equal(1, target.GetBindings().Count()); } [Fact] public void Completing_A_Binding_Should_Revert_To_Previous_Binding() { var target = new PriorityValue(null, TestProperty, typeof(string)); var source = new BehaviorSubject<object>("bar"); target.Add(Single("foo"), 0); target.Add(source, 0); Assert.Equal("bar", target.Value); source.OnCompleted(); Assert.Equal("foo", target.Value); } [Fact] public void Completing_A_Binding_Should_Revert_To_Lower_Priority() { var target = new PriorityValue(null, TestProperty, typeof(string)); var source = new BehaviorSubject<object>("bar"); target.Add(Single("foo"), 1); target.Add(source, 0); Assert.Equal("bar", target.Value); source.OnCompleted(); Assert.Equal("foo", target.Value); } [Fact] public void Completing_A_Binding_Should_Remove_BindingEntry() { var target = new PriorityValue(null, TestProperty, typeof(string)); var subject = new BehaviorSubject<object>("bar"); target.Add(Single("foo"), 0); target.Add(subject, 0); Assert.Equal(2, target.GetBindings().Count()); subject.OnCompleted(); Assert.Equal(1, target.GetBindings().Count()); } [Fact] public void Direct_Value_Should_Be_Coerced() { var target = new PriorityValue(null, TestProperty, typeof(int), x => Math.Min((int)x, 10)); target.SetValue(5, 0); Assert.Equal(5, target.Value); target.SetValue(15, 0); Assert.Equal(10, target.Value); } [Fact] public void Bound_Value_Should_Be_Coerced() { var target = new PriorityValue(null, TestProperty, typeof(int), x => Math.Min((int)x, 10)); var source = new Subject<object>(); target.Add(source, 0); source.OnNext(5); Assert.Equal(5, target.Value); source.OnNext(15); Assert.Equal(10, target.Value); } [Fact] public void Revalidate_Should_ReCoerce_Value() { var max = 10; var target = new PriorityValue(null, TestProperty, typeof(int), x => Math.Min((int)x, max)); var source = new Subject<object>(); target.Add(source, 0); source.OnNext(5); Assert.Equal(5, target.Value); source.OnNext(15); Assert.Equal(10, target.Value); max = 12; target.Revalidate(); Assert.Equal(12, target.Value); } /// <summary> /// Returns an observable that returns a single value but does not complete. /// </summary> /// <typeparam name="T">The type of the observable.</typeparam> /// <param name="value">The value.</param> /// <returns>The observable.</returns> private IObservable<T> Single<T>(T value) { return Observable.Never<T>().StartWith(value); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Model = Discord.API.Channel; namespace Discord.Rest { /// <summary> /// Represents a REST-based channel in a guild that can send and receive messages. /// </summary> [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class RestTextChannel : RestGuildChannel, IRestMessageChannel, ITextChannel { /// <inheritdoc /> public string Topic { get; private set; } /// <inheritdoc /> public virtual int SlowModeInterval { get; private set; } /// <inheritdoc /> public ulong? CategoryId { get; private set; } /// <inheritdoc /> public string Mention => MentionUtils.MentionChannel(Id); /// <inheritdoc /> public bool IsNsfw { get; private set; } internal RestTextChannel(BaseDiscordClient discord, IGuild guild, ulong id) : base(discord, guild, id) { } internal new static RestTextChannel Create(BaseDiscordClient discord, IGuild guild, Model model) { var entity = new RestTextChannel(discord, guild, model.Id); entity.Update(model); return entity; } /// <inheritdoc /> internal override void Update(Model model) { base.Update(model); CategoryId = model.CategoryId; Topic = model.Topic.Value; SlowModeInterval = model.SlowMode.Value; IsNsfw = model.Nsfw.GetValueOrDefault(); } /// <inheritdoc /> public async Task ModifyAsync(Action<TextChannelProperties> func, RequestOptions options = null) { var model = await ChannelHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false); Update(model); } /// <summary> /// Gets a user in this channel. /// </summary> /// <param name="id">The snowflake identifier of the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <exception cref="InvalidOperationException"> /// Resolving permissions requires the parent guild to be downloaded. /// </exception> /// <returns> /// A task representing the asynchronous get operation. The task result contains a guild user object that /// represents the user; <c>null</c> if none is found. /// </returns> public Task<RestGuildUser> GetUserAsync(ulong id, RequestOptions options = null) => ChannelHelper.GetUserAsync(this, Guild, Discord, id, options); /// <summary> /// Gets a collection of users that are able to view the channel. /// </summary> /// <param name="options">The options to be used when sending the request.</param> /// <exception cref="InvalidOperationException"> /// Resolving permissions requires the parent guild to be downloaded. /// </exception> /// <returns> /// A paged collection containing a collection of guild users that can access this channel. Flattening the /// paginated response into a collection of users with /// <see cref="AsyncEnumerableExtensions.FlattenAsync{T}"/> is required if you wish to access the users. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<RestGuildUser>> GetUsersAsync(RequestOptions options = null) => ChannelHelper.GetUsersAsync(this, Guild, Discord, null, null, options); /// <inheritdoc /> public Task<RestMessage> GetMessageAsync(ulong id, RequestOptions options = null) => ChannelHelper.GetMessageAsync(this, Discord, id, options); /// <inheritdoc /> public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => ChannelHelper.GetMessagesAsync(this, Discord, null, Direction.Before, limit, options); /// <inheritdoc /> public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => ChannelHelper.GetMessagesAsync(this, Discord, fromMessageId, dir, limit, options); /// <inheritdoc /> public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => ChannelHelper.GetMessagesAsync(this, Discord, fromMessage.Id, dir, limit, options); /// <inheritdoc /> public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null) => ChannelHelper.GetPinnedMessagesAsync(this, Discord, options); /// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null) => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, options); /// <inheritdoc /> /// <exception cref="ArgumentException"> /// <paramref name="filePath" /> is a zero-length string, contains only white space, or contains one or more /// invalid characters as defined by <see cref="System.IO.Path.GetInvalidPathChars"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="filePath" /> is <c>null</c>. /// </exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum length. For example, on /// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 /// characters. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// The specified path is invalid, (for example, it is on an unmapped drive). /// </exception> /// <exception cref="UnauthorizedAccessException"> /// <paramref name="filePath" /> specified a directory.-or- The caller does not have the required permission. /// </exception> /// <exception cref="FileNotFoundException"> /// The file specified in <paramref name="filePath" /> was not found. /// </exception> /// <exception cref="NotSupportedException"><paramref name="filePath" /> is in an invalid format.</exception> /// <exception cref="IOException">An I/O error occurred while opening the file.</exception> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false) => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, options, isSpoiler); /// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false) => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options, isSpoiler); /// <inheritdoc /> public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options); /// <inheritdoc /> public Task DeleteMessageAsync(IMessage message, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options); /// <inheritdoc /> public Task DeleteMessagesAsync(IEnumerable<IMessage> messages, RequestOptions options = null) => ChannelHelper.DeleteMessagesAsync(this, Discord, messages.Select(x => x.Id), options); /// <inheritdoc /> public Task DeleteMessagesAsync(IEnumerable<ulong> messageIds, RequestOptions options = null) => ChannelHelper.DeleteMessagesAsync(this, Discord, messageIds, options); /// <inheritdoc /> public Task TriggerTypingAsync(RequestOptions options = null) => ChannelHelper.TriggerTypingAsync(this, Discord, options); /// <inheritdoc /> public IDisposable EnterTypingState(RequestOptions options = null) => ChannelHelper.EnterTypingState(this, Discord, options); /// <summary> /// Creates a webhook in this text channel. /// </summary> /// <param name="name">The name of the webhook.</param> /// <param name="avatar">The avatar of the webhook.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous creation operation. The task result contains the newly created /// webhook. /// </returns> public Task<RestWebhook> CreateWebhookAsync(string name, Stream avatar = null, RequestOptions options = null) => ChannelHelper.CreateWebhookAsync(this, Discord, name, avatar, options); /// <summary> /// Gets a webhook available in this text channel. /// </summary> /// <param name="id">The identifier of the webhook.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous get operation. The task result contains a webhook associated /// with the identifier; <c>null</c> if the webhook is not found. /// </returns> public Task<RestWebhook> GetWebhookAsync(ulong id, RequestOptions options = null) => ChannelHelper.GetWebhookAsync(this, Discord, id, options); /// <summary> /// Gets the webhooks available in this text channel. /// </summary> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous get operation. The task result contains a read-only collection /// of webhooks that is available in this channel. /// </returns> public Task<IReadOnlyCollection<RestWebhook>> GetWebhooksAsync(RequestOptions options = null) => ChannelHelper.GetWebhooksAsync(this, Discord, options); /// <summary> /// Gets the parent (category) channel of this channel. /// </summary> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous get operation. The task result contains the category channel /// representing the parent of this channel; <c>null</c> if none is set. /// </returns> public Task<ICategoryChannel> GetCategoryAsync(RequestOptions options = null) => ChannelHelper.GetCategoryAsync(this, Discord, options); /// <inheritdoc /> public Task SyncPermissionsAsync(RequestOptions options = null) => ChannelHelper.SyncPermissionsAsync(this, Discord, options); //Invites /// <inheritdoc /> public async Task<IInviteMetadata> CreateInviteAsync(int? maxAge = 86400, int? maxUses = null, bool isTemporary = false, bool isUnique = false, RequestOptions options = null) => await ChannelHelper.CreateInviteAsync(this, Discord, maxAge, maxUses, isTemporary, isUnique, options).ConfigureAwait(false); /// <inheritdoc /> public async Task<IReadOnlyCollection<IInviteMetadata>> GetInvitesAsync(RequestOptions options = null) => await ChannelHelper.GetInvitesAsync(this, Discord, options).ConfigureAwait(false); private string DebuggerDisplay => $"{Name} ({Id}, Text)"; //ITextChannel /// <inheritdoc /> async Task<IWebhook> ITextChannel.CreateWebhookAsync(string name, Stream avatar, RequestOptions options) => await CreateWebhookAsync(name, avatar, options).ConfigureAwait(false); /// <inheritdoc /> async Task<IWebhook> ITextChannel.GetWebhookAsync(ulong id, RequestOptions options) => await GetWebhookAsync(id, options).ConfigureAwait(false); /// <inheritdoc /> async Task<IReadOnlyCollection<IWebhook>> ITextChannel.GetWebhooksAsync(RequestOptions options) => await GetWebhooksAsync(options).ConfigureAwait(false); //IMessageChannel /// <inheritdoc /> async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return await GetMessageAsync(id, options).ConfigureAwait(false); else return null; } /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return GetMessagesAsync(limit, options); else return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>(); } /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return GetMessagesAsync(fromMessageId, dir, limit, options); else return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>(); } /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return GetMessagesAsync(fromMessage, dir, limit, options); else return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>(); } /// <inheritdoc /> async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler) => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler) => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options) => await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false); //IGuildChannel /// <inheritdoc /> async Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return await GetUserAsync(id, options).ConfigureAwait(false); else return null; } /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return GetUsersAsync(options); else return AsyncEnumerable.Empty<IReadOnlyCollection<IGuildUser>>(); } //IChannel /// <inheritdoc /> async Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return await GetUserAsync(id, options).ConfigureAwait(false); else return null; } /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return GetUsersAsync(options); else return AsyncEnumerable.Empty<IReadOnlyCollection<IGuildUser>>(); } // INestedChannel /// <inheritdoc /> async Task<ICategoryChannel> INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options) { if (CategoryId.HasValue && mode == CacheMode.AllowDownload) return (await Guild.GetChannelAsync(CategoryId.Value, mode, options).ConfigureAwait(false)) as ICategoryChannel; return null; } } }
/* * Copyright (C) 2007-2014 ARGUS TV * http://www.argus-tv.com * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using ArgusTV.DataContracts; namespace ArgusTV.ServiceProxy { /// <exclude /> public abstract class RestProxyBase { private string _module; /// <exclude /> private HttpClient _client; /// <exclude /> public RestProxyBase(string module) { _module = module; _client = CreateHttpClient(); } /// <exclude /> protected HttpClient CreateHttpClient() { var url = (Proxies.ServerSettings.Transport == ServiceTransport.Https ? "https://" : "http://") + Proxies.ServerSettings.ServerName + ":" + Proxies.ServerSettings.Port + "/ArgusTV/" + _module + "/"; HttpClientHandler handler = new HttpClientHandler { Proxy = WebRequest.DefaultWebProxy, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; handler.Proxy.Credentials = CredentialCache.DefaultCredentials; HttpClient client = new HttpClient(handler, true) { BaseAddress = new Uri(url) }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); if (Proxies.ServerSettings.Transport == ServiceTransport.Https) { byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(Proxies.ServerSettings.UserName + ":" + Proxies.ServerSettings.Password); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); } return client; } /// <exclude /> internal class SchedulerJsonSerializerStrategy : PocoJsonSerializerStrategy { private static readonly long _initialJavaScriptDateTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks; private static readonly DateTime _minimumJavaScriptDate = new DateTime(100, 1, 1, 0, 0, 0, DateTimeKind.Utc); /// <exclude /> public override object DeserializeObject(object value, Type type) { bool isString = value is string; Type valueType = null; bool isEnum = type.IsEnum || (IsNullable(type, out valueType) && valueType.IsEnum); if (isEnum && (isString || value is Int32 || value is Int64)) { if (!isString || Enum.IsDefined(valueType ?? type, value)) { return Enum.Parse(valueType ?? type, value.ToString()); } } else if (type == typeof(DateTime) || type == typeof(DateTime?)) { var s = value as string; if (s != null && s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal)) { int tzCharIndex = s.IndexOfAny(new char[] { '+', '-' }, 7); long javaScriptTicks = Convert.ToInt64(s.Substring(6, (tzCharIndex > 0) ? tzCharIndex - 6 : s.Length - 8)); DateTime time = new DateTime((javaScriptTicks * 10000) + _initialJavaScriptDateTicks, DateTimeKind.Utc); if (tzCharIndex > 0) { time = time.ToLocalTime(); } return time; } } else if (type == typeof(ServiceEvent)) { var jsonObject = (JsonObject)value; var @event = new ServiceEvent() { Name = (string)jsonObject["Name"], Time = (DateTime)DeserializeObject(jsonObject["Time"], typeof(DateTime)) }; var args = (JsonArray)jsonObject["Arguments"]; if (args != null) { List<object> arguments = new List<object>(); switch (@event.Name) { case DataContracts.ServiceEventNames.ConfigurationChanged: arguments.Add(DeserializeObject(args[0], typeof(string))); arguments.Add(DeserializeObject(args[1], typeof(string))); break; case DataContracts.ServiceEventNames.ScheduleChanged: arguments.Add(DeserializeObject(args[0], typeof(Guid))); arguments.Add(DeserializeObject(args[1], typeof(int))); break; case DataContracts.ServiceEventNames.RecordingStarted: case DataContracts.ServiceEventNames.RecordingEnded: arguments.Add(DeserializeObject(args[0], typeof(Recording))); break; case DataContracts.ServiceEventNames.LiveStreamStarted: case DataContracts.ServiceEventNames.LiveStreamTuned: case DataContracts.ServiceEventNames.LiveStreamEnded: case DataContracts.ServiceEventNames.LiveStreamAborted: arguments.Add(DeserializeObject(args[0], typeof(LiveStream))); if (@event.Name == DataContracts.ServiceEventNames.LiveStreamAborted) { arguments.Add(DeserializeObject(args[1], typeof(LiveStreamAbortReason))); arguments.Add(DeserializeObject(args[2], typeof(UpcomingProgram))); } break; default: foreach (JsonObject arg in args) { arguments.Add(arg); } break; } @event.Arguments = arguments.ToArray(); } return @event; } return base.DeserializeObject(value, type); } /// <exclude /> protected override bool TrySerializeKnownTypes(object input, out object output) { if (input is DateTime) { DateTime value = (DateTime)input; DateTime time = value.ToUniversalTime(); string suffix = ""; if (value.Kind != DateTimeKind.Utc) { TimeSpan localTZOffset; if (value >= time) { localTZOffset = value - time; suffix = "+"; } else { localTZOffset = time - value; suffix = "-"; } suffix += localTZOffset.ToString("hhmm"); } if (time < _minimumJavaScriptDate) { time = _minimumJavaScriptDate; } long ticks = (time.Ticks - _initialJavaScriptDateTicks) / (long)10000; output = "/Date(" + ticks + suffix + ")/"; return true; } return base.TrySerializeKnownTypes(input, out output); } private static bool IsNullable(Type type, out Type valueType) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { valueType = type.GetGenericArguments()[0]; return true; } valueType = null; return false; } } /// <exclude /> protected HttpRequestMessage NewRequest(HttpMethod method, string url, params object[] args) { if (url.StartsWith("/")) { url = url.Substring(1); } if (args != null && args.Length > 0) { List<object> encodedArgs = new List<object>(); foreach (var arg in args) { string urlArg; if (arg is DateTime) { DateTime time = (DateTime)arg; if (time.Kind == DateTimeKind.Unspecified) { urlArg = new DateTime(time.Ticks, DateTimeKind.Local).ToString("o"); } urlArg = time.ToString("o"); } else { urlArg = arg.ToString(); } encodedArgs.Add(HttpUtility.UrlEncode(urlArg)); } return new HttpRequestMessage(method, String.Format(url, encodedArgs.ToArray())); } return new HttpRequestMessage(method, url); } /// <exclude /> protected bool IsConnectionError(Exception ex) { var requestException = ex as HttpRequestException; if (requestException != null) { var webException = requestException.InnerException as WebException; if (webException != null) { switch (webException.Status) { case System.Net.WebExceptionStatus.ConnectFailure: case System.Net.WebExceptionStatus.NameResolutionFailure: case System.Net.WebExceptionStatus.ProxyNameResolutionFailure: case System.Net.WebExceptionStatus.RequestProhibitedByProxy: case System.Net.WebExceptionStatus.SecureChannelFailure: case System.Net.WebExceptionStatus.TrustFailure: return true; } } } return false; } /// <exclude /> protected async Task ExecuteAsync(HttpRequestMessage request, bool logError = true) { try { using (var response = await ExecuteRequestAsync(request, logError).ConfigureAwait(false)) { } } finally { request.Dispose(); } } /// <exclude /> protected async Task<T> ExecuteAsync<T>(HttpRequestMessage request, bool logError = true) where T : new() { try { using (var response = await ExecuteRequestAsync(request, logError).ConfigureAwait(false)) { return await DeserializeResponseContentAsync<T>(response).ConfigureAwait(false); } } catch (ArgusTVException) { throw; } catch (Exception ex) { if (logError) { Proxies.Logger.Error(ex.ToString()); } throw new ArgusTVUnexpectedErrorException("An unexpected error occured."); } finally { request.Dispose(); } } /// <exclude/> protected async Task<HttpResponseMessage> ExecuteRequestAsync(HttpRequestMessage request, bool logError = true) { try { if (request.Method != HttpMethod.Get && request.Content == null) { // Work around current Mono bug. request.Content = new ByteArrayContent(new byte[0]); } var response = await _client.SendAsync(request).ConfigureAwait(false); if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError) { var error = SimpleJson.DeserializeObject<RestError>(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); throw new ArgusTVException(error.detail); } if (response.StatusCode >= HttpStatusCode.BadRequest) { throw new ArgusTVException(response.ReasonPhrase); } return response; } catch (AggregateException ex) { if (IsConnectionError(ex.InnerException)) { WakeOnLan.EnsureServerAwake(Proxies.ServerSettings); throw new ArgusTVNotFoundException(ex.InnerException.InnerException.Message); } throw; } catch (ArgusTVException) { throw; } catch (Exception ex) { if (logError) { Proxies.Logger.Error(ex.ToString()); } throw new ArgusTVUnexpectedErrorException("An unexpected error occured."); } } /// <exclude /> protected async static Task<T> DeserializeResponseContentAsync<T>(HttpResponseMessage response) where T : new() { string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (String.IsNullOrEmpty(content)) { return default(T); } return SimpleJson.DeserializeObject<T>(content, new SchedulerJsonSerializerStrategy()); } private class RestError { public string detail { get; set; } } } /// <exclude /> public static class HttpRequestMessageExtensions { /// <exclude /> public static void AddBody(this HttpRequestMessage request, object body) { request.Content = new StringContent( SimpleJson.SerializeObject(body, new RestProxyBase.SchedulerJsonSerializerStrategy()), Encoding.UTF8, "application/json"); } /// <exclude /> public static void AddParameter(this HttpRequestMessage request, string name, object value) { string url = request.RequestUri.OriginalString; url += (url.Contains("?") ? "&" : "?") + name + "=" + HttpUtility.UrlEncode(value.ToString()); request.RequestUri = new Uri(url, UriKind.Relative); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using log4net; using OpenMetaverse; namespace OpenSim.Framework.Console { public class ConsoleUtil { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const int LocalIdNotFound = 0; /// <summary> /// Used by modules to display stock co-ordinate help, though possibly this should be under some general section /// rather than in each help summary. /// </summary> public const string CoordHelp = @"Each component of the coord is comma separated. There must be no spaces between the commas. If you don't care about the z component you can simply omit it. If you don't care about the x or y components then you can leave them blank (though a comma is still required) If you want to specify the maximum value of a component then you can use ~ instead of a number If you want to specify the minimum value of a component then you can use -~ instead of a number e.g. show object pos 20,20,20 to 40,40,40 delete object pos 20,20 to 40,40 show object pos ,20,20 to ,40,40 delete object pos ,,30 to ,,~ show object pos ,,-~ to ,,30"; public const string MinRawConsoleVectorValue = "-~"; public const string MaxRawConsoleVectorValue = "~"; public const string VectorSeparator = ","; public static char[] VectorSeparatorChars = VectorSeparator.ToCharArray(); /// <summary> /// Check if the given file path exists. /// </summary> /// <remarks>If not, warning is printed to the given console.</remarks> /// <returns>true if the file does not exist, false otherwise.</returns> /// <param name='console'></param> /// <param name='path'></param> public static bool CheckFileDoesNotExist(ICommandConsole console, string path) { if (File.Exists(path)) { console.OutputFormat("File {0} already exists. Please move or remove it.", path); return false; } return true; } /// <summary> /// Try to parse a console UUID from the console. /// </summary> /// <remarks> /// Will complain to the console if parsing fails. /// </remarks> /// <returns></returns> /// <param name='console'>If null then no complaint is printed.</param> /// <param name='rawUuid'></param> /// <param name='uuid'></param> public static bool TryParseConsoleUuid(ICommandConsole console, string rawUuid, out UUID uuid) { if (!UUID.TryParse(rawUuid, out uuid)) { if (console != null) console.OutputFormat("ERROR: {0} is not a valid uuid", rawUuid); return false; } return true; } public static bool TryParseConsoleLocalId(ICommandConsole console, string rawLocalId, out uint localId) { if (!uint.TryParse(rawLocalId, out localId)) { if (console != null) console.OutputFormat("ERROR: {0} is not a valid local id", localId); return false; } if (localId == 0) { if (console != null) console.OutputFormat("ERROR: {0} is not a valid local id - it must be greater than 0", localId); return false; } return true; } /// <summary> /// Tries to parse the input as either a UUID or a local ID. /// </summary> /// <returns>true if parsing succeeded, false otherwise.</returns> /// <param name='console'></param> /// <param name='rawId'></param> /// <param name='uuid'></param> /// <param name='localId'> /// Will be set to ConsoleUtil.LocalIdNotFound if parsing result was a UUID or no parse succeeded. /// </param> public static bool TryParseConsoleId(ICommandConsole console, string rawId, out UUID uuid, out uint localId) { if (TryParseConsoleUuid(null, rawId, out uuid)) { localId = LocalIdNotFound; return true; } if (TryParseConsoleLocalId(null, rawId, out localId)) { return true; } if (console != null) console.OutputFormat("ERROR: {0} is not a valid UUID or local id", rawId); return false; } /// <summary> /// Convert a console integer to an int, automatically complaining if a console is given. /// </summary> /// <param name='console'>Can be null if no console is available.</param> /// <param name='rawConsoleVector'>/param> /// <param name='vector'></param> /// <returns></returns> public static bool TryParseConsoleBool(ICommandConsole console, string rawConsoleString, out bool b) { if (!bool.TryParse(rawConsoleString, out b)) { if (console != null) console.OutputFormat("ERROR: {0} is not a true or false value", rawConsoleString); return false; } return true; } /// <summary> /// Convert a console integer to an int, automatically complaining if a console is given. /// </summary> /// <param name='console'>Can be null if no console is available.</param> /// <param name='rawConsoleInt'>/param> /// <param name='i'></param> /// <returns></returns> public static bool TryParseConsoleInt(ICommandConsole console, string rawConsoleInt, out int i) { if (!int.TryParse(rawConsoleInt, out i)) { if (console != null) console.OutputFormat("ERROR: {0} is not a valid integer", rawConsoleInt); return false; } return true; } /// <summary> /// Convert a console integer to a natural int, automatically complaining if a console is given. /// </summary> /// <param name='console'>Can be null if no console is available.</param> /// <param name='rawConsoleInt'>/param> /// <param name='i'></param> /// <returns></returns> public static bool TryParseConsoleNaturalInt(ICommandConsole console, string rawConsoleInt, out int i) { if (TryParseConsoleInt(console, rawConsoleInt, out i)) { if (i < 0) { if (console != null) console.OutputFormat("ERROR: {0} is not a positive integer", rawConsoleInt); return false; } return true; } return false; } /// <summary> /// Convert a minimum vector input from the console to an OpenMetaverse.Vector3 /// </summary> /// <param name='rawConsoleVector'>/param> /// <param name='vector'></param> /// <returns></returns> public static bool TryParseConsoleMinVector(string rawConsoleVector, out Vector3 vector) { return TryParseConsoleVector(rawConsoleVector, c => float.MinValue.ToString(), out vector); } /// <summary> /// Convert a maximum vector input from the console to an OpenMetaverse.Vector3 /// </summary> /// <param name='rawConsoleVector'>/param> /// <param name='vector'></param> /// <returns></returns> public static bool TryParseConsoleMaxVector(string rawConsoleVector, out Vector3 vector) { return TryParseConsoleVector(rawConsoleVector, c => float.MaxValue.ToString(), out vector); } /// <summary> /// Convert a vector input from the console to an OpenMetaverse.Vector3 /// </summary> /// <param name='rawConsoleVector'> /// A string in the form <x>,<y>,<z> where there is no space between values. /// Any component can be missing (e.g. ,,40). blankComponentFunc is invoked to replace the blank with a suitable value /// Also, if the blank component is at the end, then the comma can be missed off entirely (e.g. 40,30 or 40) /// The strings "~" and "-~" are valid in components. The first substitutes float.MaxValue whilst the second is float.MinValue /// Other than that, component values must be numeric. /// </param> /// <param name='blankComponentFunc'></param> /// <param name='vector'></param> /// <returns></returns> public static bool TryParseConsoleVector( string rawConsoleVector, Func<string, string> blankComponentFunc, out Vector3 vector) { List<string> components = rawConsoleVector.Split(VectorSeparatorChars).ToList(); if (components.Count < 1 || components.Count > 3) { vector = Vector3.Zero; return false; } for (int i = components.Count; i < 3; i++) components.Add(""); List<string> semiDigestedComponents = components.ConvertAll<string>( c => { if (c == "") return blankComponentFunc.Invoke(c); else if (c == MaxRawConsoleVectorValue) return float.MaxValue.ToString(); else if (c == MinRawConsoleVectorValue) return float.MinValue.ToString(); else return c; }); string semiDigestedConsoleVector = string.Join(VectorSeparator, semiDigestedComponents.ToArray()); // m_log.DebugFormat("[CONSOLE UTIL]: Parsing {0} into OpenMetaverse.Vector3", semiDigestedConsoleVector); return Vector3.TryParse(semiDigestedConsoleVector, out vector); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace StarDotOne.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); } } } }
// 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 SubtractInt64() { var test = new SimpleBinaryOpTest__SubtractInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractInt64 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[ElementCount]; private static Int64[] _data2 = new Int64[ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64> _dataTable; static SimpleBinaryOpTest__SubtractInt64() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__SubtractInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Subtract( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Subtract( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Subtract( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractInt64(); var result = Avx2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if ((long)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((long)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<Int64>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Input; using WPFDemo.Presentation.EventManagers; namespace WPFDemo.Presentation.Behaviors { public static class KeyboardExtensions { #region Static Properties public static readonly DependencyProperty EnterDownCommandProperty = DependencyProperty.RegisterAttached( "EnterDownCommand", typeof(ICommand), typeof(KeyboardExtensions), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, EnterDownCommand_PropertyChanged) ); private static readonly DependencyProperty EnterDownCommandWeakEventListenerProperty = DependencyProperty.RegisterAttached( "EnterDownCommandWeakEventListener", typeof(IWeakEventListener), typeof(MouseExtensions), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None) ); public static readonly DependencyProperty EnterDownCommandParameterProperty = DependencyProperty.RegisterAttached( "EnterDownCommandParameter", typeof(object), typeof(KeyboardExtensions), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None) ); public static readonly DependencyProperty F5CommandProperty = DependencyProperty.RegisterAttached( "F5Command", typeof(ICommand), typeof(KeyboardExtensions), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, F5Command_PropertyChanged) ); private static readonly DependencyProperty F5CommandWeakEventListenerProperty = DependencyProperty.RegisterAttached( "F5CommandWeakEventListener", typeof(IWeakEventListener), typeof(MouseExtensions), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None) ); public static readonly DependencyProperty F5CommandParameterProperty = DependencyProperty.RegisterAttached( "F5CommandParameter", typeof(object), typeof(KeyboardExtensions), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None) ); #endregion #region Static Methods public static ICommand GetEnterDownCommand(FrameworkElement element) { return (ICommand)element.GetValue(EnterDownCommandProperty); } public static void SetEnterDownCommand(FrameworkElement element, ICommand Value) { element.SetValue(EnterDownCommandProperty, Value); } private static IWeakEventListener GetEnterDownCommandWeakEventListener(FrameworkElement element) { return (IWeakEventListener)element.GetValue(EnterDownCommandWeakEventListenerProperty); } private static void SetEnterDownCommandWeakEventListener(FrameworkElement element, IWeakEventListener Value) { element.SetValue(EnterDownCommandWeakEventListenerProperty, Value); } public static object GetEnterDownCommandParameter(FrameworkElement element) { return (object)element.GetValue(EnterDownCommandParameterProperty); } public static void SetEnterDownCommandParameter(FrameworkElement element, object Value) { element.SetValue(EnterDownCommandParameterProperty, Value); } private static void EnterDownCommand_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var Element = o as FrameworkElement; if (Element == null) throw new ArgumentException("Type mismatch", "o"); var Value = (ICommand)e.NewValue; var Listener = GetEnterDownCommandWeakEventListener(Element); if (Value != null) { if (Listener == null) Listener = new EnterDownCommandEventListener(); SetEnterDownCommandWeakEventListener(Element, Listener); PreviewKeyDownEventManager.AddListener(Element, Listener); } else if (Listener != null) { SetEnterDownCommandWeakEventListener(Element, null); PreviewKeyDownEventManager.RemoveListener(Element, Listener); } } public static ICommand GetF5Command(FrameworkElement element) { return (ICommand)element.GetValue(F5CommandProperty); } public static void SetF5Command(FrameworkElement element, ICommand Value) { element.SetValue(F5CommandProperty, Value); } private static IWeakEventListener GetF5CommandWeakEventListener(FrameworkElement element) { return (IWeakEventListener)element.GetValue(F5CommandWeakEventListenerProperty); } private static void SetF5CommandWeakEventListener(FrameworkElement element, IWeakEventListener Value) { element.SetValue(F5CommandWeakEventListenerProperty, Value); } public static object GetF5CommandParameter(FrameworkElement element) { return (object)element.GetValue(F5CommandParameterProperty); } public static void SetF5CommandParameter(FrameworkElement element, object Value) { element.SetValue(F5CommandParameterProperty, Value); } private static void F5Command_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var Element = o as FrameworkElement; if (Element == null) throw new ArgumentException("Type mismatch", "o"); var Value = (ICommand)e.NewValue; var Listener = GetF5CommandWeakEventListener(Element); if (Value != null) { if (Listener == null) Listener = new EnterDownCommandEventListener(); SetF5CommandWeakEventListener(Element, Listener); PreviewKeyDownEventManager.AddListener(Element, Listener); } else if (Listener != null) { SetF5CommandWeakEventListener(Element, null); PreviewKeyDownEventManager.RemoveListener(Element, Listener); } } #endregion } internal class EnterDownCommandEventListener : IWeakEventListener { #region IWeakEventListener Members public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs args) { if (managerType != typeof(PreviewKeyDownEventManager)) return false; var Element = sender as FrameworkElement; if (Element == null) return true; var e = args as System.Windows.Input.KeyEventArgs; if (e == null) return true; var Command = KeyboardExtensions.GetEnterDownCommand(Element); if (Command == null) return true; if (e.Key != Key.Enter) return true; e.Handled = true; var CommandParameter = KeyboardExtensions.GetEnterDownCommandParameter(Element); if (Command.CanExecute(CommandParameter)) Command.Execute(CommandParameter); return true; } #endregion } internal class F5CommandEventListener : IWeakEventListener { #region IWeakEventListener Members public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs args) { if (managerType != typeof(PreviewKeyDownEventManager)) return false; var Element = sender as FrameworkElement; if (Element == null) return true; var e = args as System.Windows.Input.KeyEventArgs; if (e == null) return true; var Command = KeyboardExtensions.GetEnterDownCommand(Element); if (Command == null) return true; if (e.Key != Key.F5) return true; e.Handled = true; var CommandParameter = KeyboardExtensions.GetEnterDownCommandParameter(Element); if (Command.CanExecute(CommandParameter)) Command.Execute(CommandParameter); return true; } #endregion } }
using System; using System.Data.SQLite; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using Microsoft.EntityFrameworkCore; using Toolkit.Data.EFCore; using ToolKit.Data; using Xunit; namespace UnitTests.Data { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Test Suites do not need XML Documentation.")] public class EfCoreRepositoryTests { private static bool _databaseCreated = false; public EfCoreRepositoryTests() { var databaseFile = $"EFCoreRepositoryTests.{Thread.CurrentThread.ManagedThreadId}.db"; var connectionString = new SQLiteConnectionStringBuilder() { DataSource = databaseFile, ForeignKeys = true }.ConnectionString; if (!_databaseCreated) { if (File.Exists(databaseFile)) { File.Delete(databaseFile); } SQLiteConnection.CreateFile(databaseFile); using (var c = new SQLiteConnection(connectionString)) { using (var cmd = new SQLiteCommand(c)) { c.Open(); cmd.CommandText = @"CREATE TABLE `Patients` ( `Id` integer PRIMARY KEY AUTOINCREMENT, `Name` TEXT NOT NULL, `Sex` integer, `DateAdded` DATETIME, `AdmitDate` DATETIME );"; cmd.ExecuteNonQuery(); c.Close(); } } _databaseCreated = true; } using (var c = new SQLiteConnection(connectionString)) { using (var cmd = new SQLiteCommand(c)) { c.Open(); cmd.CommandText = "DELETE FROM Patients;"; cmd.ExecuteNonQuery(); c.Close(); } } } public enum Gender { /// <summary> /// The male gender. /// </summary> Male, /// <summary> /// The female gender. /// </summary> Female } [Fact] public void Contains_Should_ReturnTrue_When_EntityIsInRepository() { // Arrange InitializeDatabase(); Patient detachedPatient; var patientPresent = false; // Act using (var repository = new PatientRepository()) { detachedPatient = repository.FindFirst(p => p.DateAdded > p.AdmitDate); } using (var repository = new PatientRepository()) { patientPresent = repository.Contains(detachedPatient); } // Assert Assert.True(patientPresent); } [Fact] public void Delete_Should_RemoveEntitiesFromDatabase() { // Arrange InitializeDatabase(); var patientCount = 0; // Act using (var repository = new PatientRepository()) { var patients = repository.FindBy(p => p.DateAdded > p.AdmitDate); repository.Delete(patients); } using (var repository = new PatientRepository()) { patientCount = repository.FindAll().Count(); } // Assert Assert.Equal(1, patientCount); } [Fact] public void FindAll_Should_ReturnAllEntities() { // Arrange InitializeDatabase(); var repository = new PatientRepository(); // Act var patients = repository.FindAll(); var patientCount = patients.Count(); repository.Dispose(); // Assert Assert.Equal(3, patientCount); } [Fact] public void FindBy_Should_ReturnCorrectEntities_When_QueriedByLinq() { // Arrange InitializeDatabase(); var repository = new PatientRepository(); // Act var patients = repository.FindBy(p => p.DateAdded > p.AdmitDate); var patientCount = patients.Count(); repository.Dispose(); // Assert Assert.Equal(2, patientCount); } [Fact] public void FindById_Should_ReturnEntityAfterBeingSaved() { // Arrange InitializeDatabase(); var entity = new Patient(); Patient entityFromDatabase; // Act using (var repository = new PatientRepository()) { entity.Name = "Test"; entity.DateAdded = new DateTime(2012, 2, 1); entity.AdmitDate = new DateTime(2012, 2, 2); repository.Save(entity); } using (var repository = new PatientRepository()) { entityFromDatabase = repository.FindById(entity.Id); } // Assert Assert.Equal(entity.Id, entityFromDatabase.Id); } [Fact] public void FindFirst_Should_ReturnFirstEntity_When_MultipleEntitiesAreReturnByQuery() { // Arrange InitializeDatabase(); var repository = new PatientRepository(); // Act var patient = repository.FindFirst(p => p.DateAdded > p.AdmitDate); repository.Dispose(); // Assert Assert.Equal("Bar", patient.Name); } [Fact] public void Save_Should_AddNewEntityToDb() { // Arrange InitializeDatabase(); var records = 0; // Act using (var repository = new PatientRepository()) { var entity = new Patient { Name = "Lotho Fairbairn", AdmitDate = DateTime.Now.AddDays(-2), DateAdded = DateTime.Now }; repository.Save(entity); } using (var repository = new PatientRepository()) { var entityFromDatabase = repository.FindAll(); records = entityFromDatabase.Count(); } // Assert Assert.Equal(4, records); } [Fact] public void Save_Should_ReturnUpdatedEntityFromDb_When_EntityIsChangedAndSaved() { // Arrange InitializeDatabase(); Patient entityFromDatabase; long recordId = 0; // Act using (var repository = new PatientRepository()) { var entity = repository.FindBy(q => q.Name == "Foo").First(); recordId = entity.Id; entity.Name = "John Smith"; repository.Save(entity); } using (var repository = new PatientRepository()) { entityFromDatabase = repository.FindById(recordId); } // Assert Assert.Equal("John Smith", entityFromDatabase.Name); } private void InitializeDatabase() { var connectionString = new SQLiteConnectionStringBuilder() { DataSource = $"EFCoreRepositoryTests.{Thread.CurrentThread.ManagedThreadId}.db" }.ConnectionString; var options = new DbContextOptionsBuilder<PatientContext>()?.UseSqlite(connectionString).Options; using (var db = new PatientContext(options)) { var foo = new Patient { Name = "Foo", Sex = Gender.Male, DateAdded = new DateTime(2012, 1, 1), AdmitDate = new DateTime(2012, 1, 2) }; var bar = new Patient { Name = "Bar", Sex = Gender.Female, DateAdded = new DateTime(2012, 1, 3), AdmitDate = new DateTime(2012, 1, 2) }; var doh = new Patient { Name = "Doh", Sex = Gender.Female, DateAdded = new DateTime(2012, 2, 3), AdmitDate = new DateTime(2012, 2, 2) }; db.Patients.Add(foo); db.Patients.Add(bar); db.Patients.Add(doh); db.SaveChanges(); } } public class Patient : EntityWithTypedId<long> { public virtual DateTime AdmitDate { get; set; } public virtual DateTime DateAdded { get; set; } public virtual string Name { get; set; } public virtual Gender Sex { get; set; } } public class PatientContext : EfCoreUnitOfWork { public PatientContext(DbContextOptions options) : base(options) { } public DbSet<Patient> Patients { get; set; } } public class PatientRepository : Repository<Patient, long> { public PatientRepository() { var connectionString = new SQLiteConnectionStringBuilder() { DataSource = $"EFCoreRepositoryTests.{Thread.CurrentThread.ManagedThreadId}.db", }.ConnectionString; var options = new DbContextOptionsBuilder<PatientContext>()?.UseSqlite(connectionString).Options; var context = new PatientContext(options); Context = context; } } } }
// 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; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing.Internal #else namespace System.Diagnostics.Tracing.Internal #endif { #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; #endif using Microsoft.Reflection; using System.Reflection; internal static class Environment { public static readonly string NewLine = System.Environment.NewLine; public static int TickCount { get { return System.Environment.TickCount; } } public static string GetResourceString(string key, params object[] args) { string fmt = rm.GetString(key); if (fmt != null) return string.Format(fmt, args); string sargs = String.Empty; foreach(var arg in args) { if (sargs != String.Empty) sargs += ", "; sargs += arg.ToString(); } return key + " (" + sargs + ")"; } public static string GetRuntimeResourceString(string key, params object[] args) { return GetResourceString(key, args); } private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly()); } } #if ES_BUILD_AGAINST_DOTNET_V35 namespace Microsoft.Diagnostics.Contracts.Internal { internal class Contract { public static void Assert(bool invariant) { Assert(invariant, string.Empty); } public static void Assert(bool invariant, string message) { if (!invariant) { if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); throw new Exception("Assertion failed: " + message); } } public static void EndContractBlock() { } } } namespace Microsoft.Internal { using System.Text; internal static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } } [Serializable] internal class Tuple<T1> { private readonly T1 m_Item1; public T1 Item1 { get { return m_Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(")"); return sb.ToString(); } int Size { get { return 1; } } } [Serializable] public class Tuple<T1, T2> { private readonly T1 m_Item1; private readonly T2 m_Item2; public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(")"); return sb.ToString(); } int Size { get { return 2; } } } } #endif namespace Microsoft.Reflection { using System.Reflection; #if ES_BUILD_PCL [Flags] public enum BindingFlags { DeclaredOnly = 0x02, // Only look at the members declared on the Type Instance = 0x04, // Include Instance members in search Static = 0x08, // Include Static members in search Public = 0x10, // Include Public members in search NonPublic = 0x20, // Include Non-Public members in search } public enum TypeCode { Empty = 0, // Null reference Object = 1, // Instance that isn't a value DBNull = 2, // Database null value Boolean = 3, // Boolean Char = 4, // Unicode character SByte = 5, // Signed 8-bit integer Byte = 6, // Unsigned 8-bit integer Int16 = 7, // Signed 16-bit integer UInt16 = 8, // Unsigned 16-bit integer Int32 = 9, // Signed 32-bit integer UInt32 = 10, // Unsigned 32-bit integer Int64 = 11, // Signed 64-bit integer UInt64 = 12, // Unsigned 64-bit integer Single = 13, // IEEE 32-bit float Double = 14, // IEEE 64-bit double Decimal = 15, // Decimal DateTime = 16, // DateTime String = 18, // Unicode character string } #endif static class ReflectionExtensions { #if (!ES_BUILD_PCL && !ES_BUILD_PN) // // Type extension methods // public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsAbstract(this Type type) { return type.IsAbstract; } public static bool IsSealed(this Type type) { return type.IsSealed; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static Type BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; } #else // ES_BUILD_PCL // // Type extension methods // public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static IEnumerable<PropertyInfo> GetProperties(this Type type) { #if ES_BUILD_PN return type.GetProperties(); #else return type.GetRuntimeProperties(); #endif } public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; } public static MethodInfo[] GetMethods(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0); Func<MethodInfo, bool> visFilter; Func<MethodInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = mi => false; break; case BindingFlags.Public: visFilter = mi => mi.IsPublic; break; case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break; default: visFilter = mi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = mi => false; break; case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break; case BindingFlags.Static: instFilter = mi => mi.IsStatic; break; default: instFilter = mi => true; break; } List<MethodInfo> methodInfos = new List<MethodInfo>(); foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods) { if (visFilter(declaredMethod) && instFilter(declaredMethod)) methodInfos.Add(declaredMethod); } return methodInfos.ToArray(); } public static FieldInfo[] GetFields(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0); Func<FieldInfo, bool> visFilter; Func<FieldInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = fi => false; break; case BindingFlags.Public: visFilter = fi => fi.IsPublic; break; case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break; default: visFilter = fi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = fi => false; break; case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break; case BindingFlags.Static: instFilter = fi => fi.IsStatic; break; default: instFilter = fi => true; break; } List<FieldInfo> fieldInfos = new List<FieldInfo>(); foreach (var declaredField in type.GetTypeInfo().DeclaredFields) { if (visFilter(declaredField) && instFilter(declaredField)) fieldInfos.Add(declaredField); } return fieldInfos.ToArray(); } public static Type GetNestedType(this Type type, string nestedTypeName) { TypeInfo ti = null; foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes) { if (nt.Name == nestedTypeName) { ti = nt; break; } } return ti == null ? null : ti.AsType(); } public static TypeCode GetTypeCode(this Type type) { if (type == typeof(bool)) return TypeCode.Boolean; else if (type == typeof(byte)) return TypeCode.Byte; else if (type == typeof(char)) return TypeCode.Char; else if (type == typeof(ushort)) return TypeCode.UInt16; else if (type == typeof(uint)) return TypeCode.UInt32; else if (type == typeof(ulong)) return TypeCode.UInt64; else if (type == typeof(sbyte)) return TypeCode.SByte; else if (type == typeof(short)) return TypeCode.Int16; else if (type == typeof(int)) return TypeCode.Int32; else if (type == typeof(long)) return TypeCode.Int64; else if (type == typeof(string)) return TypeCode.String; else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(DateTime)) return TypeCode.DateTime; else if (type == (typeof(Decimal))) return TypeCode.Decimal; else return TypeCode.Object; } // // FieldInfo extension methods // public static object GetRawConstantValue(this FieldInfo fi) { return fi.GetValue(null); } // // Assembly extension methods // public static bool ReflectionOnly(this Assembly assm) { // In PCL we can't load in reflection-only context return false; } #endif } } // Defining some no-ops in PCL builds #if ES_BUILD_PCL namespace System.Security { class SuppressUnmanagedCodeSecurityAttribute : Attribute { } enum SecurityAction { Demand } } namespace System.Security.Permissions { class HostProtectionAttribute : Attribute { public bool MayLeakOnAbort { get; set; } } class PermissionSetAttribute : Attribute { public PermissionSetAttribute(System.Security.SecurityAction action) { } public bool Unrestricted { get; set; } } } #endif #if ES_BUILD_PN namespace System { internal static class AppDomain { public static int GetCurrentThreadId() { return Internal.Runtime.Augments.RuntimeThread.CurrentThread.ManagedThreadId; } } } #endif #if ES_BUILD_STANDALONE namespace Microsoft.Win32 { using System.Runtime.InteropServices; using System.Security; [SuppressUnmanagedCodeSecurityAttribute()] internal static class Win32Native { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern uint GetCurrentProcessId(); } } #endif
using System; using System.Collections.Generic; using System.Text; using Irony.Parsing; using Xunit; namespace Irony.Tests { public class NumberLiteralTests { [Fact] public void TestNumber_General() { Parser parser; Token token; NumberLiteral number = new NumberLiteral("Number"); number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt }; parser = TestHelper.CreateParser(number); token = parser.ParseInput("123"); CheckType(token, typeof(int)); Assert.True((int)token.Value == 123, "Failed to read int value"); token = parser.ParseInput("123.4"); Assert.True(Math.Abs(Convert.ToDouble(token.Value) - 123.4) < 0.000001, "Failed to read float value"); //100 digits string sbig = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; token = parser.ParseInput(sbig); Assert.True(token.Value.ToString() == sbig, "Failed to read big integer value"); }//method //The following "sign" test methods and a fix are contributed by ashmind codeplex user [Fact] public void TestNumber_SignedDoesNotMatchSingleMinus() { Parser parser; Token token; var number = new NumberLiteral("number", NumberOptions.AllowSign); parser = TestHelper.CreateParser(number); token = parser.ParseInput("-"); Assert.True(token.IsError(), "Parsed single '-' as a number value."); } [Fact] public void TestNumber_SignedDoesNotMatchSinglePlus() { Parser parser; Token token; var number = new NumberLiteral("number", NumberOptions.AllowSign); parser = TestHelper.CreateParser(number); token = parser.ParseInput("+"); Assert.True(token.IsError(), "Parsed single '+' as a number value."); } [Fact] public void TestNumber_SignedMatchesNegativeCorrectly() { Parser parser; Token token; var number = new NumberLiteral("number", NumberOptions.AllowSign); parser = TestHelper.CreateParser(number); token = parser.ParseInput("-500"); Assert.True(-500 == (int)token.Value, $"Negative number was parsed incorrectly; expected: {"-500"}, scanned: {token.Value}"); } [Fact] public void TestNumber_CSharp() { Parser parser; Token token; double eps = 0.0001; parser = TestHelper.CreateParser(TerminalFactory.CreateCSharpNumber("Number")); //Simple integers and suffixes token = parser.ParseInput("123 "); CheckType(token, typeof(int)); Assert.True(token.Details != null, "ScanDetails object not found in token."); Assert.True((int)token.Value == 123, "Failed to read int value"); token = parser.ParseInput(Int32.MaxValue.ToString()); CheckType(token, typeof(int)); Assert.True((int)token.Value == Int32.MaxValue, "Failed to read Int32.MaxValue."); token = parser.ParseInput(UInt64.MaxValue.ToString()); CheckType(token, typeof(ulong)); Assert.True((ulong)token.Value == UInt64.MaxValue, "Failed to read uint64.MaxValue value"); token = parser.ParseInput("123U "); CheckType(token, typeof(UInt32)); Assert.True((UInt32)token.Value == 123, "Failed to read uint value"); token = parser.ParseInput("123L "); CheckType(token, typeof(long)); Assert.True((long)token.Value == 123, "Failed to read long value"); token = parser.ParseInput("123uL "); CheckType(token, typeof(ulong)); Assert.True((ulong)token.Value == 123, "Failed to read ulong value"); //Hex representation token = parser.ParseInput("0x012 "); CheckType(token, typeof(Int32)); Assert.True((Int32)token.Value == 0x012, "Failed to read hex int value"); token = parser.ParseInput("0x12U "); CheckType(token, typeof(UInt32)); Assert.True((UInt32)token.Value == 0x012, "Failed to read hex uint value"); token = parser.ParseInput("0x012L "); CheckType(token, typeof(long)); Assert.True((long)token.Value == 0x012, "Failed to read hex long value"); token = parser.ParseInput("0x012uL "); CheckType(token, typeof(ulong)); Assert.True((ulong)token.Value == 0x012, "Failed to read hex ulong value"); //Floating point types token = parser.ParseInput("123.4 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #1"); token = parser.ParseInput("1234e-1 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 1234e-1) < eps, "Failed to read double value #2"); token = parser.ParseInput("12.34e+01 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #3"); token = parser.ParseInput("0.1234E3 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #4"); token = parser.ParseInput("123.4f "); CheckType(token, typeof(float)); Assert.True(Math.Abs((Single)token.Value - 123.4) < eps, "Failed to read float(single) value"); token = parser.ParseInput("123.4m "); CheckType(token, typeof(decimal)); Assert.True(Math.Abs((decimal)token.Value - 123.4m) < Convert.ToDecimal(eps), "Failed to read decimal value"); token = parser.ParseInput("123. ", useTerminator: false); //should ignore dot and read number as int. compare it to python numbers - see below CheckType(token, typeof(int)); Assert.True((int)token.Value == 123, "Failed to read int value with trailing dot"); //Quick parse token = parser.ParseInput("1 "); CheckType(token, typeof(int)); //When going through quick parse path (for one-digit numbers), the NumberScanInfo record is not created and hence is absent in Attributes Assert.True(token.Details == null, "Quick parse test failed: ScanDetails object is found in token - quick parse path should not produce this object."); Assert.True((int)token.Value == 1, "Failed to read quick-parse value"); } [Fact] public void TestNumber_VB() { Parser parser; Token token; double eps = 0.0001; parser = TestHelper.CreateParser(TerminalFactory.CreateVbNumber("Number")); //Simple integer token = parser.ParseInput("123 "); CheckType(token, typeof(int)); Assert.True(token.Details != null, "ScanDetails object not found in token."); Assert.True((int)token.Value == 123, "Failed to read int value"); //Test all suffixes token = parser.ParseInput("123S "); CheckType(token, typeof(Int16)); Assert.True((Int16)token.Value == 123, "Failed to read short value"); token = parser.ParseInput("123I "); CheckType(token, typeof(Int32)); Assert.True((Int32)token.Value == 123, "Failed to read int value"); token = parser.ParseInput("123% "); CheckType(token, typeof(Int32)); Assert.True((Int32)token.Value == 123, "Failed to read int value"); token = parser.ParseInput("123L "); CheckType(token, typeof(long)); Assert.True((long)token.Value == 123, "Failed to read long value"); token = parser.ParseInput("123& "); CheckType(token, typeof(Int64)); Assert.True((Int64)token.Value == 123, "Failed to read long value"); token = parser.ParseInput("123us "); CheckType(token, typeof(UInt16)); Assert.True((UInt16)token.Value == 123, "Failed to read ushort value"); token = parser.ParseInput("123ui "); CheckType(token, typeof(UInt32)); Assert.True((UInt32)token.Value == 123, "Failed to read uint value"); token = parser.ParseInput("123ul "); CheckType(token, typeof(ulong)); Assert.True((ulong)token.Value == 123, "Failed to read ulong value"); //Hex and octal token = parser.ParseInput("&H012 "); CheckType(token, typeof(int)); Assert.True((int)token.Value == 0x012, "Failed to read hex int value"); token = parser.ParseInput("&H012L "); CheckType(token, typeof(long)); Assert.True((long)token.Value == 0x012, "Failed to read hex long value"); token = parser.ParseInput("&O012 "); CheckType(token, typeof(int)); Assert.True((int)token.Value == 10, "Failed to read octal int value"); //12(oct) = 10(dec) token = parser.ParseInput("&o012L "); CheckType(token, typeof(long)); Assert.True((long)token.Value == 10, "Failed to read octal long value"); //Floating point types token = parser.ParseInput("123.4 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #1"); token = parser.ParseInput("1234e-1 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 1234e-1) < eps, "Failed to read double value #2"); token = parser.ParseInput("12.34e+01 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #3"); token = parser.ParseInput("0.1234E3 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #4"); token = parser.ParseInput("123.4R "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #5"); token = parser.ParseInput("123.4# "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #6"); token = parser.ParseInput("123.4f "); CheckType(token, typeof(float)); Assert.True(Math.Abs((Single)token.Value - 123.4) < eps, "Failed to read float(single) value"); token = parser.ParseInput("123.4! "); CheckType(token, typeof(float)); Assert.True(Math.Abs((Single)token.Value - 123.4) < eps, "Failed to read float(single) value"); token = parser.ParseInput("123.4D "); CheckType(token, typeof(decimal)); Assert.True(Math.Abs((decimal)token.Value - 123.4m) < Convert.ToDecimal(eps), "Failed to read decimal value"); token = parser.ParseInput("123.4@ "); CheckType(token, typeof(decimal)); Assert.True(Math.Abs((decimal)token.Value - 123.4m) < Convert.ToDecimal(eps), "Failed to read decimal value"); //Quick parse token = parser.ParseInput("1 "); CheckType(token, typeof(int)); //When going through quick parse path (for one-digit numbers), the NumberScanInfo record is not created and hence is absent in Attributes Assert.True(token.Details == null, "Quick parse test failed: ScanDetails object is found in token - quick parse path should not produce this object."); Assert.True((int)token.Value == 1, "Failed to read quick-parse value"); } [Fact] public void TestNumber_Python() { Parser parser; Token token; double eps = 0.0001; parser = TestHelper.CreateParser(TerminalFactory.CreatePythonNumber("Number")); //Simple integers and suffixes token = parser.ParseInput("123 "); CheckType(token, typeof(int)); Assert.True(token.Details != null, "ScanDetails object not found in token."); Assert.True((int)token.Value == 123, "Failed to read int value"); token = parser.ParseInput("123L "); CheckType(token, typeof(long)); Assert.True((long)token.Value == 123, "Failed to read long value"); //Hex representation token = parser.ParseInput("0x012 "); CheckType(token, typeof(int)); Assert.True((int)token.Value == 0x012, "Failed to read hex int value"); token = parser.ParseInput("0x012l "); //with small "L" CheckType(token, typeof(long)); Assert.True((long)token.Value == 0x012, "Failed to read hex long value"); //Floating point types token = parser.ParseInput("123.4 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #1"); token = parser.ParseInput("1234e-1 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 1234e-1) < eps, "Failed to read double value #2"); token = parser.ParseInput("12.34e+01 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #3"); token = parser.ParseInput("0.1234E3 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #4"); token = parser.ParseInput(".1234 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 0.1234) < eps, "Failed to read double value with leading dot"); token = parser.ParseInput("123. "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.0) < eps, "Failed to read double value with trailing dot"); //Big integer string sbig = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; //100 digits token = parser.ParseInput(sbig); Assert.True(token.Value.ToString() == sbig, "Failed to read big integer value"); //Quick parse token = parser.ParseInput("1 "); CheckType(token, typeof(int)); Assert.True(token.Details == null, "Quick parse test failed: ScanDetails object is found in token - quick parse path should produce this object."); Assert.True((int)token.Value == 1, "Failed to read quick-parse value"); } [Fact] public void TestNumber_Scheme() { Parser parser; Token token; double eps = 0.0001; parser = TestHelper.CreateParser(TerminalFactory.CreateSchemeNumber("Number")); //Just test default float value (double), and exp symbols (e->double, s->single, d -> double) token = parser.ParseInput("123.4 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #1"); token = parser.ParseInput("1234e-1 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 1234e-1) < eps, "Failed to read single value #2"); token = parser.ParseInput("1234s-1 "); CheckType(token, typeof(Single)); Assert.True(Math.Abs((Single)token.Value - 1234e-1) < eps, "Failed to read single value #3"); token = parser.ParseInput("12.34d+01 "); CheckType(token, typeof(double)); Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #4"); }//method [Fact] public void TestNumber_WithUnderscore() { Parser parser; Token token; var number = new NumberLiteral("number", NumberOptions.AllowUnderscore); parser = TestHelper.CreateParser(number); //Simple integers and suffixes token = parser.ParseInput("1_234_567"); CheckType(token, typeof(int)); Assert.True((int)token.Value == 1234567, "Failed to read int value with underscores."); }//method //There was a bug discovered in NumberLiteral - it cannot parse appropriately the int.MinValue value. // This test ensures that the issue is fixed. [Fact] public void TestNumber_MinMaxValues() { Parser parser; Token token; var number = new NumberLiteral("number", NumberOptions.AllowSign); number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32 }; parser = TestHelper.CreateParser(number); var s = int.MinValue.ToString(); token = parser.ParseInput(s); Assert.False(token.IsError(), "Failed to scan int.MinValue, scanner returned an error."); CheckType(token, typeof(int)); Assert.True((int)token.Value == int.MinValue, "Failed to scan int.MinValue, scanned value does not match."); s = int.MaxValue.ToString(); token = parser.ParseInput(s); Assert.False(token.IsError(), "Failed to scan int.MaxValue, scanner returned an error."); CheckType(token, typeof(int)); Assert.True((int)token.Value == int.MaxValue, "Failed to read int.MaxValue"); }//method private void CheckType(Token token, Type type) { Assert.True(token != null, "TryMatch returned null, while token was expected."); Type vtype = token.Value.GetType(); Assert.True(vtype == type, "Invalid target type, expected " + type.ToString() + ", found: " + vtype); } }//class }//namespace
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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. ************************************************************************************/ //#define OVR_USE_PROJ_MATRIX using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// A head-tracked stereoscopic virtual reality camera rig. /// </summary> [ExecuteInEditMode] public class OVRCameraRig : MonoBehaviour { /// <summary> /// The left eye camera. /// </summary> private Camera leftEyeCamera; /// <summary> /// The right eye camera. /// </summary> public Camera rightEyeCamera; /// <summary> /// Always coincides with the pose of the left eye. /// </summary> public Transform leftEyeAnchor { get; private set; } /// <summary> /// Always coincides with average of the left and right eye poses. /// </summary> public Transform centerEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right eye. /// </summary> public Transform rightEyeAnchor { get; private set; } private bool needsCameraConfigure; #region Unity Messages private void Awake() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; needsCameraConfigure = true; } private void Start() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateCameras(); UpdateAnchors(); } #if !UNITY_ANDROID || UNITY_EDITOR private void LateUpdate() #else private void Update() #endif { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateCameras(); UpdateAnchors(); } #endregion private void UpdateAnchors() { OVRPose leftEye = OVRManager.display.GetEyePose(OVREye.Left); OVRPose rightEye = OVRManager.display.GetEyePose(OVREye.Right); leftEyeAnchor.localRotation = leftEye.orientation; centerEyeAnchor.localRotation = leftEye.orientation; // using left eye for now rightEyeAnchor.localRotation = rightEye.orientation; leftEyeAnchor.localPosition = leftEye.position; centerEyeAnchor.localPosition = 0.5f * (leftEye.position + rightEye.position); rightEyeAnchor.localPosition = rightEye.position; } private void UpdateCameras() { if (needsCameraConfigure) { leftEyeCamera = ConfigureCamera(OVREye.Left); rightEyeCamera = ConfigureCamera(OVREye.Right); #if !UNITY_ANDROID || UNITY_EDITOR #if OVR_USE_PROJ_MATRIX OVRManager.display.ForceSymmetricProj(false); #else OVRManager.display.ForceSymmetricProj(true); #endif needsCameraConfigure = false; #endif } } private void EnsureGameObjectIntegrity() { if (leftEyeAnchor == null) leftEyeAnchor = ConfigureEyeAnchor(OVREye.Left); if (centerEyeAnchor == null) centerEyeAnchor = ConfigureEyeAnchor(OVREye.Center); if (rightEyeAnchor == null) rightEyeAnchor = ConfigureEyeAnchor(OVREye.Right); if (leftEyeCamera == null) { leftEyeCamera = leftEyeAnchor.GetComponent<Camera>(); if (leftEyeCamera == null) { leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>(); } } if (rightEyeCamera == null) { rightEyeCamera = rightEyeAnchor.GetComponent<Camera>(); if (rightEyeCamera == null) { rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>(); } } } private Transform ConfigureEyeAnchor(OVREye eye) { string name = eye.ToString() + "EyeAnchor"; Transform anchor = transform.Find(name); if (anchor == null) { string oldName = "Camera" + eye.ToString(); anchor = transform.Find(oldName); } if (anchor == null) anchor = new GameObject(name).transform; anchor.parent = transform; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Camera ConfigureCamera(OVREye eye) { Transform anchor = (eye == OVREye.Left) ? leftEyeAnchor : rightEyeAnchor; Camera cam = anchor.GetComponent<Camera>(); OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(eye); cam.fieldOfView = eyeDesc.fov.y; cam.aspect = eyeDesc.resolution.x / eyeDesc.resolution.y; cam.rect = new Rect(0f, 0f, OVRManager.instance.virtualTextureScale, OVRManager.instance.virtualTextureScale); cam.targetTexture = OVRManager.display.GetEyeTexture(eye); // AA is documented to have no effect in deferred, but it causes black screens. if (cam.actualRenderingPath == RenderingPath.DeferredLighting) QualitySettings.antiAliasing = 0; #if !UNITY_ANDROID || UNITY_EDITOR #if OVR_USE_PROJ_MATRIX cam.projectionMatrix = OVRManager.display.GetProjection((int)eye, cam.nearClipPlane, cam.farClipPlane); #endif #endif return cam; } }
// 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 SubtractSingle() { var test = new SimpleBinaryOpTest__SubtractSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static SimpleBinaryOpTest__SubtractSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__SubtractSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.Subtract( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.Subtract( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.Subtract( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.Subtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.Subtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.Subtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractSingle(); var result = Sse.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(left[0] - right[0]) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i] - right[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.Subtract)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.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 ExamSystem.Backend.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using RestSharp; namespace Salience.FluentApi.Internal { internal class FluentRequest : IEmptyRequest, IRequestWithOperation, IRequestWithMethod, IRequestWithExpectedStatus { protected readonly FluentClient _client; protected readonly RequestData _data; public FluentRequest(FluentClient client, RequestData data) { _client = client; _data = data; } IRequestWithOperation IEmptyRequest.To(string operation) { Guard.NotNullOrEmpty(operation, "operation"); _data.Operation = operation; return this; } private IRequestWithMethod SetMethodAndPath(Method method, string resourcePath, Action<RestRequest> requestCustomizer = null) { Guard.NotNullOrEmpty(resourcePath, "resourcePath"); _data.Method = method; _data.ResourcePath = "/" + resourcePath.Trim('/'); _data.RequestCustomizer = requestCustomizer; return this; } IRequestWithMethod IRequestWithOperation.Get(string resourcePath) { return this.SetMethodAndPath(Method.GET, resourcePath); } IRequestWithMethod IRequestWithOperation.Get(string resourcePath, Action<RestRequest> requestCustomizer) { return this.SetMethodAndPath(Method.GET, resourcePath, requestCustomizer); } IRequestWithMethod IRequestWithOperation.Post(string resourcePath) { return this.SetMethodAndPath(Method.POST, resourcePath); } IRequestWithMethod IRequestWithOperation.Post(string resourcePath, Action<RestRequest> requestCustomizer) { return this.SetMethodAndPath(Method.POST, resourcePath, requestCustomizer); } IRequestWithMethod IRequestWithOperation.Put(string resourcePath) { return this.SetMethodAndPath(Method.PUT, resourcePath); } IRequestWithMethod IRequestWithOperation.Put(string resourcePath, Action<RestRequest> requestCustomizer) { return this.SetMethodAndPath(Method.PUT, resourcePath, requestCustomizer); } IRequestWithMethod IRequestWithOperation.Patch(string resourcePath) { return this.SetMethodAndPath(Method.PATCH, resourcePath); } IRequestWithMethod IRequestWithOperation.Patch(string resourcePath, Action<RestRequest> requestCustomizer) { return this.SetMethodAndPath(Method.PATCH, resourcePath, requestCustomizer); } IRequestWithMethod IRequestWithOperation.Delete(string resourcePath) { return this.SetMethodAndPath(Method.DELETE, resourcePath); } IRequestWithMethod IRequestWithOperation.Delete(string resourcePath, Action<RestRequest> requestCustomizer) { return this.SetMethodAndPath(Method.DELETE, resourcePath, requestCustomizer); } IRequestWithUrl IRequestWithMethod.UsingBase(string otherBaseApiPath) { Guard.NotNullOrEmpty(otherBaseApiPath, "otherBaseApiPath"); otherBaseApiPath = otherBaseApiPath.Trim(); _data.BaseApiPath = string.IsNullOrEmpty(otherBaseApiPath) ? "" : "/" + otherBaseApiPath.Trim('/'); return this; } IRequestWithExpectedStatus IRequestWithUrl.Expecting(HttpStatusCode expectedStatusCode, params HttpStatusCode[] otherAcceptedStatusCodes) { _data.ExpectedStatusCodes.Add(expectedStatusCode); foreach (var code in otherAcceptedStatusCodes) _data.ExpectedStatusCodes.Add(code); return this; } IRequestWithContent<T> IRequestWithUrl.Expecting<T>() { _data.ResponseBodyType = typeof(T); return new FluentRequestWithContent<T>(_client, _data); } IRequestWithContent<TResult> IRequestWithUrl.Expecting<TResponse, TResult>(Func<TResponse, TResult> resultGetter) { Guard.NotNull(resultGetter, "resultGetter"); _data.ResponseBodyType = typeof(TResponse); _data.ResultGetter = resultGetter; return new FluentRequestWithContent<TResult>(_client, _data); } IRequestWithContent<string> IRequestWithExpectedStatus.WithRawContent() { _data.UseRawResponseContent = true; return new FluentRequestWithContent<string>(_client, _data); } IRequestWithContent<TResult> IRequestWithExpectedStatus.WithRawContent<TResult>(Func<string, TResult> resultGetter) { _data.UseRawResponseContent = true; _data.ResponseBodyType = typeof(TResult); _data.ResultGetter = resultGetter; return new FluentRequestWithContent<TResult>(_client, _data); } IRequestWithContent<T> IRequestWithExpectedStatus.WithContent<T>() { return ((IRequestWithUrl)this).Expecting<T>(); } IRequestWithContent<TResult> IRequestWithExpectedStatus.WithContent<TResponse, TResult>(Func<TResponse, TResult> resultGetter) { return ((IRequestWithUrl)this).Expecting(resultGetter); } void IFinalExecutableRequest.Execute() { _client.HandleRequest(_data); } Task IFinalExecutableRequest.ExecuteAsync(CancellationToken token) { return _client.HandleRequestAsync(_data, token); } IExecutableRequest IExecutableRequest.FollowedByRequest(IExecutableRequest otherRequest) { _data.FollowUps.Add(_ => new FinalExecutableRequestWrapper(otherRequest)); return this; } IExecutableRequest<T> IExecutableRequest.FollowedByRequest<T>(IExecutableRequest<T> otherRequest) { _data.FollowUps.Add(_ => new FinalExecutableRequestWrapper<T>(otherRequest)); return new FluentRequestWithContent<T>(_client, _data); } IExecutableRequest IExecutableRequest.FollowedBy(Action action) { _data.FollowUps.Add(_ => new FinalActionWrapper(action)); return this; } IExecutableRequest<T> IExecutableRequest.FollowedBy<T>(Func<T> operation) { _data.FollowUps.Add(_ => new FinalFuncWrapper<T>(operation)); return new FluentRequestWithContent<T>(_client, _data); } } internal class FluentRequestWithContent<T> : FluentRequest, IRequestWithContent<T> { public FluentRequestWithContent(FluentClient client, RequestData data) : base(client, data) { } IRequestWithAlternateResult<T> IRequestWithContent<T>.Or(T alternateResult) { return new FluentRequestWithAlternateContent<T>(this, _data, alternateResult); } IRequestWithContent<T> IRequestWithContent<T>.OrDefaultIfNotFound() { return ((IRequestWithContent<T>)this).Or(default(T)).IfNotFound(); } T IFinalExecutableRequest<T>.Execute() { return (T) _client.HandleRequest(_data); } async Task<T> IFinalExecutableRequest<T>.ExecuteAsync(CancellationToken token) { return (T) await _client.HandleRequestAsync(_data, token); } IExecutableRequest IExecutableRequest<T>.FollowedByRequest(Func<T, IExecutableRequest> otherRequest) { _data.FollowUps.Add(result => new FinalExecutableRequestWrapper(otherRequest((T)result))); return new FluentRequest(_client, _data); } IExecutableRequest<T2> IExecutableRequest<T>.FollowedByRequest<T2>(Func<T, IExecutableRequest<T2>> otherRequest) { _data.FollowUps.Add(result => new FinalExecutableRequestWrapper<T2>(otherRequest((T)result))); return new FluentRequestWithContent<T2>(_client, _data); } IExecutableRequest IExecutableRequest<T>.FollowedBy(Action<T> operation) { _data.FollowUps.Add(result => new FinalActionWrapper(() => operation((T)result))); return new FluentRequest(_client, _data); } IExecutableRequest<T2> IExecutableRequest<T>.FollowedBy<T2>(Func<T, T2> transformation) { _data.FollowUps.Add(result => new FinalFuncWrapper<T2>(() => transformation((T)result))); return new FluentRequestWithContent<T2>(_client, _data); } } internal class FluentRequestWithAlternateContent<T> : IRequestWithAlternateResult<T> { private readonly FluentRequestWithContent<T> _request; private readonly RequestData _data; private readonly object _alternateContent; public FluentRequestWithAlternateContent(FluentRequestWithContent<T> request, RequestData description, object alternateContent) { _request = request; _data = description; _alternateContent = alternateContent; } IRequestWithContent<T> IRequestWithAlternateResult<T>.If(HttpStatusCode expectedStatusCode, params HttpStatusCode[] otherAcceptedStatusCodes) { _data.ExpectedStatusCodes.Add(expectedStatusCode); _data.AlternateResults.Add(expectedStatusCode, _alternateContent); foreach(var code in otherAcceptedStatusCodes) { _data.ExpectedStatusCodes.Add(code); _data.AlternateResults.Add(code, _alternateContent); } return _request; } IRequestWithContent<T> IRequestWithAlternateResult<T>.IfNotFound() { return ((IRequestWithAlternateResult<T>)this).If(HttpStatusCode.NotFound); } IRequestWithContent<T> IRequestWithAlternateResult<T>.IfNoContent() { return ((IRequestWithAlternateResult<T>)this).If(HttpStatusCode.NoContent); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Runtime.Remoting.Messaging; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.Table; using MvcWebRole.Models; using WorkerRoleA.Telemetry; namespace WorkerRoleA { public class WorkerRoleA : RoleEntryPoint { private CloudQueue sendEmailQueue; private CloudTable mailingListTable; private CloudTable messageTable; private CloudTable messagearchiveTable; private volatile bool onStopCalled = false; private volatile bool returnedFromRunMethod = false; private TelemetryClient aiClient = new TelemetryClient(); private static string CORRELATION_SLOT = "CORRELATION-ID"; public override void Run() { Trace.TraceInformation("WorkerRoleA entering Run()"); while (true) { Stopwatch requestTimer = Stopwatch.StartNew(); var request = RequestTelemetryHelper.StartNewRequest("ProcessMessageWorkflow", DateTimeOffset.UtcNow); CallContext.LogicalSetData(CORRELATION_SLOT, request.Id); //Thread.SetData(Thread.GetNamedDataSlot(CORRELATION_SLOT), request.Id); try { var tomorrow = DateTime.Today.AddDays(1.0).ToString("yyyy-MM-dd"); // If OnStop has been called, return to do a graceful shutdown. if (onStopCalled == true) { Trace.TraceInformation("onStopCalled WorkerRoleB"); returnedFromRunMethod = true; return; } // Retrieve all messages that are scheduled for tomorrow or earlier // and are in Pending or Queuing status. string typeAndDateFilter = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThan, "message"), TableOperators.And, TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.LessThan, tomorrow)); var query = (new TableQuery<Message>().Where(typeAndDateFilter)); var messagesToProcess = messageTable.ExecuteQuery(query).ToList(); TableOperation replaceOperation; request.Metrics.Add(new KeyValuePair<string, double>("NumberOfMessages", messagesToProcess.Count)); // Process each message (queue emails to be sent). foreach (Message messageToProcess in messagesToProcess) { string restartFlag = "0"; // If the message is already in Queuing status, // set flag to indicate this is a restart. if (messageToProcess.Status == "Queuing") { restartFlag = "1"; } // If the message is in Pending status, change // it to Queuing. if (messageToProcess.Status == "Pending") { messageToProcess.Status = "Queuing"; replaceOperation = TableOperation.Replace(messageToProcess); messageTable.Execute(replaceOperation); } // If the message is in Queuing status, // process it and change it to Processing status; // otherwise it's already in processing status, and // in that case check if processing is complete. if (messageToProcess.Status == "Queuing") { ProcessMessage(messageToProcess, restartFlag); messageToProcess.Status = "Processing"; replaceOperation = TableOperation.Replace(messageToProcess); messageTable.Execute(replaceOperation); } else { CheckAndArchiveIfComplete(messageToProcess); } } RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, true); // Sleep to minimize query costs. System.Threading.Thread.Sleep(1000 * 30); } catch (Exception ex) { string err = ex.Message; if (ex.InnerException != null) { err += " Inner Exception: " + ex.InnerException.Message; } Trace.TraceError(err, ex); RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, false); // Don't fill up Trace storage if we have a bug in queue process loop. System.Threading.Thread.Sleep(1000 * 60); } } } private void ProcessMessage(Message messageToProcess, string restartFlag) { // Get Mailing List info to get the "From" email address. var retrieveOperation = TableOperation.Retrieve<MailingList>(messageToProcess.ListName, "mailinglist"); var retrievedResult = mailingListTable.Execute(retrieveOperation); var mailingList = retrievedResult.Result as MailingList; if (mailingList == null) { Trace.TraceError("Mailing list not found: " + messageToProcess.ListName + " for message: " + messageToProcess.MessageRef); return; } // Get email addresses for this Mailing List. string filter = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, messageToProcess.ListName), TableOperators.And, TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.NotEqual, "mailinglist")); var query = new TableQuery<Subscriber>().Where(filter); var subscribers = mailingListTable.ExecuteQuery(query).ToList(); aiClient.TrackMetric("SubscriberCount", subscribers.Count); foreach (Subscriber subscriber in subscribers) { // Verify that the subscriber email address has been verified. if (subscriber.Verified == false) { Trace.TraceInformation("Subscriber " + subscriber.EmailAddress + " not Verified, so not queuing "); continue; } // Create a SendEmail entity for this email. var sendEmailRow = new SendEmail { PartitionKey = messageToProcess.PartitionKey, RowKey = messageToProcess.MessageRef.ToString() + subscriber.EmailAddress, EmailAddress = subscriber.EmailAddress, EmailSent = false, MessageRef = messageToProcess.MessageRef, ScheduledDate = messageToProcess.ScheduledDate, FromEmailAddress = mailingList.FromEmailAddress, SubjectLine = messageToProcess.SubjectLine, SubscriberGUID = subscriber.SubscriberGUID, ListName = mailingList.ListName }; // When we try to add the entity to the SendEmail table, // an exception might happen if this worker role went // down after processing some of the email addresses and then restarted. // In that case the row might already be present, so we do an Upsert operation. try { var upsertOperation = TableOperation.InsertOrReplace(sendEmailRow); messageTable.Execute(upsertOperation); } catch (Exception ex) { string err = "Error creating SendEmail row: " + ex.Message; if (ex.InnerException != null) { err += " Inner Exception: " + ex.InnerException; } Trace.TraceError(err, ex); } // Create the queue message. string queueMessageString = sendEmailRow.PartitionKey + "," + sendEmailRow.RowKey + "," + restartFlag; var queueMessage = new CloudQueueMessage(queueMessageString); sendEmailQueue.AddMessage(queueMessage); } Trace.TraceInformation("ProcessMessage end PK: " + messageToProcess.PartitionKey); } private void CheckAndArchiveIfComplete(Message messageToCheck) { // Get the list of emails to be sent for this message: all SendEmail rows // for this message. string pkrkFilter = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, messageToCheck.PartitionKey), TableOperators.And, TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThan, "message")); var query = new TableQuery<SendEmail>().Where(pkrkFilter); var emailToBeSent = messageTable.ExecuteQuery(query).FirstOrDefault(); if (emailToBeSent != null) { return; } // All emails have been sent; copy the message row to the archive table. // Insert the message row in the messagearchive table var messageToDelete = new Message { PartitionKey = messageToCheck.PartitionKey, RowKey = messageToCheck.RowKey, ETag = "*" }; messageToCheck.Status = "Complete"; var insertOrReplaceOperation = TableOperation.InsertOrReplace(messageToCheck); messagearchiveTable.Execute(insertOrReplaceOperation); // Delete the message row from the message table. var deleteOperation = TableOperation.Delete(messageToDelete); messageTable.Execute(deleteOperation); } public override void OnStop() { onStopCalled = true; while (returnedFromRunMethod == false) { System.Threading.Thread.Sleep(1000); } } public override bool OnStart() { TelemetryConfiguration.Active.InstrumentationKey = RoleEnvironment.GetConfigurationSettingValue("Telemetry.AI.InstrumentationKey"); TelemetryConfiguration.Active.TelemetryInitializers.Add(new ItemCorrelationTelemetryInitializer()); ServicePointManager.DefaultConnectionLimit = Environment.ProcessorCount * 12; Trace.TraceInformation("Initializing storage account in WorkerA"); var storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString")); CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); sendEmailQueue = queueClient.GetQueueReference("azuremailqueue"); var tableClient = storageAccount.CreateCloudTableClient(); mailingListTable = tableClient.GetTableReference("mailinglist"); messageTable = tableClient.GetTableReference("message"); messagearchiveTable = tableClient.GetTableReference("messagearchive"); // Create if not exists for queue, blob container, SentEmail table. sendEmailQueue.CreateIfNotExists(); messageTable.CreateIfNotExists(); mailingListTable.CreateIfNotExists(); messagearchiveTable.CreateIfNotExists(); return base.OnStart(); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.LLVMHosted.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; public sealed class RealTimeClock { public delegate void Callback( Timer timer, ulong currentTime ); public class Timer { // // State // private RealTimeClock m_owner; private RT.KernelNode< Timer > m_node; private ulong m_timeout; private Callback m_callback; // // Constructor Methods // internal Timer( RealTimeClock owner, Callback callback ) { m_owner = owner; m_node = new RT.KernelNode<Timer>( this ); m_callback = callback; } // // Helper Methods // public void Cancel( ) { m_owner.Deregister( this ); } internal void Invoke( ulong currentTime ) { m_callback( this, currentTime ); } // // Access Methods // internal RT.KernelNode<Timer> Node { get { return m_node; } } public ulong Timeout { get { return m_timeout; } set { m_timeout = value; m_owner.Register( this ); } } public ulong RelativeTimeout { get { return m_timeout - RealTimeClock.Instance.CurrentTime; } set { m_timeout = value + RealTimeClock.Instance.CurrentTime; m_owner.Register( this ); } } } // // State // const uint c_QuarterCycle = 0x40000000u; const uint c_OverflowFlag = 0x80000000u; //readonly OSTimers.OMCR_bitfield c_Timer1Ctrl = // new OSTimers.OMCR_bitfield // { // P = true, // Keep the counter running after a match. // C = false, // Channel 5 match against Channel 4 counter. // CRES = OSTimers.OMCR_bitfield.Resolution.Freq1MHz, // }; //readonly OSTimers.OMCR_bitfield c_Timer2Ctrl = // new OSTimers.OMCR_bitfield // { // P = true, // Keep the counter running after a match. // C = true, // Channel 4 matches against its counter. // CRES = OSTimers.OMCR_bitfield.Resolution.Freq1MHz, // }; //private uint m_lastCount; //private uint m_highPart; //private InterruptController.Handler m_interrupt; //private InterruptController.Handler m_simulatedSoftInterrupt; private RT.KernelList< Timer > m_timers; // // Helper Methods // public void Initialize( ) { m_timers = new RT.KernelList<Timer>( ); //m_interrupt = InterruptController.Handler.Create( PXA27x.InterruptController.IRQ_INDEX_OS_TIMER, InterruptPriority.Normal, InterruptSettings.ActiveHigh, ProcessTimeout ); //m_simulatedSoftInterrupt = InterruptController.Handler.Create( PXA27x.InterruptController.IRQ_INDEX_OS_TIMER0, InterruptPriority.Lowest, InterruptSettings.ActiveHigh, ProcessSoftInterrupt ); ////--// //var clockControl = PXA27x.ClockManager.Instance; //clockControl.CKEN.EnOsTimer = true; ////--// //var timer = PXA27x.OSTimers.Instance; //timer.OIER = 0; ////--// //// //// We use Timer0 as a soft interrupt, so we have to wait until it has fired and NEVER reset the match value. //// //timer.EnableInterrupt( 0 ); //timer.WriteCounter( 0, 0 ); //timer.SetMatch( 0, 100 ); //while( timer.HasFired( 0 ) == false ) //{ //} ////--// //timer.SetControl( 5, c_Timer1Ctrl ); //timer.SetControl( 4, c_Timer2Ctrl ); //// //// Start the timer. //// //timer.WriteCounter( 4, 0 ); //timer.EnableInterrupt( 4 ); //timer.EnableInterrupt( 5 ); ////--// //var intc = InterruptController.Instance; //intc.RegisterAndEnable( m_interrupt ); //intc.Register( m_simulatedSoftInterrupt ); Refresh( ); } public Timer CreateTimer( Callback callback ) { return new Timer( this, callback ); } //--// private void Register( Timer timer ) { RT.KernelNode< Timer > node = timer.Node; node.RemoveFromList( ); ulong timeout = timer.Timeout; RT.KernelNode< Timer > node2 = m_timers.StartOfForwardWalk; while( node2.IsValidForForwardMove ) { if( node2.Target.Timeout > timeout ) { break; } node2 = node2.Next; } node.InsertBefore( node2 ); Refresh( ); } private void Deregister( Timer timer ) { var node = timer.Node; if( node.IsLinked ) { node.RemoveFromList( ); Refresh( ); } } //--// //private void ProcessTimeout( InterruptController.Handler handler ) //{ // ulong currentTime = this.CurrentTime; // while( true ) // { // RT.KernelNode< Timer > node = m_timers.StartOfForwardWalk; // if( node.IsValidForForwardMove == false ) // { // break; // } // if( node.Target.Timeout > currentTime ) // { // break; // } // node.RemoveFromList( ); // node.Target.Invoke( currentTime ); // } // Refresh( ); //} //internal void CauseInterrupt( ) //{ // var timer = PXA27x.OSTimers.Instance; // timer.SetMatch( 0, timer.ReadCounter( 0 ) + 8 ); // m_simulatedSoftInterrupt.Enable( ); //} //private void ProcessSoftInterrupt( InterruptController.Handler handler ) //{ // m_simulatedSoftInterrupt.Disable( ); // InterruptController.Instance.ProcessSoftInterrupt( ); //} void Refresh( ) { Timer target = m_timers.FirstTarget( ); ulong timeout; if( target != null ) { timeout = target.Timeout; } else { timeout = ulong.MaxValue; } //--// ulong now = this.CurrentTime; // // Timeout in the past? Trigger the match now. // if( now > timeout ) { timeout = now; } // // Timeout too far in the future? Generate match closer in time, so we handle wrap arounds. // ulong nowPlusQuarterCycle = now + c_QuarterCycle; if( nowPlusQuarterCycle < timeout ) { timeout = nowPlusQuarterCycle; } uint timeoutLow = ( uint )timeout; //var timer = PXA27x.OSTimers.Instance; //// disable second interrupt so we don't handle this timeout twice //timer.DisableInterrupt( 5 ); //// //// Clear previous interrupts. //// //timer.ClearFired( 4 ); //timer.ClearFired( 5 ); //// //// Create two matches, to protect against race conditions (at least one will fire). //// //timer.SetMatch( 4, timeoutLow ); //timer.SetMatch( 5, timeoutLow + 10 ); //timer.EnableInterrupt( 5 ); } // // Access Methods // public static extern RealTimeClock Instance { [RT.SingletonFactory( )] [MethodImpl( MethodImplOptions.InternalCall )] get; } public uint CurrentTimeRaw { get { //return PXA27x.OSTimers.Instance.ReadCounter( 4 ); return 0; } } public ulong CurrentTime { get { return 0; //using( RT.SmartHandles.InterruptState.Disable( ) ) //{ // uint value = PXA27x.OSTimers.Instance.ReadCounter( 4 ); // uint highPart = m_highPart; // // // // Wrap around? Update high part. // // // if( ( ( value ^ m_lastCount ) & c_OverflowFlag ) != 0 ) // { // highPart++; // m_lastCount = value; // m_highPart = highPart; // } // return ( ulong )highPart << 32 | value; //} } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Globalization; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Testing; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.Containers { public class TestCaseCoordinateSpaces : TestCase { public TestCaseCoordinateSpaces() { AddStep("0-1 space", () => loadCase(0)); AddStep("0-150 space", () => loadCase(1)); AddStep("50-200 space", () => loadCase(2)); AddStep("150-(-50) space", () => loadCase(3)); AddStep("0-300 space", () => loadCase(4)); AddStep("-250-250 space", () => loadCase(5)); } private void loadCase(int i) { Clear(); HorizontalVisualiser h; Add(h = new HorizontalVisualiser { Size = new Vector2(200, 50), X = 150 }); switch (i) { case 0: h.CreateMarkerAt(-0.1f); h.CreateMarkerAt(0); h.CreateMarkerAt(0.1f); h.CreateMarkerAt(0.3f); h.CreateMarkerAt(0.7f); h.CreateMarkerAt(0.9f); h.CreateMarkerAt(1f); h.CreateMarkerAt(1.1f); break; case 1: h.RelativeChildSize = new Vector2(150, 1); h.CreateMarkerAt(0); h.CreateMarkerAt(50); h.CreateMarkerAt(100); h.CreateMarkerAt(150); h.CreateMarkerAt(200); h.CreateMarkerAt(250); break; case 2: h.RelativeChildOffset = new Vector2(50, 0); h.RelativeChildSize = new Vector2(150, 1); h.CreateMarkerAt(0); h.CreateMarkerAt(50); h.CreateMarkerAt(100); h.CreateMarkerAt(150); h.CreateMarkerAt(200); h.CreateMarkerAt(250); break; case 3: h.RelativeChildOffset = new Vector2(150, 0); h.RelativeChildSize = new Vector2(-200, 1); h.CreateMarkerAt(0); h.CreateMarkerAt(50); h.CreateMarkerAt(100); h.CreateMarkerAt(150); h.CreateMarkerAt(200); h.CreateMarkerAt(250); break; case 4: h.RelativeChildOffset = new Vector2(0, 0); h.RelativeChildSize = new Vector2(300, 1); h.CreateMarkerAt(0); h.CreateMarkerAt(50); h.CreateMarkerAt(100); h.CreateMarkerAt(150); h.CreateMarkerAt(200); h.CreateMarkerAt(250); break; case 5: h.RelativeChildOffset = new Vector2(-250, 0); h.RelativeChildSize = new Vector2(500, 1); h.CreateMarkerAt(-300); h.CreateMarkerAt(-200); h.CreateMarkerAt(-100); h.CreateMarkerAt(0); h.CreateMarkerAt(100); h.CreateMarkerAt(200); h.CreateMarkerAt(300); break; } } private class HorizontalVisualiser : Visualiser { protected override void Update() { base.Update(); Left.Text = $"X = {RelativeChildOffset.X.ToString(CultureInfo.InvariantCulture)}"; Right.Text = $"X = {(RelativeChildOffset.X + RelativeChildSize.X).ToString(CultureInfo.InvariantCulture)}"; } } private abstract class Visualiser : Container { public new Vector2 RelativeChildSize { protected get { return innerContainer.RelativeChildSize; } set { innerContainer.RelativeChildSize = value; } } public new Vector2 RelativeChildOffset { protected get { return innerContainer.RelativeChildOffset; } set { innerContainer.RelativeChildOffset = value; } } private readonly Container innerContainer; protected readonly SpriteText Left; protected readonly SpriteText Right; protected Visualiser() { Height = 50; InternalChildren = new Drawable[] { new Box { Name = "Left marker", Colour = Color4.Gray, RelativeSizeAxes = Axes.Y, }, Left = new SpriteText { Anchor = Anchor.BottomLeft, Origin = Anchor.TopCentre, Y = 6 }, new Box { Name = "Centre line", Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Colour = Color4.Gray, RelativeSizeAxes = Axes.X }, innerContainer = new Container { RelativeSizeAxes = Axes.Both }, new Box { Name = "Right marker", Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Colour = Color4.Gray, RelativeSizeAxes = Axes.Y }, Right = new SpriteText { Anchor = Anchor.BottomRight, Origin = Anchor.TopCentre, Y = 6 }, }; } public void CreateMarkerAt(float x) { innerContainer.Add(new Container { Anchor = Anchor.CentreLeft, Origin = Anchor.Centre, RelativePositionAxes = Axes.Both, AutoSizeAxes = Axes.Both, X = x, Colour = Color4.Yellow, Children = new Drawable[] { new Box { Name = "Centre marker horizontal", Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(8, 1) }, new Box { Name = "Centre marker vertical", Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(1, 8) }, new SpriteText { Anchor = Anchor.BottomCentre, Origin = Anchor.TopCentre, Y = 6, BypassAutoSizeAxes = Axes.Both, Text = x.ToString(CultureInfo.InvariantCulture) } } }); } } } }
// 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.Runtime.InteropServices; using System.Security; using System.Threading.Tasks; namespace System.Runtime.CompilerServices { /// <summary>Represents a builder for asynchronous methods that return a <see cref="ValueTask"/>.</summary> [StructLayout(LayoutKind.Auto)] public struct AsyncValueTaskMethodBuilder { /// <summary>The <see cref="AsyncTaskMethodBuilder"/> to which most operations are delegated.</summary> private AsyncTaskMethodBuilder _methodBuilder; // mutable struct; do not make it readonly /// <summary>true if completed synchronously and successfully; otherwise, false.</summary> private bool _haveResult; /// <summary>true if the builder should be used for setting/getting the result; otherwise, false.</summary> private bool _useBuilder; /// <summary>Creates an instance of the <see cref="AsyncValueTaskMethodBuilder"/> struct.</summary> /// <returns>The initialized instance.</returns> public static AsyncValueTaskMethodBuilder Create() => #if PROJECTN // ProjectN's AsyncTaskMethodBuilder.Create() currently does additional debugger-related // work, so we need to delegate to it. new AsyncValueTaskMethodBuilder() { _methodBuilder = AsyncTaskMethodBuilder.Create() }; #else // _methodBuilder should be initialized to AsyncTaskMethodBuilder.Create(), but on coreclr // that Create() is a nop, so we can just return the default here. default; #endif /// <summary>Begins running the builder with the associated state machine.</summary> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => // will provide the right ExecutionContext semantics AsyncMethodBuilderCore.Start(ref stateMachine); /// <summary>Associates the builder with the specified state machine.</summary> /// <param name="stateMachine">The state machine instance to associate with the builder.</param> public void SetStateMachine(IAsyncStateMachine stateMachine) => _methodBuilder.SetStateMachine(stateMachine); /// <summary>Marks the task as successfully completed.</summary> public void SetResult() { if (_useBuilder) { _methodBuilder.SetResult(); } else { _haveResult = true; } } /// <summary>Marks the task as failed and binds the specified exception to the task.</summary> /// <param name="exception">The exception to bind to the task.</param> public void SetException(Exception exception) => _methodBuilder.SetException(exception); /// <summary>Gets the task for this builder.</summary> public ValueTask Task { get { if (_haveResult) { return default; } else { _useBuilder = true; return new ValueTask(_methodBuilder.Task); } } } /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); } /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } } /// <summary>Represents a builder for asynchronous methods that returns a <see cref="ValueTask{TResult}"/>.</summary> /// <typeparam name="TResult">The type of the result.</typeparam> [StructLayout(LayoutKind.Auto)] public struct AsyncValueTaskMethodBuilder<TResult> { /// <summary>The <see cref="AsyncTaskMethodBuilder{TResult}"/> to which most operations are delegated.</summary> private AsyncTaskMethodBuilder<TResult> _methodBuilder; // mutable struct; do not make it readonly /// <summary>The result for this builder, if it's completed before any awaits occur.</summary> private TResult _result; /// <summary>true if <see cref="_result"/> contains the synchronous result for the async method; otherwise, false.</summary> private bool _haveResult; /// <summary>true if the builder should be used for setting/getting the result; otherwise, false.</summary> private bool _useBuilder; /// <summary>Creates an instance of the <see cref="AsyncValueTaskMethodBuilder{TResult}"/> struct.</summary> /// <returns>The initialized instance.</returns> public static AsyncValueTaskMethodBuilder<TResult> Create() => #if PROJECTN // ProjectN's AsyncTaskMethodBuilder<TResult>.Create() currently does additional debugger-related // work, so we need to delegate to it. new AsyncValueTaskMethodBuilder<TResult>() { _methodBuilder = AsyncTaskMethodBuilder<TResult>.Create() }; #else // _methodBuilder should be initialized to AsyncTaskMethodBuilder<TResult>.Create(), but on coreclr // that Create() is a nop, so we can just return the default here. default; #endif /// <summary>Begins running the builder with the associated state machine.</summary> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => // will provide the right ExecutionContext semantics AsyncMethodBuilderCore.Start(ref stateMachine); /// <summary>Associates the builder with the specified state machine.</summary> /// <param name="stateMachine">The state machine instance to associate with the builder.</param> public void SetStateMachine(IAsyncStateMachine stateMachine) => _methodBuilder.SetStateMachine(stateMachine); /// <summary>Marks the task as successfully completed.</summary> /// <param name="result">The result to use to complete the task.</param> public void SetResult(TResult result) { if (_useBuilder) { _methodBuilder.SetResult(result); } else { _result = result; _haveResult = true; } } /// <summary>Marks the task as failed and binds the specified exception to the task.</summary> /// <param name="exception">The exception to bind to the task.</param> public void SetException(Exception exception) => _methodBuilder.SetException(exception); /// <summary>Gets the task for this builder.</summary> public ValueTask<TResult> Task { get { if (_haveResult) { return new ValueTask<TResult>(_result); } else { _useBuilder = true; return new ValueTask<TResult>(_methodBuilder.Task); } } } /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">the awaiter</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); } /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">the awaiter</param> /// <param name="stateMachine">The state machine.</param> public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } } }
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; /// Draws a circular reticle in front of any object that the user points at. /// The circle dilates if the object is clickable. [AddComponentMenu("GoogleVR/UI/GvrReticlePointer")] [RequireComponent(typeof(Renderer))] public class GvrReticlePointer : GvrBasePointer { /// Number of segments making the reticle circle. public int reticleSegments = 20; /// Growth speed multiplier for the reticle/ public float reticleGrowthSpeed = 8.0f; // Private members private Material materialComp; // Current inner angle of the reticle (in degrees). private float reticleInnerAngle = 0.0f; // Current outer angle of the reticle (in degrees). private float reticleOuterAngle = 0.5f; // Current distance of the reticle (in meters). private float reticleDistanceInMeters = 10.0f; // Minimum inner angle of the reticle (in degrees). private const float kReticleMinInnerAngle = 0.0f; // Minimum outer angle of the reticle (in degrees). private const float kReticleMinOuterAngle = 0.5f; // Angle at which to expand the reticle when intersecting with an object // (in degrees). private const float kReticleGrowthAngle = 1.5f; // Minimum distance of the reticle (in meters). private const float kReticleDistanceMin = 0.45f; // Maximum distance of the reticle (in meters). private const float kReticleDistanceMax = 10.0f; // Current inner and outer diameters of the reticle, // before distance multiplication. private float reticleInnerDiameter = 0.0f; private float reticleOuterDiameter = 0.0f; protected override void Start () { base.Start(); CreateReticleVertices(); materialComp = gameObject.GetComponent<Renderer>().material; } void Update() { UpdateDiameters(); } /// This is called when the 'BaseInputModule' system should be enabled. public override void OnInputModuleEnabled() {} /// This is called when the 'BaseInputModule' system should be disabled. public override void OnInputModuleDisabled() {} /// Called when the user is pointing at valid GameObject. This can be a 3D /// or UI element. /// /// The targetObject is the object the user is pointing at. /// The intersectionPosition is where the ray intersected with the targetObject. /// The intersectionRay is the ray that was cast to determine the intersection. public override void OnPointerEnter(GameObject targetObject, Vector3 intersectionPosition, Ray intersectionRay, bool isInteractive) { SetPointerTarget(intersectionPosition, isInteractive); } /// Called every frame the user is still pointing at a valid GameObject. This /// can be a 3D or UI element. /// /// The targetObject is the object the user is pointing at. /// The intersectionPosition is where the ray intersected with the targetObject. /// The intersectionRay is the ray that was cast to determine the intersection. public override void OnPointerHover(GameObject targetObject, Vector3 intersectionPosition, Ray intersectionRay, bool isInteractive) { SetPointerTarget(intersectionPosition, isInteractive); } /// Called when the user's look no longer intersects an object previously /// intersected with a ray projected from the camera. /// This is also called just before **OnInputModuleDisabled** and may have have any of /// the values set as **null**. public override void OnPointerExit(GameObject targetObject) { reticleDistanceInMeters = kReticleDistanceMax; reticleInnerAngle = kReticleMinInnerAngle; reticleOuterAngle = kReticleMinOuterAngle; } /// Called when a trigger event is initiated. This is practically when /// the user begins pressing the trigger. public override void OnPointerClickDown() {} /// Called when a trigger event is finished. This is practically when /// the user releases the trigger. public override void OnPointerClickUp() {} public override float GetMaxPointerDistance() { return kReticleDistanceMax; } public override void GetPointerRadius(out float enterRadius, out float exitRadius) { float min_inner_angle_radians = Mathf.Deg2Rad * kReticleMinInnerAngle; float max_inner_angle_radians = Mathf.Deg2Rad * (kReticleMinInnerAngle + kReticleGrowthAngle); enterRadius = 2.0f * Mathf.Tan(min_inner_angle_radians); exitRadius = 2.0f * Mathf.Tan(max_inner_angle_radians); } private void CreateReticleVertices() { Mesh mesh = new Mesh(); gameObject.AddComponent<MeshFilter>(); GetComponent<MeshFilter>().mesh = mesh; int segments_count = reticleSegments; int vertex_count = (segments_count+1)*2; #region Vertices Vector3[] vertices = new Vector3[vertex_count]; const float kTwoPi = Mathf.PI * 2.0f; int vi = 0; for (int si = 0; si <= segments_count; ++si) { // Add two vertices for every circle segment: one at the beginning of the // prism, and one at the end of the prism. float angle = (float)si / (float)(segments_count) * kTwoPi; float x = Mathf.Sin(angle); float y = Mathf.Cos(angle); vertices[vi++] = new Vector3(x, y, 0.0f); // Outer vertex. vertices[vi++] = new Vector3(x, y, 1.0f); // Inner vertex. } #endregion #region Triangles int indices_count = (segments_count+1)*3*2; int[] indices = new int[indices_count]; int vert = 0; int idx = 0; for (int si = 0; si < segments_count; ++si) { indices[idx++] = vert+1; indices[idx++] = vert; indices[idx++] = vert+2; indices[idx++] = vert+1; indices[idx++] = vert+2; indices[idx++] = vert+3; vert += 2; } #endregion mesh.vertices = vertices; mesh.triangles = indices; mesh.RecalculateBounds(); ; } private void UpdateDiameters() { reticleDistanceInMeters = Mathf.Clamp(reticleDistanceInMeters, kReticleDistanceMin, kReticleDistanceMax); if (reticleInnerAngle < kReticleMinInnerAngle) { reticleInnerAngle = kReticleMinInnerAngle; } if (reticleOuterAngle < kReticleMinOuterAngle) { reticleOuterAngle = kReticleMinOuterAngle; } float inner_half_angle_radians = Mathf.Deg2Rad * reticleInnerAngle * 0.5f; float outer_half_angle_radians = Mathf.Deg2Rad * reticleOuterAngle * 0.5f; float inner_diameter = 2.0f * Mathf.Tan(inner_half_angle_radians); float outer_diameter = 2.0f * Mathf.Tan(outer_half_angle_radians); reticleInnerDiameter = Mathf.Lerp(reticleInnerDiameter, inner_diameter, Time.deltaTime * reticleGrowthSpeed); reticleOuterDiameter = Mathf.Lerp(reticleOuterDiameter, outer_diameter, Time.deltaTime * reticleGrowthSpeed); materialComp.SetFloat("_InnerDiameter", reticleInnerDiameter * reticleDistanceInMeters); materialComp.SetFloat("_OuterDiameter", reticleOuterDiameter * reticleDistanceInMeters); materialComp.SetFloat("_DistanceInMeters", reticleDistanceInMeters); } private void SetPointerTarget(Vector3 target, bool interactive) { Vector3 targetLocalPosition = transform.InverseTransformPoint(target); reticleDistanceInMeters = Mathf.Clamp(targetLocalPosition.z, kReticleDistanceMin, kReticleDistanceMax); if (interactive) { reticleInnerAngle = kReticleMinInnerAngle + kReticleGrowthAngle; reticleOuterAngle = kReticleMinOuterAngle + kReticleGrowthAngle; } else { reticleInnerAngle = kReticleMinInnerAngle; reticleOuterAngle = kReticleMinOuterAngle; } } }
using Lucene.Net.Diagnostics; using System; using System.Diagnostics; namespace Lucene.Net.Codecs.Compressing { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using IndexOutput = Lucene.Net.Store.IndexOutput; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; /// <summary> /// Efficient index format for block-based <see cref="Codec"/>s. /// <para/> this writer generates a file which can be loaded into memory using /// memory-efficient data structures to quickly locate the block that contains /// any document. /// <para>In order to have a compact in-memory representation, for every block of /// 1024 chunks, this index computes the average number of bytes per /// chunk and for every chunk, only stores the difference between /// <list type="bullet"> /// <li>${chunk number} * ${average length of a chunk}</li> /// <li>and the actual start offset of the chunk</li> /// </list> /// </para> /// <para>Data is written as follows:</para> /// <list type="bullet"> /// <li>PackedIntsVersion, &lt;Block&gt;<sup>BlockCount</sup>, BlocksEndMarker</li> /// <li>PackedIntsVersion --&gt; <see cref="PackedInt32s.VERSION_CURRENT"/> as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </li> /// <li>BlocksEndMarker --&gt; <tt>0</tt> as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) , this marks the end of blocks since blocks are not allowed to start with <tt>0</tt></li> /// <li>Block --&gt; BlockChunks, &lt;DocBases&gt;, &lt;StartPointers&gt;</li> /// <li>BlockChunks --&gt; a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) which is the number of chunks encoded in the block</li> /// <li>DocBases --&gt; DocBase, AvgChunkDocs, BitsPerDocBaseDelta, DocBaseDeltas</li> /// <li>DocBase --&gt; first document ID of the block of chunks, as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </li> /// <li>AvgChunkDocs --&gt; average number of documents in a single chunk, as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </li> /// <li>BitsPerDocBaseDelta --&gt; number of bits required to represent a delta from the average using <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">ZigZag encoding</a></li> /// <li>DocBaseDeltas --&gt; packed (<see cref="PackedInt32s"/>) array of BlockChunks elements of BitsPerDocBaseDelta bits each, representing the deltas from the average doc base using <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">ZigZag encoding</a>.</li> /// <li>StartPointers --&gt; StartPointerBase, AvgChunkSize, BitsPerStartPointerDelta, StartPointerDeltas</li> /// <li>StartPointerBase --&gt; the first start pointer of the block, as a VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </li> /// <li>AvgChunkSize --&gt; the average size of a chunk of compressed documents, as a VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </li> /// <li>BitsPerStartPointerDelta --&gt; number of bits required to represent a delta from the average using <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">ZigZag encoding</a></li> /// <li>StartPointerDeltas --&gt; packed (<see cref="PackedInt32s"/>) array of BlockChunks elements of BitsPerStartPointerDelta bits each, representing the deltas from the average start pointer using <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">ZigZag encoding</a></li> /// <li>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(IndexOutput)"/>) </li> /// </list> /// <para>Notes</para> /// <list type="bullet"> /// <li>For any block, the doc base of the n-th chunk can be restored with /// <c>DocBase + AvgChunkDocs * n + DocBaseDeltas[n]</c>.</li> /// <li>For any block, the start pointer of the n-th chunk can be restored with /// <c>StartPointerBase + AvgChunkSize * n + StartPointerDeltas[n]</c>.</li> /// <li>Once data is loaded into memory, you can lookup the start pointer of any /// document by performing two binary searches: a first one based on the values /// of DocBase in order to find the right block, and then inside the block based /// on DocBaseDeltas (by reconstructing the doc bases for every chunk).</li> /// </list> /// @lucene.internal /// </summary> public sealed class CompressingStoredFieldsIndexWriter : IDisposable { internal const int BLOCK_SIZE = 1024; // number of chunks to serialize at once internal static long MoveSignToLowOrderBit(long n) { return (n >> 63) ^ (n << 1); } internal readonly IndexOutput fieldsIndexOut; internal int totalDocs; internal int blockDocs; internal int blockChunks; internal long firstStartPointer; internal long maxStartPointer; internal readonly int[] docBaseDeltas; internal readonly long[] startPointerDeltas; internal CompressingStoredFieldsIndexWriter(IndexOutput indexOutput) { this.fieldsIndexOut = indexOutput; Reset(); totalDocs = 0; docBaseDeltas = new int[BLOCK_SIZE]; startPointerDeltas = new long[BLOCK_SIZE]; fieldsIndexOut.WriteVInt32(PackedInt32s.VERSION_CURRENT); } private void Reset() { blockChunks = 0; blockDocs = 0; firstStartPointer = -1; // means unset } private void WriteBlock() { if (Debugging.AssertsEnabled) Debugging.Assert(blockChunks > 0); fieldsIndexOut.WriteVInt32(blockChunks); // The trick here is that we only store the difference from the average start // pointer or doc base, this helps save bits per value. // And in order to prevent a few chunks that would be far from the average to // raise the number of bits per value for all of them, we only encode blocks // of 1024 chunks at once // See LUCENE-4512 // doc bases int avgChunkDocs; if (blockChunks == 1) { avgChunkDocs = 0; } else { avgChunkDocs = (int)Math.Round((float)(blockDocs - docBaseDeltas[blockChunks - 1]) / (blockChunks - 1)); } fieldsIndexOut.WriteVInt32(totalDocs - blockDocs); // docBase fieldsIndexOut.WriteVInt32(avgChunkDocs); int docBase = 0; long maxDelta = 0; for (int i = 0; i < blockChunks; ++i) { int delta = docBase - avgChunkDocs * i; maxDelta |= MoveSignToLowOrderBit(delta); docBase += docBaseDeltas[i]; } int bitsPerDocBase = PackedInt32s.BitsRequired(maxDelta); fieldsIndexOut.WriteVInt32(bitsPerDocBase); PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(fieldsIndexOut, PackedInt32s.Format.PACKED, blockChunks, bitsPerDocBase, 1); docBase = 0; for (int i = 0; i < blockChunks; ++i) { long delta = docBase - avgChunkDocs * i; if (Debugging.AssertsEnabled) Debugging.Assert(PackedInt32s.BitsRequired(MoveSignToLowOrderBit(delta)) <= writer.BitsPerValue); writer.Add(MoveSignToLowOrderBit(delta)); docBase += docBaseDeltas[i]; } writer.Finish(); // start pointers fieldsIndexOut.WriteVInt64(firstStartPointer); long avgChunkSize; if (blockChunks == 1) { avgChunkSize = 0; } else { avgChunkSize = (maxStartPointer - firstStartPointer) / (blockChunks - 1); } fieldsIndexOut.WriteVInt64(avgChunkSize); long startPointer = 0; maxDelta = 0; for (int i = 0; i < blockChunks; ++i) { startPointer += startPointerDeltas[i]; long delta = startPointer - avgChunkSize * i; maxDelta |= MoveSignToLowOrderBit(delta); } int bitsPerStartPointer = PackedInt32s.BitsRequired(maxDelta); fieldsIndexOut.WriteVInt32(bitsPerStartPointer); writer = PackedInt32s.GetWriterNoHeader(fieldsIndexOut, PackedInt32s.Format.PACKED, blockChunks, bitsPerStartPointer, 1); startPointer = 0; for (int i = 0; i < blockChunks; ++i) { startPointer += startPointerDeltas[i]; long delta = startPointer - avgChunkSize * i; if (Debugging.AssertsEnabled) Debugging.Assert(PackedInt32s.BitsRequired(MoveSignToLowOrderBit(delta)) <= writer.BitsPerValue); writer.Add(MoveSignToLowOrderBit(delta)); } writer.Finish(); } internal void WriteIndex(int numDocs, long startPointer) { if (blockChunks == BLOCK_SIZE) { WriteBlock(); Reset(); } if (firstStartPointer == -1) { firstStartPointer = maxStartPointer = startPointer; } if (Debugging.AssertsEnabled) Debugging.Assert(firstStartPointer > 0 && startPointer >= firstStartPointer); docBaseDeltas[blockChunks] = numDocs; startPointerDeltas[blockChunks] = startPointer - maxStartPointer; ++blockChunks; blockDocs += numDocs; totalDocs += numDocs; maxStartPointer = startPointer; } internal void Finish(int numDocs, long maxPointer) { if (numDocs != totalDocs) { throw new InvalidOperationException("Expected " + numDocs + " docs, but got " + totalDocs); } if (blockChunks > 0) { WriteBlock(); } fieldsIndexOut.WriteVInt32(0); // end marker fieldsIndexOut.WriteVInt64(maxPointer); CodecUtil.WriteFooter(fieldsIndexOut); } public void Dispose() { fieldsIndexOut.Dispose(); } } }
using System; using System.Collections; using System.Globalization; using System.IO; using Raksha.Utilities; using Raksha.Utilities.Collections; namespace Raksha.Bcpg.OpenPgp { /// <remarks> /// Often a PGP key ring file is made up of a succession of master/sub-key key rings. /// If you want to read an entire public key file in one hit this is the class for you. /// </remarks> public class PgpPublicKeyRingBundle { private readonly IDictionary pubRings; private readonly IList order; private PgpPublicKeyRingBundle( IDictionary pubRings, IList order) { this.pubRings = pubRings; this.order = order; } public PgpPublicKeyRingBundle( byte[] encoding) : this(new MemoryStream(encoding, false)) { } /// <summary>Build a PgpPublicKeyRingBundle from the passed in input stream.</summary> /// <param name="inputStream">Input stream containing data.</param> /// <exception cref="IOException">If a problem parsing the stream occurs.</exception> /// <exception cref="PgpException">If an object is encountered which isn't a PgpPublicKeyRing.</exception> public PgpPublicKeyRingBundle( Stream inputStream) : this(new PgpObjectFactory(inputStream).AllPgpObjects()) { } public PgpPublicKeyRingBundle( IEnumerable e) { this.pubRings = Platform.CreateHashtable(); this.order = Platform.CreateArrayList(); foreach (object obj in e) { PgpPublicKeyRing pgpPub = obj as PgpPublicKeyRing; if (pgpPub == null) { throw new PgpException(obj.GetType().FullName + " found where PgpPublicKeyRing expected"); } long key = pgpPub.GetPublicKey().KeyId; pubRings.Add(key, pgpPub); order.Add(key); } } [Obsolete("Use 'Count' property instead")] public int Size { get { return order.Count; } } /// <summary>Return the number of key rings in this collection.</summary> public int Count { get { return order.Count; } } /// <summary>Allow enumeration of the public key rings making up this collection.</summary> public IEnumerable GetKeyRings() { return new EnumerableProxy(pubRings.Values); } /// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary> /// <param name="userId">The user ID to be matched.</param> /// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns> public IEnumerable GetKeyRings( string userId) { return GetKeyRings(userId, false, false); } /// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary> /// <param name="userId">The user ID to be matched.</param> /// <param name="matchPartial">If true, userId need only be a substring of an actual ID string to match.</param> /// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns> public IEnumerable GetKeyRings( string userId, bool matchPartial) { return GetKeyRings(userId, matchPartial, false); } /// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary> /// <param name="userId">The user ID to be matched.</param> /// <param name="matchPartial">If true, userId need only be a substring of an actual ID string to match.</param> /// <param name="ignoreCase">If true, case is ignored in user ID comparisons.</param> /// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns> public IEnumerable GetKeyRings( string userId, bool matchPartial, bool ignoreCase) { IList rings = Platform.CreateArrayList(); if (ignoreCase) { userId = userId.ToLowerInvariant(); } foreach (PgpPublicKeyRing pubRing in GetKeyRings()) { foreach (string nextUserID in pubRing.GetPublicKey().GetUserIds()) { string next = nextUserID; if (ignoreCase) { next = next.ToLowerInvariant(); } if (matchPartial) { if (next.IndexOf(userId) > -1) { rings.Add(pubRing); } } else { if (next.Equals(userId)) { rings.Add(pubRing); } } } } return new EnumerableProxy(rings); } /// <summary>Return the PGP public key associated with the given key id.</summary> /// <param name="keyId">The ID of the public key to return.</param> public PgpPublicKey GetPublicKey( long keyId) { foreach (PgpPublicKeyRing pubRing in GetKeyRings()) { PgpPublicKey pub = pubRing.GetPublicKey(keyId); if (pub != null) { return pub; } } return null; } /// <summary>Return the public key ring which contains the key referred to by keyId</summary> /// <param name="keyId">key ID to match against</param> public PgpPublicKeyRing GetPublicKeyRing( long keyId) { if (pubRings.Contains(keyId)) { return (PgpPublicKeyRing)pubRings[keyId]; } foreach (PgpPublicKeyRing pubRing in GetKeyRings()) { PgpPublicKey pub = pubRing.GetPublicKey(keyId); if (pub != null) { return pubRing; } } return null; } /// <summary> /// Return true if a key matching the passed in key ID is present, false otherwise. /// </summary> /// <param name="keyID">key ID to look for.</param> public bool Contains( long keyID) { return GetPublicKey(keyID) != null; } public byte[] GetEncoded() { MemoryStream bOut = new MemoryStream(); Encode(bOut); return bOut.ToArray(); } public void Encode( Stream outStr) { BcpgOutputStream bcpgOut = BcpgOutputStream.Wrap(outStr); foreach (long key in order) { PgpPublicKeyRing sec = (PgpPublicKeyRing) pubRings[key]; sec.Encode(bcpgOut); } } /// <summary> /// Return a new bundle containing the contents of the passed in bundle and /// the passed in public key ring. /// </summary> /// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be added to.</param> /// <param name="publicKeyRing">The key ring to be added.</param> /// <returns>A new <c>PgpPublicKeyRingBundle</c> merging the current one with the passed in key ring.</returns> /// <exception cref="ArgumentException">If the keyId for the passed in key ring is already present.</exception> public static PgpPublicKeyRingBundle AddPublicKeyRing( PgpPublicKeyRingBundle bundle, PgpPublicKeyRing publicKeyRing) { long key = publicKeyRing.GetPublicKey().KeyId; if (bundle.pubRings.Contains(key)) { throw new ArgumentException("Bundle already contains a key with a keyId for the passed in ring."); } IDictionary newPubRings = Platform.CreateHashtable(bundle.pubRings); IList newOrder = Platform.CreateArrayList(bundle.order); newPubRings[key] = publicKeyRing; newOrder.Add(key); return new PgpPublicKeyRingBundle(newPubRings, newOrder); } /// <summary> /// Return a new bundle containing the contents of the passed in bundle with /// the passed in public key ring removed. /// </summary> /// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be removed from.</param> /// <param name="publicKeyRing">The key ring to be removed.</param> /// <returns>A new <c>PgpPublicKeyRingBundle</c> not containing the passed in key ring.</returns> /// <exception cref="ArgumentException">If the keyId for the passed in key ring is not present.</exception> public static PgpPublicKeyRingBundle RemovePublicKeyRing( PgpPublicKeyRingBundle bundle, PgpPublicKeyRing publicKeyRing) { long key = publicKeyRing.GetPublicKey().KeyId; if (!bundle.pubRings.Contains(key)) { throw new ArgumentException("Bundle does not contain a key with a keyId for the passed in ring."); } IDictionary newPubRings = Platform.CreateHashtable(bundle.pubRings); IList newOrder = Platform.CreateArrayList(bundle.order); newPubRings.Remove(key); newOrder.Remove(key); return new PgpPublicKeyRingBundle(newPubRings, newOrder); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Mercurial.Attributes; namespace Mercurial { /// <summary> /// This class implements the "hg bundle" command (<see href="http://www.selenic.com/mercurial/hg.1.html#bundle"/>): /// create a changegroup file. /// </summary> public sealed class BundleCommand : MercurialCommandBase<BundleCommand> { /// <summary> /// This is the backing field for the <see cref="BaseRevisions"/> property. /// </summary> private readonly List<RevSpec> _BaseRevisions = new List<RevSpec>(); /// <summary> /// This is the backing field for the <see cref="Revisions"/> property. /// </summary> private readonly List<RevSpec> _Revisions = new List<RevSpec>(); /// <summary> /// This is the backing field for the <see cref="Branches"/> property. /// </summary> private readonly List<string> _Branches = new List<string>(); /// <summary> /// This is the backing field for the <see cref="Destination"/> property. /// </summary> private string _Destination = string.Empty; /// <summary> /// This is the backing field for the <see cref="FileName"/> property. /// </summary> private string _FileName = string.Empty; /// <summary> /// This is the backing field for the <see cref="SshCommand"/> property. /// </summary> private string _SshCommand = string.Empty; /// <summary> /// This is the backing field for the <see cref="RemoteCommand"/> property. /// </summary> private string _RemoteCommand = string.Empty; /// <summary> /// This is the backing field for the <see cref="VerifyServerCertificate"/> property. /// </summary> private bool _VerifyServerCertificate = true; /// <summary> /// Initializes a new instance of the <see cref="BundleCommand"/> class. /// </summary> public BundleCommand() : base("bundle") { // Do nothing here } /// <summary> /// Gets or sets a value indicating whether to run even when the destination is unrelated. /// Default is <c>false</c>. /// </summary> [BooleanArgument(TrueOption = "--force")] [DefaultValue(false)] public bool Force { get; set; } /// <summary> /// Gets or sets a value indicating whether to verify the server certificate. If set to <c>false</c>, will ignore web.cacerts configuration. /// Default value is <c>true</c>. /// </summary> [BooleanArgument(FalseOption = "--insecure")] [DefaultValue(true)] public bool VerifyServerCertificate { get { return _VerifyServerCertificate; } set { RequiresVersion(new Version(1, 7, 5), "VerifyServerCertificate property of the BundleCommand class"); _VerifyServerCertificate = value; } } /// <summary> /// Sets the <see cref="SshCommand"/> property to the specified value and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="SshCommand"/> property. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithSshCommand(string value) { SshCommand = value; return this; } /// <summary> /// Sets the <see cref="RemoteCommand"/> property to the specified value and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="RemoteCommand"/> property. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithRemoteCommand(string value) { RemoteCommand = value; return this; } /// <summary> /// Sets the <see cref="VerifyServerCertificate"/> property to the specified value and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="VerifyServerCertificate"/> property. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithVerifyServerCertificate(bool value) { VerifyServerCertificate = value; return this; } /// <summary> /// Gets the collection of revisions to be added to the destination, and thus include in the bundle. /// If empty, include every changeset from the source repository that isn't in the destination. /// Default is empty. /// </summary> [RepeatableArgument(Option = "--rev")] public Collection<RevSpec> Revisions { get { return new Collection<RevSpec>(_Revisions); } } /// <summary> /// Gets the collection of branches to bundle. /// Default is empty. /// </summary> [RepeatableArgument(Option = "--branch")] public Collection<string> Branches { get { return new Collection<string>(_Branches); } } /// <summary> /// Gets the collection of revisions assumed to be available at the destination, and thus not /// included in the bundle. Mostly used when leaving <see cref="Destination"/> empty, /// to calculate an "assumed" bundle for a target repository that may not be available for /// comparison. /// Default is empty. /// </summary> [RepeatableArgument(Option = "--base")] public Collection<RevSpec> BaseRevisions { get { return new Collection<RevSpec>(_BaseRevisions); } } /// <summary> /// Gets or sets a value indicating whether to bundle all the changesets in the repository. /// Default is <c>false</c>. /// </summary> [BooleanArgument(TrueOption = "--all")] [DefaultValue(false)] public bool All { get; set; } /// <summary> /// Gets or sets the <see cref="MercurialCompressionType">compression type</see> to use /// for the bundle file. Default is <c>MercurialCompressionType.BZip2</c>. /// </summary> [DefaultValue(MercurialCompressionType.BZip2)] [EnumArgument(MercurialCompressionType.None, "--type", "none")] [EnumArgument(MercurialCompressionType.GZip, "--type", "gzip")] public MercurialCompressionType Compression { get; set; } /// <summary> /// Gets or sets the full path to and name of the file to save the bundle to. /// Default is <see cref="string.Empty"/>. /// </summary> [NullableArgument] [DefaultValue("")] public string FileName { get { return _FileName; } set { _FileName = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets the path or URL to the destination repository that the bundled will be /// built for. The repository will be used to figure out which changesets to add to the /// bundle. /// Default is <see cref="string.Empty"/>. /// </summary> [NullableArgument] [DefaultValue("")] public string Destination { get { return _Destination; } set { _Destination = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets the ssh command to use when cloning. /// Default is <see cref="string.Empty"/>. /// </summary> [NullableArgument(NonNullOption = "--ssh")] [DefaultValue("")] public string SshCommand { get { return _SshCommand; } set { _SshCommand = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets the hg command to run on the remote side. /// Default is <see cref="string.Empty"/>. /// </summary> [NullableArgument(NonNullOption = "--remotecmd")] [DefaultValue("")] public string RemoteCommand { get { return _RemoteCommand; } set { _RemoteCommand = (value ?? string.Empty).Trim(); } } /// <summary> /// Validates the command configuration. This method should throw the necessary /// exceptions to signal missing or incorrect configuration (like attempting to /// add files to the repository without specifying which files to add.) /// </summary> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. /// </remarks> /// <exception cref="InvalidOperationException"> /// <para>The 'bundle' command requires FileName to be specified.</para> /// <para>- or -</para> /// <para>The <see cref="VerifyServerCertificate"/> command was used with Mercurial 1.7.4 or older.</para> /// </exception> public override void Validate() { base.Validate(); if (!VerifyServerCertificate && ClientExecutable.CurrentVersion < new Version(1, 7, 5)) throw new InvalidOperationException("The 'VerifyServerCertificate' property is only available in Mercurial 1.7.5 and newer"); if (StringEx.IsNullOrWhiteSpace(FileName)) throw new InvalidOperationException("The 'bundle' command requires FileName to be specified"); } /// <summary> /// Sets the <see cref="Force"/> property to the specified value and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="Force"/> property, /// defaults to <c>true</c>. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithForce(bool value = true) { Force = value; return this; } /// <summary> /// Adds the value to the <see cref="Revisions"/> collection property and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The value to add to the <see cref="Revisions"/> collection property. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithRevision(RevSpec value) { Revisions.Add(value); return this; } /// <summary> /// Adds the value to the <see cref="Branches"/> collection property and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The value to add to the <see cref="Branches"/> collection property. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithBranch(string value) { Branches.Add(value); return this; } /// <summary> /// Adds the value to the <see cref="BaseRevisions"/> collection property and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The value to add to the <see cref="BaseRevisions"/> collection property. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithBaseRevision(RevSpec value) { BaseRevisions.Add(value); return this; } /// <summary> /// Sets the <see cref="All"/> property to the specified value and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="All"/> property, /// defaults to <c>true</c>. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithAll(bool value = true) { All = value; return this; } /// <summary> /// Sets the <see cref="Compression"/> property to the specified value and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="Compression"/> property. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithCompression(MercurialCompressionType value) { Compression = value; return this; } /// <summary> /// Sets the <see cref="FileName"/> property to the specified value and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="FileName"/> property. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithFileName(string value) { FileName = value; return this; } /// <summary> /// Sets the <see cref="Destination"/> property to the specified value and /// returns this <see cref="BundleCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="Destination"/> property. /// </param> /// <returns> /// This <see cref="BundleCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public BundleCommand WithDestination(string value) { Destination = value; return this; } /// <summary> /// This method should throw the appropriate exception depending on the contents of /// the <paramref name="exitCode"/> and <paramref name="standardErrorOutput"/> /// parameters, or simply return if the execution is considered successful. /// </summary> /// <param name="exitCode"> /// The exit code from executing the command line client. /// </param> /// <param name="standardErrorOutput"> /// The standard error output from executing the command client. /// </param> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. The default behavior is to throw a <see cref="MercurialExecutionException"/> /// if <paramref name="exitCode"/> is not zero. If you require different behavior, don't call the base /// method. /// </remarks> /// <exception cref="NoChangesFoundMercurialExecutionException"> /// <para><paramref name="exitCode"/> is <c>1</c>.</para> /// </exception> /// <exception cref="MercurialExecutionException"> /// <para><paramref name="exitCode"/> is not <c>0</c> or <c>1</c>.</para> /// </exception> protected override void ThrowOnUnsuccessfulExecution(int exitCode, string standardErrorOutput) { switch (exitCode) { case 0: break; case 1: throw new NoChangesFoundMercurialExecutionException(exitCode, standardErrorOutput); default: base.ThrowOnUnsuccessfulExecution(exitCode, standardErrorOutput); break; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.Cx.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTransitionRouteGroupsClientTest { [xunit::FactAttribute] public void GetTransitionRouteGroupRequestObject() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.GetTransitionRouteGroup(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTransitionRouteGroupRequestObjectAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.GetTransitionRouteGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.GetTransitionRouteGroupAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTransitionRouteGroup() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.GetTransitionRouteGroup(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTransitionRouteGroupAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.GetTransitionRouteGroupAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.GetTransitionRouteGroupAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTransitionRouteGroupResourceNames() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.GetTransitionRouteGroup(request.TransitionRouteGroupName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTransitionRouteGroupResourceNamesAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.GetTransitionRouteGroupAsync(request.TransitionRouteGroupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.GetTransitionRouteGroupAsync(request.TransitionRouteGroupName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTransitionRouteGroupRequestObject() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.CreateTransitionRouteGroup(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTransitionRouteGroupRequestObjectAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.CreateTransitionRouteGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.CreateTransitionRouteGroupAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTransitionRouteGroup() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.CreateTransitionRouteGroup(request.Parent, request.TransitionRouteGroup); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTransitionRouteGroupAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.CreateTransitionRouteGroupAsync(request.Parent, request.TransitionRouteGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.CreateTransitionRouteGroupAsync(request.Parent, request.TransitionRouteGroup, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTransitionRouteGroupResourceNames() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.CreateTransitionRouteGroup(request.ParentAsFlowName, request.TransitionRouteGroup); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTransitionRouteGroupResourceNamesAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.CreateTransitionRouteGroupAsync(request.ParentAsFlowName, request.TransitionRouteGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.CreateTransitionRouteGroupAsync(request.ParentAsFlowName, request.TransitionRouteGroup, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTransitionRouteGroupRequestObject() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new wkt::FieldMask(), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.UpdateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.UpdateTransitionRouteGroup(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTransitionRouteGroupRequestObjectAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new wkt::FieldMask(), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.UpdateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.UpdateTransitionRouteGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.UpdateTransitionRouteGroupAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTransitionRouteGroup() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new wkt::FieldMask(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.UpdateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.UpdateTransitionRouteGroup(request.TransitionRouteGroup, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTransitionRouteGroupAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new wkt::FieldMask(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.UpdateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.UpdateTransitionRouteGroupAsync(request.TransitionRouteGroup, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.UpdateTransitionRouteGroupAsync(request.TransitionRouteGroup, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTransitionRouteGroupRequestObject() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), Force = true, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); client.DeleteTransitionRouteGroup(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTransitionRouteGroupRequestObjectAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), Force = true, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); await client.DeleteTransitionRouteGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTransitionRouteGroupAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTransitionRouteGroup() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); client.DeleteTransitionRouteGroup(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTransitionRouteGroupAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); await client.DeleteTransitionRouteGroupAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTransitionRouteGroupAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTransitionRouteGroupResourceNames() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); client.DeleteTransitionRouteGroup(request.TransitionRouteGroupName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTransitionRouteGroupResourceNamesAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); await client.DeleteTransitionRouteGroupAsync(request.TransitionRouteGroupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTransitionRouteGroupAsync(request.TransitionRouteGroupName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
using System; using System.IO; using System.Text; using NUnit.Framework; using Org.BouncyCastle.Bcpg.Sig; using Org.BouncyCastle.Utilities.Date; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests { [TestFixture] public class PgpSignatureTest : SimpleTest { private const int[] NO_PREFERENCES = null; private static readonly int[] PREFERRED_SYMMETRIC_ALGORITHMS = new int[] { (int)SymmetricKeyAlgorithmTag.Aes128, (int)SymmetricKeyAlgorithmTag.TripleDes }; private static readonly int[] PREFERRED_HASH_ALGORITHMS = new int[] { (int)HashAlgorithmTag.Sha1, (int)HashAlgorithmTag.Sha256 }; private static readonly int[] PREFERRED_COMPRESSION_ALGORITHMS = new int[] { (int)CompressionAlgorithmTag.ZLib }; private const int TEST_EXPIRATION_TIME = 10000; private const string TEST_USER_ID = "test user id"; private static readonly byte[] TEST_DATA = Encoding.ASCII.GetBytes("hello world!\nhello world!\n"); private static readonly byte[] TEST_DATA_WITH_CRLF = Encoding.ASCII.GetBytes("hello world!\r\nhello world!\r\n"); private static readonly byte[] dsaKeyRing = Base64.Decode( "lQHhBD9HBzURBACzkxRCVGJg5+Ld9DU4Xpnd4LCKgMq7YOY7Gi0EgK92gbaa6+zQ" + "oQFqz1tt3QUmpz3YVkm/zLESBBtC1ACIXGggUdFMUr5I87+1Cb6vzefAtGt8N5VV" + "1F/MXv1gJz4Bu6HyxL/ncfe71jsNhav0i4yAjf2etWFj53zK6R+Ojg5H6wCgpL9/" + "tXVfGP8SqFvyrN/437MlFSUEAIN3V6j/MUllyrZglrtr2+RWIwRrG/ACmrF6hTug" + "Ol4cQxaDYNcntXbhlTlJs9MxjTH3xxzylyirCyq7HzGJxZzSt6FTeh1DFYzhJ7Qu" + "YR1xrSdA6Y0mUv0ixD5A4nPHjupQ5QCqHGeRfFD/oHzD4zqBnJp/BJ3LvQ66bERJ" + "mKl5A/4uj3HoVxpb0vvyENfRqKMmGBISycY4MoH5uWfb23FffsT9r9KL6nJ4syLz" + "aRR0gvcbcjkc9Z3epI7gr3jTrb4d8WPxsDbT/W1tv9bG/EHawomLcihtuUU68Uej" + "6/wZot1XJqu2nQlku57+M/V2X1y26VKsipolPfja4uyBOOyvbP4DAwIDIBTxWjkC" + "GGAWQO2jy9CTvLHJEoTO7moHrp1FxOVpQ8iJHyRqZzLllO26OzgohbiPYz8u9qCu" + "lZ9Xn7QzRXJpYyBFY2hpZG5hIChEU0EgVGVzdCBLZXkpIDxlcmljQGJvdW5jeWNh" + "c3RsZS5vcmc+iFkEExECABkFAj9HBzUECwcDAgMVAgMDFgIBAh4BAheAAAoJEM0j" + "9enEyjRDAlwAnjTjjt57NKIgyym7OTCwzIU3xgFpAJ0VO5m5PfQKmGJRhaewLSZD" + "4nXkHg=="); private static readonly char[] dsaPass = "hello world".ToCharArray(); private static readonly byte[] rsaKeyRing = Base64.Decode( "lQIEBEBXUNMBBADScQczBibewnbCzCswc/9ut8R0fwlltBRxMW0NMdKJY2LF" + "7k2COeLOCIU95loJGV6ulbpDCXEO2Jyq8/qGw1qD3SCZNXxKs3GS8Iyh9Uwd" + "VL07nMMYl5NiQRsFB7wOb86+94tYWgvikVA5BRP5y3+O3GItnXnpWSJyREUy" + "6WI2QQAGKf4JAwIVmnRs4jtTX2DD05zy2mepEQ8bsqVAKIx7lEwvMVNcvg4Y" + "8vFLh9Mf/uNciwL4Se/ehfKQ/AT0JmBZduYMqRU2zhiBmxj4cXUQ0s36ysj7" + "fyDngGocDnM3cwPxaTF1ZRBQHSLewP7dqE7M73usFSz8vwD/0xNOHFRLKbsO" + "RqDlLA1Cg2Yd0wWPS0o7+qqk9ndqrjjSwMM8ftnzFGjShAdg4Ca7fFkcNePP" + "/rrwIH472FuRb7RbWzwXA4+4ZBdl8D4An0dwtfvAO+jCZSrLjmSpxEOveJxY" + "GduyR4IA4lemvAG51YHTHd4NXheuEqsIkn1yarwaaj47lFPnxNOElOREMdZb" + "nkWQb1jfgqO24imEZgrLMkK9bJfoDnlF4k6r6hZOp5FSFvc5kJB4cVo1QJl4" + "pwCSdoU6luwCggrlZhDnkGCSuQUUW45NE7Br22NGqn4/gHs0KCsWbAezApGj" + "qYUCfX1bcpPzUMzUlBaD5rz2vPeO58CDtBJ0ZXN0ZXIgPHRlc3RAdGVzdD6I" + "sgQTAQIAHAUCQFdQ0wIbAwQLBwMCAxUCAwMWAgECHgECF4AACgkQs8JyyQfH" + "97I1QgP8Cd+35maM2cbWV9iVRO+c5456KDi3oIUSNdPf1NQrCAtJqEUhmMSt" + "QbdiaFEkPrORISI/2htXruYn0aIpkCfbUheHOu0sef7s6pHmI2kOQPzR+C/j" + "8D9QvWsPOOso81KU2axUY8zIer64Uzqc4szMIlLw06c8vea27RfgjBpSCryw" + "AgAA"); private static readonly char[] rsaPass = "2002 Buffalo Sabres".ToCharArray(); private static readonly byte[] nullPacketsSubKeyBinding = Base64.Decode( "iDYEGBECAAAAACp9AJ9PlJCrFpi+INwG7z61eku2Wg1HaQCgl33X5Egj+Kf7F9CXIWj2iFCvQDo="); public override void PerformTest() { // // RSA tests // PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(rsaKeyRing); IPgpSecretKey secretKey = pgpPriv.GetSecretKey(); IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(rsaPass); try { doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("RSA wrong key test failed."); } catch (PgpException) { // expected } try { doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("RSA V3 wrong key test failed."); } catch (PgpException) { // expected } // // certifications // PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.KeyRevocation, pgpPrivKey); PgpSignature sig = sGen.GenerateCertification(secretKey.PublicKey); sig.InitVerify(secretKey.PublicKey); if (!sig.VerifyCertification(secretKey.PublicKey)) { Fail("revocation verification failed."); } PgpSecretKeyRing pgpDSAPriv = new PgpSecretKeyRing(dsaKeyRing); IPgpSecretKey secretDSAKey = pgpDSAPriv.GetSecretKey(); IPgpPrivateKey pgpPrivDSAKey = secretDSAKey.ExtractPrivateKey(dsaPass); sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); PgpSignatureSubpacketGenerator unhashedGen = new PgpSignatureSubpacketGenerator(); PgpSignatureSubpacketGenerator hashedGen = new PgpSignatureSubpacketGenerator(); hashedGen.SetSignatureExpirationTime(false, TEST_EXPIRATION_TIME); hashedGen.SetSignerUserId(true, TEST_USER_ID); hashedGen.SetPreferredCompressionAlgorithms(false, PREFERRED_COMPRESSION_ALGORITHMS); hashedGen.SetPreferredHashAlgorithms(false, PREFERRED_HASH_ALGORITHMS); hashedGen.SetPreferredSymmetricAlgorithms(false, PREFERRED_SYMMETRIC_ALGORITHMS); sGen.SetHashedSubpackets(hashedGen.Generate()); sGen.SetUnhashedSubpackets(unhashedGen.Generate()); sig = sGen.GenerateCertification(secretDSAKey.PublicKey, secretKey.PublicKey); byte[] sigBytes = sig.GetEncoded(); PgpObjectFactory f = new PgpObjectFactory(sigBytes); sig = ((PgpSignatureList) f.NextPgpObject())[0]; sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(secretDSAKey.PublicKey, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } var hashedPcks = sig.GetHashedSubPackets(); var unhashedPcks = sig.GetUnhashedSubPackets(); if (hashedPcks.Count != 6) { Fail("wrong number of hashed packets found."); } if (unhashedPcks.Count != 1) { Fail("wrong number of unhashed packets found."); } if (!hashedPcks.GetSignerUserId().Equals(TEST_USER_ID)) { Fail("test userid not matching"); } if (hashedPcks.GetSignatureExpirationTime() != TEST_EXPIRATION_TIME) { Fail("test signature expiration time not matching"); } if (unhashedPcks.GetIssuerKeyId() != secretDSAKey.KeyId) { Fail("wrong issuer key ID found in certification"); } int[] prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms(); preferredAlgorithmCheck("compression", PREFERRED_COMPRESSION_ALGORITHMS, prefAlgs); prefAlgs = hashedPcks.GetPreferredHashAlgorithms(); preferredAlgorithmCheck("hash", PREFERRED_HASH_ALGORITHMS, prefAlgs); prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms(); preferredAlgorithmCheck("symmetric", PREFERRED_SYMMETRIC_ALGORITHMS, prefAlgs); SignatureSubpacketTag[] criticalHashed = hashedPcks.GetCriticalTags(); if (criticalHashed.Length != 1) { Fail("wrong number of critical packets found."); } if (criticalHashed[0] != SignatureSubpacketTag.SignerUserId) { Fail("wrong critical packet found in tag list."); } // // no packets passed // sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); sGen.SetHashedSubpackets(null); sGen.SetUnhashedSubpackets(null); sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey); sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } hashedPcks = sig.GetHashedSubPackets(); if (hashedPcks.Count != 1) { Fail("found wrong number of hashed packets"); } unhashedPcks = sig.GetUnhashedSubPackets(); if (unhashedPcks.Count != 1) { Fail("found wrong number of unhashed packets"); } try { sig.VerifyCertification(secretKey.PublicKey); Fail("failed to detect non-key signature."); } catch (InvalidOperationException) { // expected } // // override hash packets // sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); hashedGen = new PgpSignatureSubpacketGenerator(); DateTime creationTime = new DateTime(1973, 7, 27); hashedGen.SetSignatureCreationTime(false, creationTime); sGen.SetHashedSubpackets(hashedGen.Generate()); sGen.SetUnhashedSubpackets(null); sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey); sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } hashedPcks = sig.GetHashedSubPackets(); if (hashedPcks.Count != 1) { Fail("found wrong number of hashed packets in override test"); } if (!hashedPcks.HasSubpacket(SignatureSubpacketTag.CreationTime)) { Fail("hasSubpacket test for creation time failed"); } DateTime sigCreationTime = hashedPcks.GetSignatureCreationTime(); if (!sigCreationTime.Equals(creationTime)) { Fail("creation of overridden date failed."); } prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms(); preferredAlgorithmCheck("compression", NO_PREFERENCES, prefAlgs); prefAlgs = hashedPcks.GetPreferredHashAlgorithms(); preferredAlgorithmCheck("hash", NO_PREFERENCES, prefAlgs); prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms(); preferredAlgorithmCheck("symmetric", NO_PREFERENCES, prefAlgs); if (hashedPcks.GetKeyExpirationTime() != 0) { Fail("unexpected key expiration time found"); } if (hashedPcks.GetSignatureExpirationTime() != 0) { Fail("unexpected signature expiration time found"); } if (hashedPcks.GetSignerUserId() != null) { Fail("unexpected signer user ID found"); } criticalHashed = hashedPcks.GetCriticalTags(); if (criticalHashed.Length != 0) { Fail("critical packets found when none expected"); } unhashedPcks = sig.GetUnhashedSubPackets(); if (unhashedPcks.Count != 1) { Fail("found wrong number of unhashed packets in override test"); } // // general signatures // doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey); doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey); doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey); doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); // // DSA Tests // pgpPriv = new PgpSecretKeyRing(dsaKeyRing); secretKey = pgpPriv.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(dsaPass); try { doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("DSA wrong key test failed."); } catch (PgpException) { // expected } try { doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("DSA V3 wrong key test failed."); } catch (PgpException) { // expected } doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); // special cases // doTestMissingSubpackets(nullPacketsSubKeyBinding); doTestMissingSubpackets(generateV3BinarySig(pgpPrivKey, PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1)); // keyflags doTestKeyFlagsValues(); } private void doTestKeyFlagsValues() { checkValue(KeyFlags.CertifyOther, 0x01); checkValue(KeyFlags.SignData, 0x02); checkValue(KeyFlags.EncryptComms, 0x04); checkValue(KeyFlags.EncryptStorage, 0x08); checkValue(KeyFlags.Split, 0x10); checkValue(KeyFlags.Authentication, 0x20); checkValue(KeyFlags.Shared, 0x80); // yes this actually happens checkValue(new byte[] { 4, 0, 0, 0 }, 0x04); checkValue(new byte[] { 4, 0, 0 }, 0x04); checkValue(new byte[] { 4, 0 }, 0x04); checkValue(new byte[] { 4 }, 0x04); } private void checkValue(int flag, int val) { KeyFlags f = new KeyFlags(true, flag); if (f.Flags != val) { Fail("flag value mismatch"); } } private void checkValue(byte[] flag, int val) { KeyFlags f = new KeyFlags(true, flag); if (f.Flags != val) { Fail("flag value mismatch"); } } private void doTestMissingSubpackets(byte[] signature) { PgpObjectFactory f = new PgpObjectFactory(signature); object obj = f.NextPgpObject(); while (!(obj is PgpSignatureList)) { obj = f.NextPgpObject(); if (obj is PgpLiteralData) { Stream input = ((PgpLiteralData)obj).GetDataStream(); Streams.Drain(input); } } PgpSignature sig = ((PgpSignatureList)obj)[0]; if (sig.Version > 3) { var v = sig.GetHashedSubPackets(); if (v.GetKeyExpirationTime() != 0) { Fail("key expiration time not zero for missing subpackets"); } if (!sig.HasSubpackets) { Fail("HasSubpackets property was false with packets"); } } else { if (sig.GetHashedSubPackets() != null) { Fail("hashed sub packets found when none expected"); } if (sig.GetUnhashedSubPackets() != null) { Fail("unhashed sub packets found when none expected"); } if (sig.HasSubpackets) { Fail("HasSubpackets property was true with no packets"); } } } private void preferredAlgorithmCheck( string type, int[] expected, int[] prefAlgs) { if (expected == null) { if (prefAlgs != null) { Fail("preferences for " + type + " found when none expected"); } } else { if (prefAlgs.Length != expected.Length) { Fail("wrong number of preferred " + type + " algorithms found"); } for (int i = 0; i != expected.Length; i++) { if (expected[i] != prefAlgs[i]) { Fail("wrong algorithm found for " + type + ": expected " + expected[i] + " got " + prefAlgs); } } } } private void doTestSig( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, IPgpPublicKey pubKey, IPgpPrivateKey privKey) { MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(TEST_DATA, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(encAlgorithm, hashAlgorithm); sGen.InitSign(PgpSignature.BinaryDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Binary, "_CONSOLE", TEST_DATA.Length * 2, DateTime.UtcNow); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(TEST_DATA, 0, TEST_DATA.Length); sGen.Update(TEST_DATA); lGen.Close(); sGen.Generate().Encode(bOut); verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, TEST_DATA); } private void doTestTextSig( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, IPgpPublicKey pubKey, IPgpPrivateKey privKey, byte[] data, byte[] canonicalData) { PgpSignatureGenerator sGen = new PgpSignatureGenerator(encAlgorithm, HashAlgorithmTag.Sha1); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(data, false); DateTime creationTime = DateTime.UtcNow; sGen.InitSign(PgpSignature.CanonicalTextDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Text, "_CONSOLE", data.Length * 2, creationTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(data, 0, data.Length); sGen.Update(data); lGen.Close(); PgpSignature sig = sGen.Generate(); if (sig.CreationTime == DateTimeUtilities.UnixMsToDateTime(0)) { Fail("creation time not set in v4 signature"); } sig.Encode(bOut); verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, canonicalData); } private void doTestSigV3( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, IPgpPublicKey pubKey, IPgpPrivateKey privKey) { byte[] bytes = generateV3BinarySig(privKey, encAlgorithm, hashAlgorithm); verifySignature(bytes, hashAlgorithm, pubKey, TEST_DATA); } private byte[] generateV3BinarySig( IPgpPrivateKey privKey, PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm) { MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(TEST_DATA, false); PgpV3SignatureGenerator sGen = new PgpV3SignatureGenerator(encAlgorithm, hashAlgorithm); sGen.InitSign(PgpSignature.BinaryDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Binary, "_CONSOLE", TEST_DATA.Length * 2, DateTime.UtcNow); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(TEST_DATA, 0, TEST_DATA.Length); sGen.Update(TEST_DATA); lGen.Close(); sGen.Generate().Encode(bOut); return bOut.ToArray(); } private void doTestTextSigV3( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, IPgpPublicKey pubKey, IPgpPrivateKey privKey, byte[] data, byte[] canonicalData) { PgpV3SignatureGenerator sGen = new PgpV3SignatureGenerator(encAlgorithm, HashAlgorithmTag.Sha1); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(data, false); sGen.InitSign(PgpSignature.CanonicalTextDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Text, "_CONSOLE", data.Length * 2, DateTime.UtcNow); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(data, 0, data.Length); sGen.Update(data); lGen.Close(); PgpSignature sig = sGen.Generate(); if (sig.CreationTime == DateTimeUtilities.UnixMsToDateTime(0)) { Fail("creation time not set in v3 signature"); } sig.Encode(bOut); verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, canonicalData); } private void verifySignature( byte[] encodedSig, HashAlgorithmTag hashAlgorithm, IPgpPublicKey pubKey, byte[] original) { PgpObjectFactory pgpFact = new PgpObjectFactory(encodedSig); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; DateTime creationTime = sig.CreationTime; // Check creationTime is recent if (creationTime.CompareTo(DateTime.UtcNow) > 0 || creationTime.CompareTo(DateTime.UtcNow.AddMinutes(-10)) < 0) { Fail("bad creation time in signature: " + creationTime); } if (sig.KeyId != pubKey.KeyId) { Fail("key id mismatch in signature"); } if (!ops.Verify(sig)) { Fail("Failed generated signature check - " + hashAlgorithm); } sig.InitVerify(pubKey); for (int i = 0; i != original.Length; i++) { sig.Update(original[i]); } sig.Update(original); if (!sig.Verify()) { Fail("Failed generated signature check against original data"); } } public override string Name { get { return "PGPSignatureTest"; } } public static void Main( string[] args) { RunTest(new PgpSignatureTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; #if !NETSTANDARD_TODO using System.Reflection.PortableExecutable; #endif using System.Text; using Microsoft.Extensions.DependencyInjection; namespace Orleans.Runtime { internal class AssemblyLoader { #if !NETSTANDARD_TODO private readonly Dictionary<string, SearchOption> dirEnumArgs; private readonly HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria; private readonly HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria; private readonly Logger logger; internal bool SimulateExcludeCriteriaFailure { get; set; } internal bool SimulateLoadCriteriaFailure { get; set; } internal bool SimulateReflectionOnlyLoadFailure { get; set; } internal bool RethrowDiscoveryExceptions { get; set; } private AssemblyLoader( Dictionary<string, SearchOption> dirEnumArgs, HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria, HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria, Logger logger) { this.dirEnumArgs = dirEnumArgs; this.pathNameCriteria = pathNameCriteria; this.reflectionCriteria = reflectionCriteria; this.logger = logger; SimulateExcludeCriteriaFailure = false; SimulateLoadCriteriaFailure = false; SimulateReflectionOnlyLoadFailure = false; RethrowDiscoveryExceptions = false; } /// <summary> /// Loads assemblies according to caller-defined criteria. /// </summary> /// <param name="dirEnumArgs">A list of arguments that are passed to Directory.EnumerateFiles(). /// The sum of the DLLs found from these searches is used as a base set of assemblies for /// criteria to evaluate.</param> /// <param name="pathNameCriteria">A list of criteria that are used to disqualify /// assemblies from being loaded based on path name alone (e.g. /// AssemblyLoaderCriteria.ExcludeFileNames) </param> /// <param name="reflectionCriteria">A list of criteria that are used to identify /// assemblies to be loaded based on examination of their ReflectionOnly type /// information (e.g. AssemblyLoaderCriteria.LoadTypesAssignableFrom).</param> /// <param name="logger">A logger to provide feedback to.</param> /// <returns>List of discovered assembly locations</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] public static List<string> LoadAssemblies( Dictionary<string, SearchOption> dirEnumArgs, IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria, IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria, Logger logger) { var loader = NewAssemblyLoader( dirEnumArgs, pathNameCriteria, reflectionCriteria, logger); int count = 0; List<string> discoveredAssemblyLocations = loader.DiscoverAssemblies(); foreach (var pathName in discoveredAssemblyLocations) { loader.logger.Info("Loading assembly {0}...", pathName); // It is okay to use LoadFrom here because we are loading application assemblies deployed to the specific directory. // Such application assemblies should not be deployed somewhere else, e.g. GAC, so this is safe. Assembly.LoadFrom(pathName); ++count; } loader.logger.Info("{0} assemblies loaded.", count); return discoveredAssemblyLocations; } #endif public static T TryLoadAndCreateInstance<T>(string assemblyName, Logger logger, IServiceProvider serviceProvider) where T : class { try { var assembly = Assembly.Load(new AssemblyName(assemblyName)); var foundType = TypeUtils.GetTypes( assembly, type => typeof(T).IsAssignableFrom(type) && !type.GetTypeInfo().IsInterface, logger).FirstOrDefault(); if (foundType == null) { return null; } return (T)ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, foundType); } catch (FileNotFoundException) { logger.Info(ErrorCode.Loader_TryLoadAndCreateInstance_Failure, $"Failed to find assembly {assemblyName} to create instance of {typeof(T)}."); return null; } catch (Exception exc) { logger.Error(ErrorCode.Loader_TryLoadAndCreateInstance_Failure, exc.Message, exc); throw; } } public static T LoadAndCreateInstance<T>(string assemblyName, Logger logger, IServiceProvider serviceProvider) where T : class { try { var assembly = Assembly.Load(new AssemblyName(assemblyName)); var foundType = TypeUtils.GetTypes(assembly, type => typeof(T).IsAssignableFrom(type), logger).First(); return (T)ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, foundType); } catch (Exception exc) { logger.Error(ErrorCode.Loader_LoadAndCreateInstance_Failure, exc.Message, exc); throw; } } #if !NETSTANDARD_TODO // this method is internal so that it can be accessed from unit tests, which only test the discovery // process-- not the actual loading of assemblies. internal static AssemblyLoader NewAssemblyLoader( Dictionary<string, SearchOption> dirEnumArgs, IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria, IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria, Logger logger) { if (null == dirEnumArgs) throw new ArgumentNullException("dirEnumArgs"); if (dirEnumArgs.Count == 0) throw new ArgumentException("At least one directory is necessary in order to search for assemblies."); HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteriaSet = null == pathNameCriteria ? new HashSet<AssemblyLoaderPathNameCriterion>() : new HashSet<AssemblyLoaderPathNameCriterion>(pathNameCriteria.Distinct()); if (null == reflectionCriteria || !reflectionCriteria.Any()) throw new ArgumentException("No assemblies will be loaded unless reflection criteria are specified."); var reflectionCriteriaSet = new HashSet<AssemblyLoaderReflectionCriterion>(reflectionCriteria.Distinct()); if (null == logger) throw new ArgumentNullException("logger"); return new AssemblyLoader( dirEnumArgs, pathNameCriteriaSet, reflectionCriteriaSet, logger); } // this method is internal so that it can be accessed from unit tests, which only test the discovery // process-- not the actual loading of assemblies. internal List<string> DiscoverAssemblies() { try { if (dirEnumArgs.Count == 0) throw new InvalidOperationException("Please specify a directory to search using the AddDirectory or AddRoot methods."); AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve; // the following explicit loop ensures that the finally clause is invoked // after we're done enumerating. return EnumerateApprovedAssemblies(); } finally { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve; } } private List<string> EnumerateApprovedAssemblies() { var assemblies = new List<string>(); foreach (var i in dirEnumArgs) { var pathName = i.Key; var searchOption = i.Value; if (!Directory.Exists(pathName)) { logger.Warn(ErrorCode.Loader_DirNotFound, "Unable to find directory {0}; skipping.", pathName); continue; } logger.Info( searchOption == SearchOption.TopDirectoryOnly ? "Searching for assemblies in {0}..." : "Recursively searching for assemblies in {0}...", pathName); var candidates = Directory.EnumerateFiles(pathName, "*.dll", searchOption) .Select(Path.GetFullPath) .Where(p => p.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) .Distinct() .ToArray(); // This is a workaround for the behavior of ReflectionOnlyLoad/ReflectionOnlyLoadFrom // that appear not to automatically resolve dependencies. // We are trying to pre-load all dlls we find in the folder, so that if one of these // assemblies happens to be a dependency of an assembly we later on call // Assembly.DefinedTypes on, the dependency will be already loaded and will get // automatically resolved. Ugly, but seems to solve the problem. foreach (var j in candidates) { try { var complaints = default(string[]); if (IsCompatibleWithCurrentProcess(j, out complaints)) { if (logger.IsVerbose) logger.Verbose("Trying to pre-load {0} to reflection-only context.", j); Assembly.ReflectionOnlyLoadFrom(j); } else { if (logger.IsInfo) logger.Info("{0} is not compatible with current process, loading is skipped.", j); } } catch (Exception) { if (logger.IsVerbose) logger.Verbose("Failed to pre-load assembly {0} in reflection-only context.", j); } } foreach (var j in candidates) { if (AssemblyPassesLoadCriteria(j)) assemblies.Add(j); } } return assemblies; } private bool ShouldExcludeAssembly(string pathName) { foreach (var criterion in pathNameCriteria) { IEnumerable<string> complaints; bool shouldExclude; try { shouldExclude = !criterion.EvaluateCandidate(pathName, out complaints); } catch (Exception ex) { complaints = ReportUnexpectedException(ex); if (RethrowDiscoveryExceptions) throw; shouldExclude = true; } if (shouldExclude) { LogComplaints(pathName, complaints); return true; } } return false; } private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, IEnumerable<Assembly> assemblies) { foreach (var assembly in assemblies) { var searchForFullName = searchFor.FullName; var candidateFullName = assembly.FullName; if (String.Equals(candidateFullName, searchForFullName, StringComparison.OrdinalIgnoreCase)) { return assembly; } } return null; } private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, AppDomain appDomain) { return MatchWithLoadedAssembly(searchFor, appDomain.GetAssemblies()) ?? MatchWithLoadedAssembly(searchFor, appDomain.ReflectionOnlyGetAssemblies()); } private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor) { return MatchWithLoadedAssembly(searchFor, AppDomain.CurrentDomain); } private static bool InterpretFileLoadException(string asmPathName, out string[] complaints) { var matched = default(Assembly); try { matched = MatchWithLoadedAssembly(AssemblyName.GetAssemblyName(asmPathName)); } catch (BadImageFormatException) { // this can happen when System.Reflection.Metadata or System.Collections.Immutable assembly version is different (one requires the other) and there is no correct binding redirect in the app.config complaints = null; return false; } if (null == matched) { // something unexpected has occurred. rethrow until we know what we're catching. complaints = null; return false; } if (matched.Location != asmPathName) { complaints = new string[] {String.Format("A conflicting assembly has already been loaded from {0}.", matched.Location)}; // exception was anticipated. return true; } // we've been asked to not log this because it's not indicative of a problem. complaints = null; //complaints = new string[] {"Assembly has already been loaded into current application domain."}; // exception was anticipated. return true; } private string[] ReportUnexpectedException(Exception exception) { const string msg = "An unexpected exception occurred while attempting to load an assembly."; logger.Error(ErrorCode.Loader_UnexpectedException, msg, exception); return new string[] {msg}; } private bool ReflectionOnlyLoadAssembly(string pathName, out Assembly assembly, out string[] complaints) { try { if (SimulateReflectionOnlyLoadFailure) throw NewTestUnexpectedException(); if (IsCompatibleWithCurrentProcess(pathName, out complaints)) { assembly = Assembly.ReflectionOnlyLoadFrom(pathName); } else { assembly = null; return false; } } catch (FileLoadException ex) { assembly = null; if (!InterpretFileLoadException(pathName, out complaints)) complaints = ReportUnexpectedException(ex); if (RethrowDiscoveryExceptions) throw; return false; } catch (Exception ex) { assembly = null; complaints = ReportUnexpectedException(ex); if (RethrowDiscoveryExceptions) throw; return false; } complaints = null; return true; } private static bool IsCompatibleWithCurrentProcess(string fileName, out string[] complaints) { complaints = null; Stream peImage = null; try { peImage = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); using (var peReader = new PEReader(peImage, PEStreamOptions.PrefetchMetadata)) { peImage = null; if (peReader.HasMetadata) { var processorArchitecture = ProcessorArchitecture.MSIL; var isPureIL = (peReader.PEHeaders.CorHeader.Flags & CorFlags.ILOnly) != 0; if (peReader.PEHeaders.PEHeader.Magic == PEMagic.PE32Plus) processorArchitecture = ProcessorArchitecture.Amd64; else if ((peReader.PEHeaders.CorHeader.Flags & CorFlags.Requires32Bit) != 0 || !isPureIL) processorArchitecture = ProcessorArchitecture.X86; var isLoadable = (isPureIL && processorArchitecture == ProcessorArchitecture.MSIL) || (Environment.Is64BitProcess && processorArchitecture == ProcessorArchitecture.Amd64) || (!Environment.Is64BitProcess && processorArchitecture == ProcessorArchitecture.X86); if (!isLoadable) { complaints = new[] { $"The file {fileName} is not loadable into this process, either it is not an MSIL assembly or the compliled for a different processor architecture." }; } return isLoadable; } else { complaints = new[] { $"The file {fileName} does not contain any CLR metadata, probably it is a native file." }; return false; } } } catch (IOException) { return false; } catch (BadImageFormatException) { return false; } catch (UnauthorizedAccessException) { return false; } catch (MissingMethodException) { complaints = new[] { "MissingMethodException occured. Please try to add a BindingRedirect for System.Collections.ImmutableCollections to the App.config file to correct this error." }; return false; } catch (Exception ex) { complaints = new[] { LogFormatter.PrintException(ex) }; return false; } finally { peImage?.Dispose(); } } private void LogComplaint(string pathName, string complaint) { LogComplaints(pathName, new string[] { complaint }); } private void LogComplaints(string pathName, IEnumerable<string> complaints) { var distinctComplaints = complaints.Distinct(); // generate feedback so that the operator can determine why her DLL didn't load. var msg = new StringBuilder(); string bullet = Environment.NewLine + "\t* "; msg.Append(String.Format("User assembly ignored: {0}", pathName)); int count = 0; foreach (var i in distinctComplaints) { msg.Append(bullet); msg.Append(i); ++count; } if (0 == count) throw new InvalidOperationException("No complaint provided for assembly."); // we can't use an error code here because we want each log message to be displayed. logger.Info(msg.ToString()); } private static AggregateException NewTestUnexpectedException() { var inner = new Exception[] { new OrleansException("Inner Exception #1"), new OrleansException("Inner Exception #2") }; return new AggregateException("Unexpected AssemblyLoader Exception Used for Unit Tests", inner); } private bool ShouldLoadAssembly(string pathName) { Assembly assembly; string[] loadComplaints; if (!ReflectionOnlyLoadAssembly(pathName, out assembly, out loadComplaints)) { if (loadComplaints == null || loadComplaints.Length == 0) return false; LogComplaints(pathName, loadComplaints); return false; } if (assembly.IsDynamic) { LogComplaint(pathName, "Assembly is dynamic (not supported)."); return false; } var criteriaComplaints = new List<string>(); foreach (var i in reflectionCriteria) { IEnumerable<string> complaints; try { if (SimulateLoadCriteriaFailure) throw NewTestUnexpectedException(); if (i.EvaluateCandidate(assembly, out complaints)) return true; } catch (Exception ex) { complaints = ReportUnexpectedException(ex); if (RethrowDiscoveryExceptions) throw; } criteriaComplaints.AddRange(complaints); } LogComplaints(pathName, criteriaComplaints); return false; } private bool AssemblyPassesLoadCriteria(string pathName) { return !ShouldExcludeAssembly(pathName) && ShouldLoadAssembly(pathName); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Threading; namespace System.Globalization { // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) public class GregorianCalendar : Calendar { /* A.D. = anno Domini */ public const int ADEra = 1; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal const int MaxYear = 9999; internal GregorianCalendarTypes m_type; internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; private static volatile Calendar s_defaultInstance; [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if (m_type < GregorianCalendarTypes.Localized || m_type > GregorianCalendarTypes.TransliteratedFrench) { throw new SerializationException( String.Format(CultureInfo.CurrentCulture, SR.Serialization_MemberOutOfRange, "type", "GregorianCalendar")); } } public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new GregorianCalendar(); } return (s_defaultInstance); } // Construct an instance of gregorian calendar. public GregorianCalendar() : this(GregorianCalendarTypes.Localized) { } public GregorianCalendar(GregorianCalendarTypes type) { if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) { throw new ArgumentOutOfRangeException( nameof(type), SR.Format(SR.ArgumentOutOfRange_Range, GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } Contract.EndContractBlock(); this.m_type = type; } public virtual GregorianCalendarTypes CalendarType { get { return (m_type); } set { VerifyWritable(); switch (value) { case GregorianCalendarTypes.Localized: case GregorianCalendarTypes.USEnglish: case GregorianCalendarTypes.MiddleEastFrench: case GregorianCalendarTypes.Arabic: case GregorianCalendarTypes.TransliteratedEnglish: case GregorianCalendarTypes.TransliteratedFrench: m_type = value; break; default: throw new ArgumentOutOfRangeException("m_type", SR.ArgumentOutOfRange_Enum); } } } internal override CalendarId ID { get { // By returning different ID for different variations of GregorianCalendar, // we can support the Transliterated Gregorian calendar. // DateTimeFormatInfo will use this ID to get formatting information about // the calendar. return ((CalendarId)m_type); } } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal virtual long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day) * TicksPerDay); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } Contract.EndContractBlock(); time.GetDatePart(out int y, out int m, out int d); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return time.Day; } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { return time.DayOfYear; } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { if (era == CurrentEra || era == ADEra) { if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException(nameof(year), SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return (days[month] - days[month - 1]); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365); } throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { return (ADEra); } public override int[] Eras { get { return (new int[] { ADEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return time.Month; } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (12); } throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear(DateTime time) { return time.Year; } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } Contract.EndContractBlock(); if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (day < 1 || day > GetDaysInMonth(year, month)) { throw new ArgumentOutOfRangeException(nameof(day), SR.Format(SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month))); } if (!IsLeapYear(year)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } Contract.EndContractBlock(); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } Contract.EndContractBlock(); return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { if (era == CurrentEra || era == ADEra) { return new DateTime(year, month, day, hour, minute, second, millisecond); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { if (era == CurrentEra || era == ADEra) { try { result = new DateTime(year, month, day, hour, minute, second, millisecond); return true; } catch (ArgumentOutOfRangeException) { result = DateTime.Now; return false; } catch (ArgumentException) { result = DateTime.Now; return false; } } result = DateTime.MinValue; return false; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } return (base.ToFourDigitYear(year)); } } }
// 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. /* Note on transaction support: Eventually we will want to add support for NT's transactions to our RegistryKey API's (possibly Whidbey M3?). When we do this, here's the list of API's we need to make transaction-aware: RegCreateKeyEx RegDeleteKey RegDeleteValue RegEnumKeyEx RegEnumValue RegOpenKeyEx RegQueryInfoKey RegQueryValueEx RegSetValueEx We can ignore RegConnectRegistry (remote registry access doesn't yet have transaction support) and RegFlushKey. RegCloseKey doesn't require any additional work. . */ /* Note on ACL support: The key thing to note about ACL's is you set them on a kernel object like a registry key, then the ACL only gets checked when you construct handles to them. So if you set an ACL to deny read access to yourself, you'll still be able to read with that handle, but not with new handles. Another peculiarity is a Terminal Server app compatibility workaround. The OS will second guess your attempt to open a handle sometimes. If a certain combination of Terminal Server app compat registry keys are set, then the OS will try to reopen your handle with lesser permissions if you couldn't open it in the specified mode. So on some machines, we will see handles that may not be able to read or write to a registry key. It's very strange. But the real test of these handles is attempting to read or set a value in an affected registry key. For reference, at least two registry keys must be set to particular values for this behavior: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1. HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1 There might possibly be an interaction with yet a third registry key as well. */ using Microsoft.Win32.SafeHandles; using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; namespace Microsoft.Win32 { /** * Registry encapsulation. To get an instance of a RegistryKey use the * Registry class's static members then call OpenSubKey. * * @see Registry * @security(checkDllCalls=off) * @security(checkClassLinking=on) */ internal sealed class RegistryKey : MarshalByRefObject, IDisposable { // We could use const here, if C# supported ELEMENT_TYPE_I fully. internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); internal static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004)); internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); // Dirty indicates that we have munged data that should be potentially // written to disk. // private const int STATE_DIRTY = 0x0001; // SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened" // or "closed". // private const int STATE_SYSTEMKEY = 0x0002; // Access // private const int STATE_WRITEACCESS = 0x0004; // Indicates if this key is for HKEY_PERFORMANCE_DATA private const int STATE_PERF_DATA = 0x0008; // Names of keys. This array must be in the same order as the HKEY values listed above. // private static readonly String[] hkeyNames = new String[] { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_PERFORMANCE_DATA", "HKEY_CURRENT_CONFIG", }; // MSDN defines the following limits for registry key names & values: // Key Name: 255 characters // Value name: 16,383 Unicode characters // Value: either 1 MB or current available memory, depending on registry format. private const int MaxKeyLength = 255; private const int MaxValueLength = 16383; private volatile SafeRegistryHandle hkey = null; private volatile int state = 0; private volatile String keyName; private volatile bool remoteKey = false; private volatile RegistryKeyPermissionCheck checkMode; private volatile RegistryView regView = RegistryView.Default; /** * Creates a RegistryKey. * * This key is bound to hkey, if writable is <b>false</b> then no write operations * will be allowed. If systemkey is set then the hkey won't be released * when the object is GC'ed. * The remoteKey flag when set to true indicates that we are dealing with registry entries * on a remote machine and requires the program making these calls to have full trust. */ private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) { this.hkey = hkey; keyName = ""; this.remoteKey = remoteKey; regView = view; if (systemkey) { state |= STATE_SYSTEMKEY; } if (writable) { state |= STATE_WRITEACCESS; } if (isPerfData) state |= STATE_PERF_DATA; ValidateKeyView(view); } /** * Closes this key, flushes it to disk if the contents have been modified. */ public void Close() { Dispose(true); } private void Dispose(bool disposing) { if (hkey != null) { if (!IsSystemKey()) { try { hkey.Dispose(); } catch (IOException) { // we don't really care if the handle is invalid at this point } finally { hkey = null; } } else if (disposing && IsPerfDataKey()) { // System keys should never be closed. However, we want to call RegCloseKey // on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources // (i.e. when disposing is true) so that we release the PERFLIB cache and cause it // to be refreshed (by re-reading the registry) when accessed subsequently. // This is the only way we can see the just installed perf counter. // NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race condition in closing // the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources // in this situation the down level OSes are not. We have a small window between // the dispose below and usage elsewhere (other threads). This is By Design. // This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey // (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary. SafeRegistryHandle.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA); } } } void IDisposable.Dispose() { Dispose(true); } public void DeleteValue(String name, bool throwOnMissingValue) { EnsureWriteable(); int errorCode = Win32Native.RegDeleteValue(hkey, name); // // From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE // This still means the name doesn't exist. We need to be consistent with previous OS. // if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_FILENAME_EXCED_RANGE) { if (throwOnMissingValue) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyValueAbsent); } // Otherwise, just return giving no indication to the user. // (For compatibility) } // We really should throw an exception here if errorCode was bad, // but we can't for compatibility reasons. Debug.Assert(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode); } /** * Retrieves a new RegistryKey that represents the requested key. Valid * values are: * * HKEY_CLASSES_ROOT, * HKEY_CURRENT_USER, * HKEY_LOCAL_MACHINE, * HKEY_USERS, * HKEY_PERFORMANCE_DATA, * HKEY_CURRENT_CONFIG, * HKEY_DYN_DATA. * * @param hKey HKEY_* to open. * * @return the RegistryKey requested. */ internal static RegistryKey GetBaseKey(IntPtr hKey) { return GetBaseKey(hKey, RegistryView.Default); } internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view) { int index = ((int)hKey) & 0x0FFFFFFF; Debug.Assert(index >= 0 && index < hkeyNames.Length, "index is out of range!"); Debug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!"); bool isPerf = hKey == HKEY_PERFORMANCE_DATA; // only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA. SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf); RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view); key.checkMode = RegistryKeyPermissionCheck.Default; key.keyName = hkeyNames[index]; return key; } /** * Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with * read-only access. * * @param name Name or path of subkey to open. * @param readonly Set to <b>true</b> if you only need readonly access. * * @return the Subkey requested, or <b>null</b> if the operation failed. */ public RegistryKey OpenSubKey(string name, bool writable) { ValidateKeyName(name); EnsureNotDisposed(); name = FixupName(name); // Fixup multiple slashes to a single slash SafeRegistryHandle result = null; int ret = Win32Native.RegOpenKeyEx(hkey, name, 0, GetRegistryKeyAccess(writable) | (int)regView, out result); if (ret == 0 && !result.IsInvalid) { RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView); key.checkMode = GetSubKeyPermissonCheck(writable); key.keyName = keyName + "\\" + name; return key; } // Return null if we didn't find the key. if (ret == Interop.Errors.ERROR_ACCESS_DENIED || ret == Interop.Errors.ERROR_BAD_IMPERSONATION_LEVEL) { // We need to throw SecurityException here for compatibility reasons, // although UnauthorizedAccessException will make more sense. ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission); } return null; } /** * Returns a subkey with read only permissions. * * @param name Name or path of subkey to open. * * @return the Subkey requested, or <b>null</b> if the operation failed. */ public RegistryKey OpenSubKey(String name) { return OpenSubKey(name, false); } /// <summary> /// Retrieves an array of strings containing all the subkey names. /// </summary> public string[] GetSubKeyNames() { EnsureNotDisposed(); var names = new List<string>(); char[] name = ArrayPool<char>.Shared.Rent(MaxKeyLength + 1); try { int result; int nameLength = name.Length; while ((result = Win32Native.RegEnumKeyEx( hkey, names.Count, name, ref nameLength, null, null, null, null)) != Interop.Errors.ERROR_NO_MORE_ITEMS) { switch (result) { case Interop.Errors.ERROR_SUCCESS: names.Add(new string(name, 0, nameLength)); nameLength = name.Length; break; default: // Throw the error Win32Error(result, null); break; } } } finally { ArrayPool<char>.Shared.Return(name); } return names.ToArray(); } /// <summary> /// Retrieves an array of strings containing all the value names. /// </summary> public unsafe string[] GetValueNames() { EnsureNotDisposed(); var names = new List<string>(); // Names in the registry aren't usually very long, although they can go to as large // as 16383 characters (MaxValueLength). // // Every call to RegEnumValue will allocate another buffer to get the data from // NtEnumerateValueKey before copying it back out to our passed in buffer. This can // add up quickly- we'll try to keep the memory pressure low and grow the buffer // only if needed. char[] name = ArrayPool<char>.Shared.Rent(100); try { int result; int nameLength = name.Length; while ((result = Win32Native.RegEnumValue( hkey, names.Count, name, ref nameLength, IntPtr.Zero, null, null, null)) != Interop.Errors.ERROR_NO_MORE_ITEMS) { switch (result) { // The size is only ever reported back correctly in the case // of ERROR_SUCCESS. It will almost always be changed, however. case Interop.Errors.ERROR_SUCCESS: names.Add(new string(name, 0, nameLength)); break; case Interop.Errors.ERROR_MORE_DATA: if (IsPerfDataKey()) { // Enumerating the values for Perf keys always returns // ERROR_MORE_DATA, but has a valid name. Buffer does need // to be big enough however. 8 characters is the largest // known name. The size isn't returned, but the string is // null terminated. fixed (char* c = &name[0]) { names.Add(new string(c)); } } else { char[] oldName = name; int oldLength = oldName.Length; name = null; ArrayPool<char>.Shared.Return(oldName); name = ArrayPool<char>.Shared.Rent(checked(oldLength * 2)); } break; default: // Throw the error Win32Error(result, null); break; } // Always set the name length back to the buffer size nameLength = name.Length; } } finally { if (name != null) ArrayPool<char>.Shared.Return(name); } return names.ToArray(); } /** * Retrieves the specified value. <b>null</b> is returned if the value * doesn't exist. * * Note that <var>name</var> can be null or "", at which point the * unnamed or default value of this Registry key is returned, if any. * * @param name Name of value to retrieve. * * @return the data associated with the value. */ public Object GetValue(String name) { return InternalGetValue(name, null, false, true); } /** * Retrieves the specified value. <i>defaultValue</i> is returned if the value doesn't exist. * * Note that <var>name</var> can be null or "", at which point the * unnamed or default value of this Registry key is returned, if any. * The default values for RegistryKeys are OS-dependent. NT doesn't * have them by default, but they can exist and be of any type. * * @param name Name of value to retrieve. * @param defaultValue Value to return if <i>name</i> doesn't exist. * * @return the data associated with the value. */ public Object GetValue(String name, Object defaultValue) { return InternalGetValue(name, defaultValue, false, true); } public Object GetValue(String name, Object defaultValue, RegistryValueOptions options) { if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options)); } bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames); return InternalGetValue(name, defaultValue, doNotExpand, true); } internal Object InternalGetValue(String name, Object defaultValue, bool doNotExpand, bool checkSecurity) { if (checkSecurity) { // Name can be null! It's the most common use of RegQueryValueEx EnsureNotDisposed(); } Object data = defaultValue; int type = 0; int datasize = 0; int ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize); if (ret != 0) { if (IsPerfDataKey()) { int size = 65000; int sizeInput = size; int r; byte[] blob = new byte[size]; while (Interop.Errors.ERROR_MORE_DATA == (r = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref sizeInput))) { if (size == Int32.MaxValue) { // ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue Win32Error(r, name); } else if (size > (Int32.MaxValue / 2)) { // at this point in the loop "size * 2" would cause an overflow size = Int32.MaxValue; } else { size *= 2; } sizeInput = size; blob = new byte[size]; } if (r != 0) Win32Error(r, name); return blob; } else { // For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data). // Some OS's returned ERROR_MORE_DATA even in success cases, so we // want to continue on through the function. if (ret != Interop.Errors.ERROR_MORE_DATA) return data; } } if (datasize < 0) { // unexpected code path Debug.Fail("[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize"); datasize = 0; } switch (type) { case Win32Native.REG_NONE: case Win32Native.REG_DWORD_BIG_ENDIAN: case Win32Native.REG_BINARY: { byte[] blob = new byte[datasize]; ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize); data = blob; } break; case Win32Native.REG_QWORD: { // also REG_QWORD_LITTLE_ENDIAN if (datasize > 8) { // prevent an AV in the edge case that datasize is larger than sizeof(long) goto case Win32Native.REG_BINARY; } long blob = 0; Debug.Assert(datasize == 8, "datasize==8"); // Here, datasize must be 8 when calling this ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize); data = blob; } break; case Win32Native.REG_DWORD: { // also REG_DWORD_LITTLE_ENDIAN if (datasize > 4) { // prevent an AV in the edge case that datasize is larger than sizeof(int) goto case Win32Native.REG_QWORD; } int blob = 0; Debug.Assert(datasize == 4, "datasize==4"); // Here, datasize must be four when calling this ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize); data = blob; } break; case Win32Native.REG_SZ: { if (datasize % 2 == 1) { // handle the case where the registry contains an odd-byte length (corrupt data?) try { datasize = checked(datasize + 1); } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } } char[] blob = new char[datasize / 2]; ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { data = new String(blob, 0, blob.Length - 1); } else { // in the very unlikely case the data is missing null termination, // pass in the whole char[] to prevent truncating a character data = new String(blob); } } break; case Win32Native.REG_EXPAND_SZ: { if (datasize % 2 == 1) { // handle the case where the registry contains an odd-byte length (corrupt data?) try { datasize = checked(datasize + 1); } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } } char[] blob = new char[datasize / 2]; ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { data = new String(blob, 0, blob.Length - 1); } else { // in the very unlikely case the data is missing null termination, // pass in the whole char[] to prevent truncating a character data = new String(blob); } if (!doNotExpand) data = Environment.ExpandEnvironmentVariables((String)data); } break; case Win32Native.REG_MULTI_SZ: { if (datasize % 2 == 1) { // handle the case where the registry contains an odd-byte length (corrupt data?) try { datasize = checked(datasize + 1); } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } } char[] blob = new char[datasize / 2]; ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize); // make sure the string is null terminated before processing the data if (blob.Length > 0 && blob[blob.Length - 1] != (char)0) { try { char[] newBlob = new char[checked(blob.Length + 1)]; for (int i = 0; i < blob.Length; i++) { newBlob[i] = blob[i]; } newBlob[newBlob.Length - 1] = (char)0; blob = newBlob; } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } blob[blob.Length - 1] = (char)0; } IList<String> strings = new List<String>(); int cur = 0; int len = blob.Length; while (ret == 0 && cur < len) { int nextNull = cur; while (nextNull < len && blob[nextNull] != (char)0) { nextNull++; } if (nextNull < len) { Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0"); if (nextNull - cur > 0) { strings.Add(new String(blob, cur, nextNull - cur)); } else { // we found an empty string. But if we're at the end of the data, // it's just the extra null terminator. if (nextNull != len - 1) strings.Add(String.Empty); } } else { strings.Add(new String(blob, cur, len - cur)); } cur = nextNull + 1; } data = new String[strings.Count]; strings.CopyTo((String[])data, 0); } break; case Win32Native.REG_LINK: default: break; } return data; } private bool IsSystemKey() { return (state & STATE_SYSTEMKEY) != 0; } private bool IsWritable() { return (state & STATE_WRITEACCESS) != 0; } private bool IsPerfDataKey() { return (state & STATE_PERF_DATA) != 0; } private void SetDirty() { state |= STATE_DIRTY; } /** * Sets the specified value. * * @param name Name of value to store data in. * @param value Data to store. */ public void SetValue(String name, Object value) { SetValue(name, value, RegistryValueKind.Unknown); } public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if (name != null && name.Length > MaxValueLength) { throw new ArgumentException(SR.Arg_RegValStrLenBug); } if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind)) throw new ArgumentException(SR.Arg_RegBadKeyKind, nameof(valueKind)); EnsureWriteable(); if (valueKind == RegistryValueKind.Unknown) { // this is to maintain compatibility with the old way of autodetecting the type. // SetValue(string, object) will come through this codepath. valueKind = CalculateValueKind(value); } int ret = 0; try { switch (valueKind) { case RegistryValueKind.ExpandString: case RegistryValueKind.String: { String data = value.ToString(); ret = Win32Native.RegSetValueEx(hkey, name, 0, valueKind, data, checked(data.Length * 2 + 2)); break; } case RegistryValueKind.MultiString: { // Other thread might modify the input array after we calculate the buffer length. // Make a copy of the input array to be safe. string[] dataStrings = (string[])(((string[])value).Clone()); int sizeInBytes = 0; // First determine the size of the array // for (int i = 0; i < dataStrings.Length; i++) { if (dataStrings[i] == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetStrArrNull); } sizeInBytes = checked(sizeInBytes + (dataStrings[i].Length + 1) * 2); } sizeInBytes = checked(sizeInBytes + 2); byte[] basePtr = new byte[sizeInBytes]; fixed (byte* b = basePtr) { IntPtr currentPtr = new IntPtr((void*)b); // Write out the strings... // for (int i = 0; i < dataStrings.Length; i++) { // Assumes that the Strings are always null terminated. String.InternalCopy(dataStrings[i], currentPtr, (checked(dataStrings[i].Length * 2))); currentPtr = new IntPtr((long)currentPtr + (checked(dataStrings[i].Length * 2))); *(char*)(currentPtr.ToPointer()) = '\0'; currentPtr = new IntPtr((long)currentPtr + 2); } *(char*)(currentPtr.ToPointer()) = '\0'; currentPtr = new IntPtr((long)currentPtr + 2); ret = Win32Native.RegSetValueEx(hkey, name, 0, RegistryValueKind.MultiString, basePtr, sizeInBytes); } break; } case RegistryValueKind.None: case RegistryValueKind.Binary: byte[] dataBytes = (byte[])value; ret = Win32Native.RegSetValueEx(hkey, name, 0, (valueKind == RegistryValueKind.None ? Win32Native.REG_NONE : RegistryValueKind.Binary), dataBytes, dataBytes.Length); break; case RegistryValueKind.DWord: { // We need to use Convert here because we could have a boxed type cannot be // unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail. int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture); ret = Win32Native.RegSetValueEx(hkey, name, 0, RegistryValueKind.DWord, ref data, 4); break; } case RegistryValueKind.QWord: { long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture); ret = Win32Native.RegSetValueEx(hkey, name, 0, RegistryValueKind.QWord, ref data, 8); break; } } } catch (OverflowException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind); } catch (InvalidOperationException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind); } catch (FormatException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind); } catch (InvalidCastException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind); } if (ret == 0) { SetDirty(); } else Win32Error(ret, null); } private RegistryValueKind CalculateValueKind(Object value) { // This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days. // Even though we could add detection for an int64 in here, we want to maintain compatibility with the // old behavior. if (value is Int32) return RegistryValueKind.DWord; else if (value is Array) { if (value is byte[]) return RegistryValueKind.Binary; else if (value is String[]) return RegistryValueKind.MultiString; else throw new ArgumentException(SR.Format(SR.Arg_RegSetBadArrType, value.GetType().Name)); } else return RegistryValueKind.String; } /** * Retrieves a string representation of this key. * * @return a string representing the key. */ public override String ToString() { EnsureNotDisposed(); return keyName; } /** * After calling GetLastWin32Error(), it clears the last error field, * so you must save the HResult and pass it to this method. This method * will determine the appropriate exception to throw dependent on your * error, and depending on the error, insert a string into the message * gotten from the ResourceManager. */ internal void Win32Error(int errorCode, String str) { switch (errorCode) { case Interop.Errors.ERROR_ACCESS_DENIED: if (str != null) throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)); else throw new UnauthorizedAccessException(); case Interop.Errors.ERROR_INVALID_HANDLE: /** * For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException. * However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the * SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues * in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception * on reentrant calls because of this error code path in RegistryKey * * Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this, * however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on * this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of * having serialized access). */ if (!IsPerfDataKey()) { hkey.SetHandleAsInvalid(); hkey = null; } goto default; case Interop.Errors.ERROR_FILE_NOT_FOUND: throw new IOException(SR.Arg_RegKeyNotFound, errorCode); default: throw new IOException(Interop.Kernel32.GetMessage(errorCode), errorCode); } } internal static String FixupName(String name) { Debug.Assert(name != null, "[FixupName]name!=null"); if (name.IndexOf('\\') == -1) return name; StringBuilder sb = new StringBuilder(name); FixupPath(sb); int temp = sb.Length - 1; if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash sb.Length = temp; return sb.ToString(); } private static void FixupPath(StringBuilder path) { Debug.Assert(path != null); int length = path.Length; bool fixup = false; char markerChar = (char)0xFFFF; int i = 1; while (i < length - 1) { if (path[i] == '\\') { i++; while (i < length) { if (path[i] == '\\') { path[i] = markerChar; i++; fixup = true; } else break; } } i++; } if (fixup) { i = 0; int j = 0; while (i < length) { if (path[i] == markerChar) { i++; continue; } path[j] = path[i]; i++; j++; } path.Length += j - i; } } private void EnsureNotDisposed() { if (hkey == null) { ThrowHelper.ThrowObjectDisposedException(keyName, ExceptionResource.ObjectDisposed_RegKeyClosed); } } private void EnsureWriteable() { EnsureNotDisposed(); if (!IsWritable()) { ThrowHelper.ThrowUnauthorizedAccessException(ExceptionResource.UnauthorizedAccess_RegistryNoWrite); } } private static int GetRegistryKeyAccess(bool isWritable) { int winAccess; if (!isWritable) { winAccess = Win32Native.KEY_READ; } else { winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE; } return winAccess; } private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable) { if (checkMode == RegistryKeyPermissionCheck.Default) { return checkMode; } if (subkeyWritable) { return RegistryKeyPermissionCheck.ReadWriteSubTree; } else { return RegistryKeyPermissionCheck.ReadSubTree; } } static private void ValidateKeyName(string name) { if (name == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name); } int nextSlash = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase); int current = 0; while (nextSlash != -1) { if ((nextSlash - current) > MaxKeyLength) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug); current = nextSlash + 1; nextSlash = name.IndexOf("\\", current, StringComparison.OrdinalIgnoreCase); } if ((name.Length - current) > MaxKeyLength) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug); } static private void ValidateKeyView(RegistryView view) { if (view != RegistryView.Default && view != RegistryView.Registry32 && view != RegistryView.Registry64) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidRegistryViewCheck, ExceptionArgument.view); } } // Win32 constants for error handling private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; } [Flags] internal enum RegistryValueOptions { None = 0, DoNotExpandEnvironmentNames = 1 } // the name for this API is meant to mimic FileMode, which has similar values internal enum RegistryKeyPermissionCheck { Default = 0, ReadSubTree = 1, ReadWriteSubTree = 2 } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.ServiceAuth; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class GridServicesConnector : BaseServiceConnector, IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public GridServicesConnector() { } public GridServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public GridServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig gridConfig = source.Configs["GridService"]; if (gridConfig == null) { m_log.Error("[GRID CONNECTOR]: GridService missing from OpenSim.ini"); throw new Exception("Grid connector init error"); } string serviceURI = gridConfig.GetString("GridServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[GRID CONNECTOR]: No Server URI named in section GridService"); throw new Exception("Grid connector init error"); } m_ServerURI = serviceURI; base.Initialise(source, "GridService"); } #region IGridService public string RegisterRegion(UUID scopeID, GridRegion regionInfo) { Dictionary<string, object> rinfo = regionInfo.ToKeyValuePairs(); Dictionary<string, object> sendData = new Dictionary<string,object>(); foreach (KeyValuePair<string, object> kvp in rinfo) sendData[kvp.Key] = (string)kvp.Value; sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "register"; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/grid"; // m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "success")) { return String.Empty; } else if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "failure")) { m_log.ErrorFormat( "[GRID CONNECTOR]: Registration failed: {0} when contacting {1}", replyData["Message"], uri); return replyData["Message"].ToString(); } else if (!replyData.ContainsKey("Result")) { m_log.ErrorFormat( "[GRID CONNECTOR]: reply data does not contain result field when contacting {0}", uri); } else { m_log.ErrorFormat( "[GRID CONNECTOR]: unexpected result {0} when contacting {1}", replyData["Result"], uri); return "Unexpected result " + replyData["Result"].ToString(); } } else { m_log.ErrorFormat( "[GRID CONNECTOR]: RegisterRegion received null reply when contacting grid server at {0}", uri); } } catch (Exception e) { m_log.ErrorFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); } return string.Format("Error communicating with the grid service at {0}", uri); } public bool DeregisterRegion(UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["REGIONID"] = regionID.ToString(); sendData["METHOD"] = "deregister"; string uri = m_ServerURI + "/grid"; try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData["Result"] != null) && (replyData["Result"].ToString().ToLower() == "success")) return true; } else m_log.DebugFormat("[GRID CONNECTOR]: DeregisterRegion received null reply"); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); } return false; } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["REGIONID"] = regionID.ToString(); sendData["METHOD"] = "get_neighbours"; List<GridRegion> rinfos = new List<GridRegion>(); string reqString = ServerUtils.BuildQueryString(sendData); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; //m_log.DebugFormat("[GRID CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count); foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received null response", scopeID, regionID); return rinfos; } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["REGIONID"] = regionID.ToString(); sendData["METHOD"] = "get_region_by_uuid"; string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return null; } GridRegion rinfo = null; if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData != null) && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]); //else // m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response", // scopeID, regionID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response", scopeID, regionID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID received null reply"); return rinfo; } public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["X"] = x.ToString(); sendData["Y"] = y.ToString(); sendData["METHOD"] = "get_region_by_position"; string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return null; } GridRegion rinfo = null; if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData != null) && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]); //else // m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received no region", // scopeID, x, y); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received null response", scopeID, x, y); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition received null reply"); return rinfo; } public GridRegion GetRegionByName(UUID scopeID, string regionName) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["NAME"] = regionName; sendData["METHOD"] = "get_region_by_name"; string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return null; } GridRegion rinfo = null; if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData != null) && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1} received null response", scopeID, regionName); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByName received null reply"); return rinfo; } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["NAME"] = name; sendData["MAX"] = maxNumber.ToString(); sendData["METHOD"] = "get_regions_by_name"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received null response", scopeID, name, maxNumber); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName received null reply"); return rinfos; } public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["XMIN"] = xmin.ToString(); sendData["XMAX"] = xmax.ToString(); sendData["YMIN"] = ymin.ToString(); sendData["YMAX"] = ymax.ToString(); sendData["METHOD"] = "get_region_range"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange {0}, {1}-{2} {3}-{4} received null response", scopeID, xmin, xmax, ymin, ymax); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange received null reply"); return rinfos; } public List<GridRegion> GetDefaultRegions(UUID scopeID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["METHOD"] = "get_default_regions"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions {0} received null response", scopeID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions received null reply"); return rinfos; } public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["METHOD"] = "get_default_hypergrid_regions"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultHypergridRegions {0} received null response", scopeID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultHypergridRegions received null reply"); return rinfos; } public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["X"] = x.ToString(); sendData["Y"] = y.ToString(); sendData["METHOD"] = "get_fallback_regions"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions {0}, {1}-{2} received null response", scopeID, x, y); } else m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions received null reply"); return rinfos; } public List<GridRegion> GetHyperlinks(UUID scopeID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["METHOD"] = "get_hyperlinks"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks {0} received null response", scopeID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks received null reply"); return rinfos; } public int GetRegionFlags(UUID scopeID, UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["REGIONID"] = regionID.ToString(); sendData["METHOD"] = "get_region_flags"; string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return -1; } int flags = -1; if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { Int32.TryParse((string)replyData["result"], out flags); //else // m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received wrong type {2}", // scopeID, regionID, replyData["result"].GetType()); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received null response", scopeID, regionID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags received null reply"); return flags; } public Dictionary<string, object> GetExtraFeatures() { Dictionary<string, object> sendData = new Dictionary<string, object>(); Dictionary<string, object> extraFeatures = new Dictionary<string, object>(); sendData["METHOD"] = "get_grid_extra_features"; string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: GetExtraFeatures - Exception when contacting grid server at {0}: {1}", uri, e.Message); return extraFeatures; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData != null) && replyData.Count > 0) { foreach (string key in replyData.Keys) { extraFeatures[key] = replyData[key].ToString(); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetExtraServiceURLs received null reply"); return extraFeatures; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using AonWeb.FluentHttp.Helpers; using AonWeb.FluentHttp.Serialization; namespace AonWeb.FluentHttp.Handlers { public class TypedHandlerRegister { private delegate Task TypedHandlerDelegate(TypedHandlerContext context); private readonly ISet<ITypedHandler> _handlerInstances; private readonly IDictionary<HandlerType, IDictionary<HandlerPriority, ICollection<TypedHandlerInfo>>> _handlers; private readonly IDictionary<string, object> _contextConstructorCache; public TypedHandlerRegister() { _handlerInstances = new HashSet<ITypedHandler>(); _handlers = new Dictionary<HandlerType, IDictionary<HandlerPriority, ICollection<TypedHandlerInfo>>>(); _contextConstructorCache = new Dictionary<string, object>(); } public async Task<Modifiable> OnSending(ITypedBuilderContext context, HttpRequestMessage request, object content) { TypedSendingContext handlerContext = null; foreach (var handlerInfo in GetHandlerInfo(HandlerType.Sending)) { if (handlerContext == null) handlerContext = ((Func<ITypedBuilderContext, HttpRequestMessage, object, TypedSendingContext>)handlerInfo.InitialConstructor)(context, request, content); else handlerContext = ((Func<TypedSendingContext, TypedSendingContext>)handlerInfo.ContinuationConstructor)(handlerContext); await handlerInfo.Handler(handlerContext); } return handlerContext?.GetHandlerResult(); } public async Task<Modifiable> OnSent(ITypedBuilderContext context, HttpRequestMessage request, HttpResponseMessage response) { TypedSentContext handlerContext = null; foreach (var handlerInfo in GetHandlerInfo(HandlerType.Sent)) { if (handlerContext == null) handlerContext = ((Func<ITypedBuilderContext, HttpRequestMessage, HttpResponseMessage, TypedSentContext>)handlerInfo.InitialConstructor)(context, request, response); else handlerContext = ((Func<TypedSentContext, TypedSentContext>)handlerInfo.ContinuationConstructor)(handlerContext); await handlerInfo.Handler(handlerContext); } return handlerContext?.GetHandlerResult(); } public async Task<Modifiable> OnResult(ITypedBuilderContext context, HttpRequestMessage request, HttpResponseMessage response, object result) { TypedResultContext handlerContext = null; foreach (var handlerInfo in GetHandlerInfo(HandlerType.Result)) { if (handlerContext == null) handlerContext = ((Func<ITypedBuilderContext, HttpRequestMessage, HttpResponseMessage, object, TypedResultContext>)handlerInfo.InitialConstructor)(context, request, response, result); else handlerContext = ((Func<TypedResultContext, TypedResultContext>)handlerInfo.ContinuationConstructor)(handlerContext); await handlerInfo.Handler(handlerContext); } return handlerContext?.GetHandlerResult(); } public async Task<Modifiable> OnError(ITypedBuilderContext context, HttpRequestMessage request, HttpResponseMessage response, object error) { TypedErrorContext handlerContext = null; foreach (var handlerInfo in GetHandlerInfo(HandlerType.Error)) { if (handlerContext == null) handlerContext = ((Func<ITypedBuilderContext, HttpRequestMessage, HttpResponseMessage, object, TypedErrorContext>)handlerInfo.InitialConstructor)(context, request, response, error); else handlerContext = ((Func<TypedErrorContext, TypedErrorContext>)handlerInfo.ContinuationConstructor)(handlerContext); await handlerInfo.Handler(handlerContext); } return handlerContext?.GetHandlerResult(); } public async Task<Modifiable> OnException(ITypedBuilderContext context, HttpRequestMessage request, HttpResponseMessage response, Exception exception) { TypedExceptionContext handlerContext = null; foreach (var handlerInfo in GetHandlerInfo(HandlerType.Exception)) { if (handlerContext == null) handlerContext = ((Func<ITypedBuilderContext, HttpRequestMessage, HttpResponseMessage, Exception, TypedExceptionContext>)handlerInfo.InitialConstructor)(context, request, response, exception); else handlerContext = ((Func<TypedExceptionContext, TypedExceptionContext>)handlerInfo.ContinuationConstructor)(handlerContext); await handlerInfo.Handler(handlerContext); } return handlerContext?.GetHandlerResult(); } public TypedHandlerRegister WithHandler(ITypedHandler handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); if (_handlerInstances.Contains(handler)) throw new InvalidOperationException(SR.HanderAlreadyExistsError); _handlerInstances.Add(handler); WithAsyncSendingHandler<object, object>(handler.GetPriority(HandlerType.Sending), async ctx => { if (handler.Enabled) await handler.OnSending(ctx); }); WithAsyncSentHandler<object>(handler.GetPriority(HandlerType.Sent), async ctx => { if (handler.Enabled) await handler.OnSent(ctx); }); WithAsyncResultHandler<object>(handler.GetPriority(HandlerType.Result), async ctx => { if (handler.Enabled) await handler.OnResult(ctx); }); WithAsyncErrorHandler<object>(handler.GetPriority(HandlerType.Error), async ctx => { if (handler.Enabled) await handler.OnError(ctx); }); WithAsyncExceptionHandler(handler.GetPriority(HandlerType.Exception), async ctx => { if (handler.Enabled) await handler.OnException(ctx); }); return this; } public TypedHandlerRegister WithConfiguration<THandler>(Action<THandler> configure, bool throwOnNotFound = true) where THandler : class, ITypedHandler { if (configure == null) throw new ArgumentNullException(nameof(configure)); var handler = _handlerInstances.OfType<THandler>().FirstOrDefault(); if (handler == null) { if (throwOnNotFound) throw new KeyNotFoundException(string.Format(SR.HanderDoesNotExistErrorFormat, typeof(THandler).Name)); } else { configure(handler); } return this; } #region Sending public TypedHandlerRegister WithSendingHandler<TResult, TContent>(Action<TypedSendingContext<TResult, TContent>> handler) { return WithSendingHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithSendingHandler<TResult, TContent>(HandlerPriority priority, Action<TypedSendingContext<TResult, TContent>> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); return WithAsyncSendingHandler<TResult, TContent>(priority, handler.ToTask); } public TypedHandlerRegister WithAsyncSendingHandler<TResult, TContent>(Func<TypedSendingContext<TResult, TContent>, Task> handler) { return WithAsyncSendingHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithAsyncSendingHandler<TResult, TContent>(HandlerPriority priority, Func<TypedSendingContext<TResult, TContent>, Task> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); var handlerInfo = new TypedHandlerInfo { Handler = context => handler((TypedSendingContext<TResult, TContent>)context), InitialConstructor = GetOrAddFromCtorCache(HandlerType.Sending, handler.GetType(), false, (Func<ITypedBuilderContext, HttpRequestMessage, object, TypedSendingContext>)( (ctx, request, content) => new TypedSendingContext<TResult, TContent>(ctx, request, TypeHelpers.CheckType<TContent>(content, ctx.SuppressTypeMismatchExceptions)))), ContinuationConstructor = GetOrAddFromCtorCache(HandlerType.Sending, handler.GetType(), true, (Func<TypedSendingContext, TypedSendingContext>)( ctx => new TypedSendingContext<TResult, TContent>(ctx))), }; WithHandler(HandlerType.Sending, priority, handlerInfo); return this; } #endregion #region Sent public TypedHandlerRegister WithSentHandler<TResult>(Action<TypedSentContext<TResult>> handler) { return WithSentHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithSentHandler<TResult>(HandlerPriority priority, Action<TypedSentContext<TResult>> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); return WithAsyncSentHandler<TResult>(priority, handler.ToTask); } public TypedHandlerRegister WithAsyncSentHandler<TResult>(Func<TypedSentContext<TResult>, Task> handler) { return WithAsyncSentHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithAsyncSentHandler<TResult>(HandlerPriority priority, Func<TypedSentContext<TResult>, Task> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); var handlerInfo = new TypedHandlerInfo { Handler = context => handler((TypedSentContext<TResult>)context), InitialConstructor = GetOrAddFromCtorCache(HandlerType.Sent, handler.GetType(), false, (Func<ITypedBuilderContext, HttpRequestMessage, HttpResponseMessage, TypedSentContext>)((ctx, request, response) => new TypedSentContext<TResult>(ctx, request, response))), ContinuationConstructor = GetOrAddFromCtorCache(HandlerType.Sent, handler.GetType(), true, (Func<TypedSentContext, TypedSentContext>)(ctx => new TypedSentContext<TResult>(ctx))), }; WithHandler(HandlerType.Sent, priority, handlerInfo); return this; } #endregion #region Result public TypedHandlerRegister WithResultHandler<TResult>(Action<TypedResultContext<TResult>> handler) { return WithResultHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithResultHandler<TResult>(HandlerPriority priority, Action<TypedResultContext<TResult>> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); return WithAsyncResultHandler<TResult>(priority, handler.ToTask); } public TypedHandlerRegister WithAsyncResultHandler<TResult>(Func<TypedResultContext<TResult>, Task> handler) { return WithAsyncResultHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithAsyncResultHandler<TResult>(HandlerPriority priority, Func<TypedResultContext<TResult>, Task> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); var handlerInfo = new TypedHandlerInfo { Handler = context => handler((TypedResultContext<TResult>)context), InitialConstructor = GetOrAddFromCtorCache(HandlerType.Result, handler.GetType(), false, (Func<ITypedBuilderContext, HttpRequestMessage, HttpResponseMessage, object, TypedResultContext>)((ctx, request, response, result) => new TypedResultContext<TResult>(ctx, request, response, TypeHelpers.CheckType<TResult>( result, ctx.SuppressTypeMismatchExceptions)))), ContinuationConstructor = GetOrAddFromCtorCache(HandlerType.Result, handler.GetType(), true, (Func<TypedResultContext, TypedResultContext>)(ctx => new TypedResultContext<TResult>(ctx))), }; WithHandler(HandlerType.Result, priority, handlerInfo); return this; } #endregion #region Error public TypedHandlerRegister WithErrorHandler<TError>(Action<TypedErrorContext<TError>> handler) { return WithErrorHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithErrorHandler<TError>(HandlerPriority priority, Action<TypedErrorContext<TError>> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); return WithAsyncErrorHandler<TError>(priority, handler.ToTask); } public TypedHandlerRegister WithAsyncErrorHandler<TError>(Func<TypedErrorContext<TError>, Task> handler) { return WithAsyncErrorHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithAsyncErrorHandler<TError>(HandlerPriority priority, Func<TypedErrorContext<TError>, Task> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); var handlerInfo = new TypedHandlerInfo { Handler = context => handler((TypedErrorContext<TError>)context), InitialConstructor = GetOrAddFromCtorCache(HandlerType.Error, handler.GetType(), false, (Func<ITypedBuilderContext, HttpRequestMessage, HttpResponseMessage, object, TypedErrorContext>)((ctx, request, response, error) => new TypedErrorContext<TError>(ctx, request, response, TypeHelpers.CheckType<TError>(error, ctx.SuppressTypeMismatchExceptions)))), ContinuationConstructor = GetOrAddFromCtorCache(HandlerType.Error, handler.GetType(), true, (Func<TypedErrorContext, TypedErrorContext>)(ctx => new TypedErrorContext<TError>(ctx))), }; WithHandler(HandlerType.Error, priority, handlerInfo); return this; } #endregion #region Exception public TypedHandlerRegister WithExceptionHandler(Action<TypedExceptionContext> handler) { return WithExceptionHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithExceptionHandler(HandlerPriority priority, Action<TypedExceptionContext> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); return WithAsyncExceptionHandler(priority, handler.ToTask); } public TypedHandlerRegister WithAsyncExceptionHandler(Func<TypedExceptionContext, Task> handler) { return WithAsyncExceptionHandler(HandlerPriority.Default, handler); } public TypedHandlerRegister WithAsyncExceptionHandler(HandlerPriority priority, Func<TypedExceptionContext, Task> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); var handlerInfo = new TypedHandlerInfo { Handler = context => handler((TypedExceptionContext)context), InitialConstructor = GetOrAddFromCtorCache(HandlerType.Exception, handler.GetType(), false, (Func<ITypedBuilderContext, HttpRequestMessage, HttpResponseMessage, Exception, TypedExceptionContext>)((ctx, request, response, exception) => new TypedExceptionContext(ctx, request, response, exception))), ContinuationConstructor = GetOrAddFromCtorCache(HandlerType.Exception, handler.GetType(), true, (Func<TypedExceptionContext, TypedExceptionContext>)(ctx => new TypedExceptionContext(ctx))) }; WithHandler(HandlerType.Exception, priority, handlerInfo); return this; } #endregion private IEnumerable<TypedHandlerInfo> GetHandlerInfo(HandlerType type) { IDictionary<HandlerPriority, ICollection<TypedHandlerInfo>> handlers; lock (_handlers) { if (!_handlers.TryGetValue(type, out handlers)) { return Enumerable.Empty<TypedHandlerInfo>(); } return handlers.Keys.OrderBy(k => k).SelectMany(k => { ICollection<TypedHandlerInfo> col; if (!handlers.TryGetValue(k, out col)) { return Enumerable.Empty<TypedHandlerInfo>(); } return col; }); } } private void WithHandler(HandlerType type, HandlerPriority priority, TypedHandlerInfo handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); lock (_handlers) { if (!_handlers.ContainsKey(type)) { _handlers[type] = new Dictionary<HandlerPriority, ICollection<TypedHandlerInfo>>() { {priority, new List<TypedHandlerInfo> {handler}} }; } else { var handlersForType = _handlers[type]; if (!handlersForType.ContainsKey(priority)) { handlersForType[priority] = new List<TypedHandlerInfo> { handler }; } else { handlersForType[priority].Add(handler); } } } } private object GetOrAddFromCtorCache(HandlerType type, Type handlerType, bool isContinuation, object ctor) { var ctorType = isContinuation ? "C" : "I"; var key = $"{(int)type}:{handlerType.FormattedTypeName()}:{ctorType}"; lock (_contextConstructorCache) { if (!_contextConstructorCache.ContainsKey(key)) _contextConstructorCache[key] = ctor; return ctor; } } private class TypedHandlerInfo { public object InitialConstructor { get; set; } public object ContinuationConstructor { get; set; } public TypedHandlerDelegate Handler { get; set; } } } }
using CorDebugInterop; using nanoFramework.Tools.Debugger; using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace nanoFramework.Tools.VisualStudio.Debugger { public abstract class CorDebugValue : ICorDebugHeapValue, ICorDebugValue2 { protected RuntimeValue m_rtv; protected CorDebugAppDomain m_appDomain; public static CorDebugValue CreateValue(RuntimeValue rtv, CorDebugAppDomain appDomain) { CorDebugValue val = null; bool fIsReference; if (rtv.IsBoxed) { val = new CorDebugValueBoxedObject (rtv, appDomain); fIsReference = true; } else if (rtv.IsPrimitive) { CorDebugClass c = ClassFromRuntimeValue (rtv, appDomain); if (c.IsEnum) { val = new CorDebugValueObject (rtv, appDomain); fIsReference = false; } else { val = new CorDebugValuePrimitive (rtv, appDomain); fIsReference = false; } } else if (rtv.IsArray) { val = new CorDebugValueArray (rtv, appDomain); fIsReference = true; } else if (rtv.CorElementType == CorElementType.ELEMENT_TYPE_STRING) { val = new CorDebugValueString (rtv, appDomain); fIsReference = true; } else { val = new CorDebugValueObject (rtv, appDomain); fIsReference = !rtv.IsValueType; } if (fIsReference) { val = new CorDebugValueReference(val, val.m_rtv, val.m_appDomain); } if (rtv.IsReference) //CorElementType.ELEMENT_TYPE_BYREF { val = new CorDebugValueReferenceByRef(val, val.m_rtv, val.m_appDomain); } return val; } public static CorDebugValue[] CreateValues(RuntimeValue[] rtv, CorDebugAppDomain appDomain) { CorDebugValue [] values = new CorDebugValue[rtv.Length]; for (int i = 0; i < rtv.Length; i++) { values[i] = CorDebugValue.CreateValue(rtv[i], appDomain); } return values; } public static CorDebugClass ClassFromRuntimeValue(RuntimeValue rtv, CorDebugAppDomain appDomain) { RuntimeValue_Reflection rtvf = rtv as RuntimeValue_Reflection; CorDebugClass cls = null; object objBuiltInKey = null; Debug.Assert( !rtv.IsNull ); if (rtvf != null) { objBuiltInKey = rtvf.ReflectionType; } else if(rtv.DataType == RuntimeDataType.DATATYPE_TRANSPARENT_PROXY) { objBuiltInKey = RuntimeDataType.DATATYPE_TRANSPARENT_PROXY; } else { cls = nanoCLR_TypeSystem.CorDebugClassFromTypeIndex( rtv.Type, appDomain ); ; } if(objBuiltInKey != null) { CorDebugProcess.BuiltinType builtInType = appDomain.Process.ResolveBuiltInType( objBuiltInKey ); cls = builtInType.GetClass( appDomain ); if(cls == null) { cls = new CorDebugClass( builtInType.GetAssembly( appDomain ), builtInType.TokenCLR ); } } return cls; } public CorDebugValue(RuntimeValue rtv, CorDebugAppDomain appDomain) { m_rtv = rtv; m_appDomain = appDomain; } public virtual RuntimeValue RuntimeValue { get { return m_rtv; } set { //This should only be used if the underlying RuntimeValue changes, but not the data //For example, if we ever support compaction. For now, this is only used when the scratch //pad needs resizing, the RuntimeValues, and there associated heapblock*, will be relocated Debug.Assert (m_rtv.GetType () == value.GetType ()); Debug.Assert(m_rtv.CorElementType == value.CorElementType || value.IsNull || m_rtv.IsNull); //other debug checks here... m_rtv = value; } } public CorDebugAppDomain AppDomain { get { return m_appDomain; } } protected Engine Engine { [System.Diagnostics.DebuggerHidden] get {return m_appDomain.Engine;} } protected CorDebugValue CreateValue(RuntimeValue rtv) { return CorDebugValue.CreateValue(rtv, m_appDomain); } protected virtual CorElementType ElementTypeProtected { get { return m_rtv.CorElementType; } } public virtual uint Size { get { return 8; } } public virtual CorElementType Type { get { return this.ElementTypeProtected; } } public ICorDebugValue ICorDebugValue { get { return (ICorDebugValue)this; } } public ICorDebugHeapValue ICorDebugHeapValue { get { return (ICorDebugHeapValue)this; } } #region ICorDebugValue Members int ICorDebugValue.GetType( out CorElementType pType ) { pType = this.Type; return COM_HResults.S_OK; } int ICorDebugValue.GetSize( out uint pSize ) { pSize = this.Size; return COM_HResults.S_OK; } int ICorDebugValue.GetAddress( out ulong pAddress ) { pAddress = m_rtv.ReferenceIdDirect; return COM_HResults.S_OK; } int ICorDebugValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { ppBreakpoint = null; return COM_HResults.E_NOTIMPL; } #endregion #region ICorDebugHeapValue Members #region ICorDebugValue int ICorDebugHeapValue.GetType( out CorElementType pType ) { return this.ICorDebugValue.GetType( out pType ); } int ICorDebugHeapValue.GetSize( out uint pSize ) { return this.ICorDebugValue.GetSize( out pSize ); } int ICorDebugHeapValue.GetAddress( out ulong pAddress ) { return this.ICorDebugValue.GetAddress( out pAddress ); } int ICorDebugHeapValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugHeapValue int ICorDebugHeapValue.IsValid( out int pbValid ) { pbValid = Boolean.TRUE; return COM_HResults.S_OK; } int ICorDebugHeapValue.CreateRelocBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { ppBreakpoint = null; return COM_HResults.E_NOTIMPL; } #endregion #endregion #region ICorDebugValue2 Members int ICorDebugValue2.GetExactType(out ICorDebugType ppType) { ppType = new CorDebugGenericType(RuntimeValue.CorElementType, m_rtv, m_appDomain); return COM_HResults.S_OK; } #endregion } public class CorDebugValuePrimitive : CorDebugValue, ICorDebugGenericValue { public CorDebugValuePrimitive(RuntimeValue rtv, CorDebugAppDomain appDomain) : base(rtv, appDomain) { } protected virtual object ValueProtected { get { return m_rtv.Value; } set { m_rtv.Value = value; } } public override uint Size { get { object o = this.ValueProtected; return (uint)Marshal.SizeOf( o ); } } public ICorDebugGenericValue ICorDebugGenericValue { get {return (ICorDebugGenericValue)this;} } #region ICorDebugGenericValue Members #region ICorDebugValue int ICorDebugGenericValue.GetType( out CorElementType pType ) { return this.ICorDebugValue.GetType( out pType ); } int ICorDebugGenericValue.GetSize( out uint pSize ) { return this.ICorDebugValue.GetSize( out pSize ); } int ICorDebugGenericValue.GetAddress( out ulong pAddress ) { return this.ICorDebugValue.GetAddress( out pAddress ); } int ICorDebugGenericValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion int ICorDebugGenericValue.GetValue( IntPtr pTo ) { byte[] data = null; object val = this.ValueProtected; switch(this.ElementTypeProtected) { case CorElementType.ELEMENT_TYPE_BOOLEAN: data = BitConverter.GetBytes( (bool)val ); break; case CorElementType.ELEMENT_TYPE_I1: data = new byte[] { (byte)(sbyte)val }; break; case CorElementType.ELEMENT_TYPE_U1: data = new byte[] { (byte)val }; break; case CorElementType.ELEMENT_TYPE_CHAR: data = BitConverter.GetBytes( (char)val ); break; case CorElementType.ELEMENT_TYPE_I2: data = BitConverter.GetBytes( (short)val ); break; case CorElementType.ELEMENT_TYPE_U2: data = BitConverter.GetBytes( (ushort)val ); break; case CorElementType.ELEMENT_TYPE_I4: data = BitConverter.GetBytes( (int)val ); break; case CorElementType.ELEMENT_TYPE_U4: data = BitConverter.GetBytes( (uint)val ); break; case CorElementType.ELEMENT_TYPE_R4: data = BitConverter.GetBytes( (float)val ); break; case CorElementType.ELEMENT_TYPE_I8: data = BitConverter.GetBytes( (long)val ); break; case CorElementType.ELEMENT_TYPE_U8: data = BitConverter.GetBytes( (ulong)val ); break; case CorElementType.ELEMENT_TYPE_R8: data = BitConverter.GetBytes( (double)val ); break; default: Debug.Assert( false ); break; } Marshal.Copy( data, 0, pTo, data.Length ); return COM_HResults.S_OK; } int ICorDebugGenericValue.SetValue( IntPtr pFrom ) { object val = null; uint cByte = this.Size; byte[] data = new byte[cByte]; Marshal.Copy( pFrom, data, 0, (int)cByte ); switch(this.ElementTypeProtected) { case CorElementType.ELEMENT_TYPE_BOOLEAN: val = BitConverter.ToBoolean( data, 0 ); break; case CorElementType.ELEMENT_TYPE_I1: val = (sbyte)data[0]; break; case CorElementType.ELEMENT_TYPE_U1: val = data[0]; break; case CorElementType.ELEMENT_TYPE_CHAR: val = BitConverter.ToChar( data, 0 ); break; case CorElementType.ELEMENT_TYPE_I2: val = BitConverter.ToInt16( data, 0 ); break; case CorElementType.ELEMENT_TYPE_U2: val = BitConverter.ToUInt16( data, 0 ); break; case CorElementType.ELEMENT_TYPE_I4: val = BitConverter.ToInt32( data, 0 ); break; case CorElementType.ELEMENT_TYPE_U4: val = BitConverter.ToUInt32( data, 0 ); break; case CorElementType.ELEMENT_TYPE_R4: val = BitConverter.ToSingle( data, 0 ); break; case CorElementType.ELEMENT_TYPE_I8: val = BitConverter.ToInt64( data, 0 ); break; case CorElementType.ELEMENT_TYPE_U8: val = BitConverter.ToUInt64( data, 0 ); break; case CorElementType.ELEMENT_TYPE_R8: val = BitConverter.ToDouble( data, 0 ); break; } this.ValueProtected = val; return COM_HResults.S_OK; } #endregion } public class CorDebugValueBoxedObject : CorDebugValue, ICorDebugBoxValue { CorDebugValueObject m_value; public CorDebugValueBoxedObject(RuntimeValue rtv, CorDebugAppDomain appDomain) : base (rtv, appDomain) { m_value = new CorDebugValueObject (rtv, appDomain); } public override RuntimeValue RuntimeValue { set { m_value.RuntimeValue = value; base.RuntimeValue = value; } } public override CorElementType Type { get { return CorElementType.ELEMENT_TYPE_CLASS; } } #region ICorDebugBoxValue Members #region ICorDebugValue int ICorDebugBoxValue.GetType( out CorElementType pType ) { return this.ICorDebugValue.GetType( out pType ); } int ICorDebugBoxValue.GetSize( out uint pSize ) { return this.ICorDebugValue.GetSize( out pSize ); } int ICorDebugBoxValue.GetAddress( out ulong pAddress ) { return this.ICorDebugValue.GetAddress( out pAddress ); } int ICorDebugBoxValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugHeapValue int ICorDebugBoxValue.IsValid( out int pbValid ) { return this.ICorDebugHeapValue.IsValid( out pbValid ); } int ICorDebugBoxValue.CreateRelocBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugBoxValue int ICorDebugBoxValue.GetObject( out ICorDebugObjectValue ppObject ) { ppObject = m_value; return COM_HResults.S_OK; } #endregion #endregion } public class CorDebugValueReference : CorDebugValue, ICorDebugHandleValue, ICorDebugValue2 { private CorDebugValue m_value; public CorDebugValueReference( CorDebugValue val, RuntimeValue rtv, CorDebugAppDomain appDomain ) : base( rtv, appDomain ) { m_value = val; } public override RuntimeValue RuntimeValue { set { m_value.RuntimeValue = value; base.RuntimeValue = value; } } public override CorElementType Type { get { return m_value.Type; } } public ICorDebugReferenceValue ICorDebugReferenceValue { get { return (ICorDebugReferenceValue)this; } } #region ICorDebugReferenceValue Members #region ICorDebugValue2 Members int ICorDebugValue2.GetExactType(out ICorDebugType ppType) { return ((ICorDebugValue2)m_value).GetExactType( out ppType); } #endregion #region ICorDebugValue int ICorDebugReferenceValue.GetType( out CorElementType pType ) { return this.ICorDebugValue.GetType( out pType ); } int ICorDebugReferenceValue.GetSize( out uint pSize ) { return this.ICorDebugValue.GetSize( out pSize ); } int ICorDebugReferenceValue.GetAddress( out ulong pAddress ) { return this.ICorDebugValue.GetAddress( out pAddress ); } int ICorDebugReferenceValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugReferenceValue int ICorDebugReferenceValue.IsNull( out int pbNull ) { pbNull = Boolean.BoolToInt( m_rtv.IsNull ); return COM_HResults.S_OK; } int ICorDebugReferenceValue.GetValue( out ulong pValue ) { pValue = (ulong)m_rtv.ReferenceIdDirect; return COM_HResults.S_OK; } int ICorDebugReferenceValue.SetValue( ulong value ) { Debug.Assert( value <= uint.MaxValue ); var assign = m_rtv.AssignAsync((uint)value); assign.Wait(); RuntimeValue rtvNew = assign.Result; this.RuntimeValue = rtvNew; return COM_HResults.S_OK; } int ICorDebugReferenceValue.Dereference( out ICorDebugValue ppValue ) { ppValue = m_value; return COM_HResults.S_OK; } int ICorDebugReferenceValue.DereferenceStrong( out ICorDebugValue ppValue ) { return this.ICorDebugReferenceValue.Dereference( out ppValue ); } #endregion #endregion #region ICorDebugHandleValue Members #region ICorDebugValue int ICorDebugHandleValue.GetType( out CorElementType pType ) { return this.ICorDebugValue.GetType( out pType ); } int ICorDebugHandleValue.GetSize( out uint pSize ) { return this.ICorDebugValue.GetSize( out pSize ); } int ICorDebugHandleValue.GetAddress( out ulong pAddress ) { return this.ICorDebugValue.GetAddress( out pAddress ); } int ICorDebugHandleValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugReferenceValue int ICorDebugHandleValue.IsNull( out int pbNull ) { return this.ICorDebugReferenceValue.IsNull( out pbNull ); } int ICorDebugHandleValue.GetValue( out ulong pValue ) { return this.ICorDebugReferenceValue.GetValue( out pValue ); } int ICorDebugHandleValue.SetValue( ulong value ) { return this.ICorDebugReferenceValue.SetValue( value ); } int ICorDebugHandleValue.Dereference( out ICorDebugValue ppValue ) { return this.ICorDebugReferenceValue.Dereference( out ppValue ); } int ICorDebugHandleValue.DereferenceStrong( out ICorDebugValue ppValue ) { return this.ICorDebugReferenceValue.DereferenceStrong( out ppValue ); } #endregion #region ICorDebugHandleValue int ICorDebugHandleValue.GetHandleType( out CorDebugHandleType pType ) { pType = CorDebugHandleType.HANDLE_STRONG; return COM_HResults.S_OK; } int ICorDebugHandleValue.Dispose() { return COM_HResults.S_OK; } #endregion #endregion } public class CorDebugValueReferenceByRef : CorDebugValueReference { public CorDebugValueReferenceByRef(CorDebugValue val, RuntimeValue rtv, CorDebugAppDomain appDomain) : base(val, rtv, appDomain) { } public override CorElementType Type { get { return CorElementType.ELEMENT_TYPE_BYREF; } } } public class CorDebugValueArray : CorDebugValue, ICorDebugArrayValue, ICorDebugValue2 { public CorDebugValueArray(RuntimeValue rtv, CorDebugAppDomain appDomain) : base(rtv, appDomain) { } public static CorElementType typeValue = CorElementType.ELEMENT_TYPE_I4; public uint Count { get { return m_rtv.Length; } } public ICorDebugArrayValue ICorDebugArrayValue { get { return (ICorDebugArrayValue)this; } } #region ICorDebugArrayValue Members #region ICorDebugValue int ICorDebugArrayValue.GetType( out CorElementType pType ) { return this.ICorDebugValue.GetType( out pType ); } int ICorDebugArrayValue.GetSize( out uint pSize ) { return this.ICorDebugValue.GetSize( out pSize ); } int ICorDebugArrayValue.GetAddress( out ulong pAddress ) { return this.ICorDebugValue.GetAddress( out pAddress ); } int ICorDebugArrayValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugValue2 Members int ICorDebugValue2.GetExactType(out ICorDebugType ppType) { ppType = new CorDebugTypeArray( this ); return COM_HResults.S_OK; } #endregion #region ICorDebugHeapValue int ICorDebugArrayValue.IsValid( out int pbValid ) { return this.ICorDebugHeapValue.IsValid( out pbValid ); } int ICorDebugArrayValue.CreateRelocBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugArrayValue /* With implementation of ICorDebugValue2.GetExactType this function * ICorDebugArrayValue.GetElementType is not called. * It is left to support VS 2005. * We cannot remove this function since it is part of ICorDebugArrayValue interface. */ int ICorDebugArrayValue.GetElementType( out CorElementType pType ) { if (this.Count != 0) { var getElement = m_rtv.GetElementAsync(0); getElement.Wait(); pType = getElement.Result.CorElementType; } else { pType = CorElementType.ELEMENT_TYPE_CLASS; } return COM_HResults.S_OK; } int ICorDebugArrayValue.GetRank( out uint pnRank ) { pnRank = 1; return COM_HResults.S_OK; } int ICorDebugArrayValue.GetCount( out uint pnCount ) { pnCount = this.Count; return COM_HResults.S_OK; } int ICorDebugArrayValue.GetDimensions( uint cdim, uint[] dims ) { Debug.Assert( cdim == 1 ); dims[0] = this.Count; return COM_HResults.S_OK; } int ICorDebugArrayValue.HasBaseIndicies( out int pbHasBaseIndicies ) { pbHasBaseIndicies = Boolean.FALSE; return COM_HResults.S_OK; } int ICorDebugArrayValue.GetBaseIndicies( uint cdim, uint[] indicies ) { Debug.Assert( cdim == 1 ); indicies[0] = 0; return COM_HResults.S_OK; } int ICorDebugArrayValue.GetElement( uint cdim, uint[] indices, out ICorDebugValue ppValue ) { //ask for several at once and cache? Debug.Assert( cdim == 1 ); var getElement = m_rtv.GetElementAsync(indices[0]); getElement.Wait(); ppValue = CreateValue(getElement.Result); return COM_HResults.S_OK; } int ICorDebugArrayValue.GetElementAtPosition( uint nPosition, out ICorDebugValue ppValue ) { var getElement = m_rtv.GetElementAsync(nPosition); getElement.Wait(); //Cache values? ppValue = CreateValue(getElement.Result); return COM_HResults.S_OK; } #endregion #endregion } public class CorDebugValueObject : CorDebugValue, ICorDebugObjectValue, ICorDebugGenericValue /*, ICorDebugObjectValue2*/ { CorDebugClass m_class = null; CorDebugValuePrimitive m_valuePrimitive = null; //for boxed primitives, or enums bool m_fIsEnum; bool m_fIsBoxed; //Object or CLASS, or VALUETYPE public CorDebugValueObject(RuntimeValue rtv, CorDebugAppDomain appDomain) : base(rtv, appDomain) { if(!rtv.IsNull) { m_class = CorDebugValue.ClassFromRuntimeValue(rtv, appDomain); m_fIsEnum = m_class.IsEnum; m_fIsBoxed = rtv.IsBoxed; } } private bool IsValuePrimitive() { if (m_fIsBoxed || m_fIsEnum) { if (m_valuePrimitive == null) { if (m_rtv.IsBoxed) { var getField = m_rtv.GetFieldAsync(1, 0); getField.Wait(); RuntimeValue rtv = getField.Result; Debug.Assert(rtv.IsPrimitive); //Assert that m_class really points to a primitive m_valuePrimitive = (CorDebugValuePrimitive)CreateValue(rtv); } else { Debug.Assert(m_fIsEnum); m_valuePrimitive = new CorDebugValuePrimitive(m_rtv, m_appDomain); Debug.Assert(m_rtv.IsPrimitive); } } } return m_valuePrimitive != null; } public override uint Size { get { if (this.IsValuePrimitive()) { return m_valuePrimitive.Size; } else { return 4; } } } public override CorElementType Type { get { if(m_fIsEnum) { return CorElementType.ELEMENT_TYPE_VALUETYPE; } else { return base.Type; } } } #region ICorDebugObjectValue Members #region ICorDebugValue int ICorDebugObjectValue.GetType( out CorElementType pType ) { return this.ICorDebugValue.GetType( out pType ); } int ICorDebugObjectValue.GetSize( out uint pSize ) { return this.ICorDebugValue.GetSize( out pSize ); } int ICorDebugObjectValue.GetAddress( out ulong pAddress ) { return this.ICorDebugValue.GetAddress( out pAddress ); } int ICorDebugObjectValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugObjectValue int ICorDebugObjectValue.GetClass( out ICorDebugClass ppClass ) { ppClass = m_class; return COM_HResults.S_OK; } int ICorDebugObjectValue.GetFieldValue( ICorDebugClass pClass, uint fieldDef, out ICorDebugValue ppValue ) { var getField = m_rtv.GetFieldAsync(0, nanoCLR_TypeSystem.ClassMemberIndexFromCLRToken(fieldDef, ((CorDebugClass)pClass).Assembly)); getField.Wait(); //cache fields? RuntimeValue rtv = getField.Result; ppValue = CreateValue( rtv ); return COM_HResults.S_OK; } int ICorDebugObjectValue.GetVirtualMethod( uint memberRef, out ICorDebugFunction ppFunction ) { var getVirtualMethod = Engine.GetVirtualMethodAsync(nanoCLR_TypeSystem.ClassMemberIndexFromCLRToken(memberRef, this.m_class.Assembly), this.m_rtv); getVirtualMethod.Wait(); uint mdVirtual = getVirtualMethod.Result; ppFunction = nanoCLR_TypeSystem.CorDebugFunctionFromMethodIndex( mdVirtual, this.m_appDomain ); return COM_HResults.S_OK; } int ICorDebugObjectValue.GetContext( out ICorDebugContext ppContext ) { ppContext = null; return COM_HResults.S_OK; } int ICorDebugObjectValue.IsValueClass( out int pbIsValueClass ) { pbIsValueClass = Boolean.BoolToInt( m_rtv.IsValueType ); return COM_HResults.S_OK; } int ICorDebugObjectValue.GetManagedCopy( out object ppObject ) { ppObject = null; Debug.Assert( false ); return COM_HResults.S_OK; } int ICorDebugObjectValue.SetFromManagedCopy( object pObject ) { return COM_HResults.S_OK; } #endregion #endregion #region ICorDebugGenericValue Members #region ICorDebugValue int ICorDebugGenericValue.GetType( out CorElementType pType ) { return this.ICorDebugValue.GetType( out pType ); } int ICorDebugGenericValue.GetSize( out uint pSize ) { return this.ICorDebugValue.GetSize( out pSize ); } int ICorDebugGenericValue.GetAddress( out ulong pAddress ) { return this.ICorDebugValue.GetAddress( out pAddress ); } int ICorDebugGenericValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugGenericValue int ICorDebugGenericValue.GetValue( IntPtr pTo ) { int hr = COM_HResults.S_OK; if (this.IsValuePrimitive()) { hr = m_valuePrimitive.ICorDebugGenericValue.GetValue(pTo); } else { ulong addr; hr = ((ICorDebugGenericValue)this).GetAddress(out addr); Marshal.WriteInt32(pTo, (int)addr); } return hr; } int ICorDebugGenericValue.SetValue( IntPtr pFrom ) { int hr = COM_HResults.S_OK; if (this.IsValuePrimitive()) { hr = m_valuePrimitive.ICorDebugGenericValue.SetValue(pFrom); } else { Debug.Assert(false); } return hr; } #endregion #endregion } public class CorDebugValueString : CorDebugValue, ICorDebugStringValue { public CorDebugValueString( RuntimeValue rtv, CorDebugAppDomain appDomain ) : base( rtv, appDomain ) { } private string Value { get { string ret = m_rtv.Value as string; return (ret == null) ? "" : ret; } } #region ICorDebugStringValue Members #region ICorDebugValue int ICorDebugStringValue.GetType( out CorElementType pType ) { return this.ICorDebugValue.GetType( out pType ); } int ICorDebugStringValue.GetSize( out uint pSize ) { return this.ICorDebugValue.GetSize( out pSize ); } int ICorDebugStringValue.GetAddress( out ulong pAddress ) { return this.ICorDebugValue.GetAddress( out pAddress ); } int ICorDebugStringValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugHeapValue int ICorDebugStringValue.IsValid( out int pbValid ) { return this.ICorDebugHeapValue.IsValid( out pbValid ); } int ICorDebugStringValue.CreateRelocBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint ) { return this.ICorDebugHeapValue.CreateRelocBreakpoint( out ppBreakpoint ); } #endregion #region ICorDebugStringValue int ICorDebugStringValue.GetLength( out uint pcchString ) { pcchString = (uint)Value.Length; return COM_HResults.S_OK; } int ICorDebugStringValue.GetString( uint cchString, IntPtr pcchString, IntPtr szString ) { Utility.MarshalString( Value, cchString, pcchString, szString, false ); return COM_HResults.S_OK; } #endregion #endregion } }
// 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.Drawing; using System.Diagnostics.Contracts; namespace System.Windows.Forms { // Summary: // Represents a display device or multiple display devices on a single system. public class Screen { private Screen() { } // Summary: // Gets an array of all displays on the system. // // Returns: // An array of type System.Windows.Forms.Screen, containing all displays on // the system. public static Screen[] AllScreens { get { Contract.Ensures(Contract.Result<Screen[]>() != null); return default(Screen[]); } } // // Summary: // Gets the number of bits of memory, associated with one pixel of data. // // Returns: // The number of bits of memory, associated with one pixel of data public int BitsPerPixel { get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } } // // Summary: // Gets the bounds of the display. // // Returns: // A System.Drawing.Rectangle, representing the bounds of the display. //public Rectangle Bounds { get; } // // Summary: // Gets the device name associated with a display. // // Returns: // The device name associated with a display. public string DeviceName { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } // // Summary: // Gets a value indicating whether a particular display is the primary device. // // Returns: // true if this display is primary; otherwise, false. //public bool Primary { get; } // // Summary: // Gets the primary display. // // Returns: // The primary display. // F: It seems that PrimaryScreen can be null in some configurations //public static Screen PrimaryScreen { get; } //// //// Summary: //// Gets the working area of the display. The working area is the desktop area //// of the display, excluding taskbars, docked windows, and docked tool bars. //// //// Returns: //// A System.Drawing.Rectangle, representing the working area of the display. //public Rectangle WorkingArea { get; } //// Summary: //// Gets or sets a value indicating whether the specified object is equal to //// this Screen. //// //// Parameters: //// obj: //// The object to compare to this System.Windows.Forms.Screen. //// //// Returns: //// true if the specified object is equal to this System.Windows.Forms.Screen; //// otherwise, false. //public override bool Equals(object obj); //// //// Summary: //// Retrieves a System.Windows.Forms.Screen for the display that contains the //// largest portion of the specified control. //// //// Parameters: //// control: //// A System.Windows.Forms.Control for which to retrieve a System.Windows.Forms.Screen. //// //// Returns: //// A System.Windows.Forms.Screen for the display that contains the largest region //// of the specified control. In multiple display environments where no display //// contains the control, the display closest to the specified control is returned. public static Screen FromControl(Control control) { Contract.Requires(control != null); Contract.Ensures(Contract.Result<Screen>() != null); return default(Screen); } //// //// Summary: //// Retrieves a System.Windows.Forms.Screen for the display that contains the //// largest portion of the object referred to by the specified handle. //// //// Parameters: //// hwnd: //// The window handle for which to retrieve the System.Windows.Forms.Screen. //// //// Returns: //// A System.Windows.Forms.Screen for the display that contains the largest region //// of the object. In multiple display environments where no display contains //// any portion of the specified window, the display closest to the object is //// returned. public static Screen FromHandle(IntPtr hwnd) { Contract.Ensures(Contract.Result<Screen>() != null); return default(Screen); } //// //// Summary: //// Retrieves a System.Windows.Forms.Screen for the display that contains the //// specified point. //// //// Parameters: //// point: //// A System.Drawing.Point that specifies the location for which to retrieve //// a System.Windows.Forms.Screen. //// //// Returns: //// A System.Windows.Forms.Screen for the display that contains the point. In //// multiple display environments where no display contains the point, the display //// closest to the specified point is returned. public static Screen FromPoint(Point point) { Contract.Ensures(Contract.Result<Screen>() != null); return default(Screen); } //// //// Summary: //// Retrieves a System.Windows.Forms.Screen for the display that contains the //// largest portion of the rectangle. //// //// Parameters: //// rect: //// A System.Drawing.Rectangle that specifies the area for which to retrieve //// the display. //// //// Returns: //// A System.Windows.Forms.Screen for the display that contains the largest region //// of the specified rectangle. In multiple display environments where no display //// contains the rectangle, the display closest to the rectangle is returned. public static Screen FromRectangle(Rectangle rect) { Contract.Ensures(Contract.Result<Screen>() != null); return default(Screen); } //// //// Summary: //// Retrieves the bounds of the display that contains the largest portion of //// the specified control. //// //// Parameters: //// ctl: //// The System.Windows.Forms.Control for which to retrieve the display bounds. //// //// Returns: //// A System.Drawing.Rectangle that specifies the bounds of the display that //// contains the specified control. In multiple display environments where no //// display contains the specified control, the display closest to the control //// is returned. [Pure] public static Rectangle GetBounds(Control ctl) { Contract.Requires(ctl != null); return default(Rectangle); } //// //// Summary: //// Retrieves the bounds of the display that contains the specified point. //// //// Parameters: //// pt: //// A System.Drawing.Point that specifies the coordinates for which to retrieve //// the display bounds. //// //// Returns: //// A System.Drawing.Rectangle that specifies the bounds of the display that //// contains the specified point. In multiple display environments where no display //// contains the specified point, the display closest to the point is returned. //public static Rectangle GetBounds(Point pt); //// //// Summary: //// Retrieves the bounds of the display that contains the largest portion of //// the specified rectangle. //// //// Parameters: //// rect: //// A System.Drawing.Rectangle that specifies the area for which to retrieve //// the display bounds. //// //// Returns: //// A System.Drawing.Rectangle that specifies the bounds of the display that //// contains the specified rectangle. In multiple display environments where //// no monitor contains the specified rectangle, the monitor closest to the rectangle //// is returned. //public static Rectangle GetBounds(Rectangle rect); //// //// Summary: //// Computes and retrieves a hash code for an object. //// //// Returns: //// A hash code for an object. //public override int GetHashCode(); //// //// Summary: //// Retrieves the working area for the display that contains the largest region //// of the specified control. The working area is the desktop area of the display, //// excluding taskbars, docked windows, and docked tool bars. //// //// Parameters: //// ctl: //// The System.Windows.Forms.Control for which to retrieve the working area. //// //// Returns: //// A System.Drawing.Rectangle that specifies the working area. In multiple display //// environments where no display contains the specified control, the display //// closest to the control is returned. [Pure] public static Rectangle GetWorkingArea(Control ctl) { Contract.Requires(ctl != null); return default(Rectangle); } //// //// Summary: //// Retrieves the working area closest to the specified point. The working area //// is the desktop area of the display, excluding taskbars, docked windows, and //// docked tool bars. //// //// Parameters: //// pt: //// A System.Drawing.Point that specifies the coordinates for which to retrieve //// the working area. //// //// Returns: //// A System.Drawing.Rectangle that specifies the working area. In multiple display //// environments where no display contains the specified point, the display closest //// to the point is returned. //public static Rectangle GetWorkingArea(Point pt); //// //// Summary: //// Retrieves the working area for the display that contains the largest portion //// of the specified rectangle. The working area is the desktop area of the display, //// excluding taskbars, docked windows, and docked tool bars. //// //// Parameters: //// rect: //// The System.Drawing.Rectangle that specifies the area for which to retrieve //// the working area. //// //// Returns: //// A System.Drawing.Rectangle that specifies the working area. In multiple display //// environments where no display contains the specified rectangle, the display //// closest to the rectangle is returned. //public static Rectangle GetWorkingArea(Rectangle rect); //// //// Summary: //// Retrieves a string representing this object. //// //// Returns: //// A string representation of the object. //public override string ToString(); } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation connections. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> internal partial class ConnectionOperations : IServiceOperations<AutomationManagementClient>, IConnectionOperations { /// <summary> /// Initializes a new instance of the ConnectionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ConnectionOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Create a connection. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create or update /// connection operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the create or update connection operation. /// </returns> public async Task<ConnectionCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string automationAccount, ConnectionCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.ConnectionType == null) { throw new ArgumentNullException("parameters.Properties.ConnectionType"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections/"; url = url + Uri.EscapeDataString(parameters.Name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject connectionCreateOrUpdateParametersValue = new JObject(); requestDoc = connectionCreateOrUpdateParametersValue; connectionCreateOrUpdateParametersValue["name"] = parameters.Name; JObject propertiesValue = new JObject(); connectionCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.Description != null) { propertiesValue["description"] = parameters.Properties.Description; } JObject connectionTypeValue = new JObject(); propertiesValue["connectionType"] = connectionTypeValue; if (parameters.Properties.ConnectionType.Name != null) { connectionTypeValue["name"] = parameters.Properties.ConnectionType.Name; } if (parameters.Properties.FieldDefinitionValues != null) { if (parameters.Properties.FieldDefinitionValues is ILazyCollection == false || ((ILazyCollection)parameters.Properties.FieldDefinitionValues).IsInitialized) { JObject fieldDefinitionValuesDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties.FieldDefinitionValues) { string fieldDefinitionValuesKey = pair.Key; string fieldDefinitionValuesValue = pair.Value; fieldDefinitionValuesDictionary[fieldDefinitionValuesKey] = fieldDefinitionValuesValue; } propertiesValue["fieldDefinitionValues"] = fieldDefinitionValuesDictionary; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ConnectionCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ConnectionCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Connection connectionInstance = new Connection(); result.Connection = connectionInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); connectionInstance.Name = nameInstance; } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ConnectionProperties propertiesInstance = new ConnectionProperties(); connectionInstance.Properties = propertiesInstance; JToken connectionTypeValue2 = propertiesValue2["connectionType"]; if (connectionTypeValue2 != null && connectionTypeValue2.Type != JTokenType.Null) { ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty(); propertiesInstance.ConnectionType = connectionTypeInstance; JToken nameValue2 = connectionTypeValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); connectionTypeInstance.Name = nameInstance2; } } JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue2["fieldDefinitionValues"]); if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in fieldDefinitionValuesSequenceElement) { string fieldDefinitionValuesKey2 = ((string)property.Name); string fieldDefinitionValuesValue2 = ((string)property.Value); propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey2, fieldDefinitionValuesValue2); } } JToken creationTimeValue = propertiesValue2["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue2["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete the connection. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionName'> /// Required. The name of connection. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, string connectionName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (connectionName == null) { throw new ArgumentNullException("connectionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("connectionName", connectionName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections/"; url = url + Uri.EscapeDataString(connectionName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the connection identified by connection name. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionName'> /// Required. The name of connection. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get connection operation. /// </returns> public async Task<ConnectionGetResponse> GetAsync(string resourceGroupName, string automationAccount, string connectionName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (connectionName == null) { throw new ArgumentNullException("connectionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("connectionName", connectionName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections/"; url = url + Uri.EscapeDataString(connectionName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ConnectionGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ConnectionGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Connection connectionInstance = new Connection(); result.Connection = connectionInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); connectionInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ConnectionProperties propertiesInstance = new ConnectionProperties(); connectionInstance.Properties = propertiesInstance; JToken connectionTypeValue = propertiesValue["connectionType"]; if (connectionTypeValue != null && connectionTypeValue.Type != JTokenType.Null) { ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty(); propertiesInstance.ConnectionType = connectionTypeInstance; JToken nameValue2 = connectionTypeValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); connectionTypeInstance.Name = nameInstance2; } } JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue["fieldDefinitionValues"]); if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in fieldDefinitionValuesSequenceElement) { string fieldDefinitionValuesKey = ((string)property.Name); string fieldDefinitionValuesValue = ((string)property.Value); propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey, fieldDefinitionValuesValue); } } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve a list of connections. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list connection operation. /// </returns> public async Task<ConnectionListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ConnectionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ConnectionListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Connection connectionInstance = new Connection(); result.Connection.Add(connectionInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); connectionInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ConnectionProperties propertiesInstance = new ConnectionProperties(); connectionInstance.Properties = propertiesInstance; JToken connectionTypeValue = propertiesValue["connectionType"]; if (connectionTypeValue != null && connectionTypeValue.Type != JTokenType.Null) { ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty(); propertiesInstance.ConnectionType = connectionTypeInstance; JToken nameValue2 = connectionTypeValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); connectionTypeInstance.Name = nameInstance2; } } JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue["fieldDefinitionValues"]); if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in fieldDefinitionValuesSequenceElement) { string fieldDefinitionValuesKey = ((string)property.Name); string fieldDefinitionValuesValue = ((string)property.Value); propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey, fieldDefinitionValuesValue); } } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve next list of connections. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list connection operation. /// </returns> public async Task<ConnectionListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ConnectionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ConnectionListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Connection connectionInstance = new Connection(); result.Connection.Add(connectionInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); connectionInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ConnectionProperties propertiesInstance = new ConnectionProperties(); connectionInstance.Properties = propertiesInstance; JToken connectionTypeValue = propertiesValue["connectionType"]; if (connectionTypeValue != null && connectionTypeValue.Type != JTokenType.Null) { ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty(); propertiesInstance.ConnectionType = connectionTypeInstance; JToken nameValue2 = connectionTypeValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); connectionTypeInstance.Name = nameInstance2; } } JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue["fieldDefinitionValues"]); if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in fieldDefinitionValuesSequenceElement) { string fieldDefinitionValuesKey = ((string)property.Name); string fieldDefinitionValuesValue = ((string)property.Value); propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey, fieldDefinitionValuesValue); } } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update a connection. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the patch a connection /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> PatchAsync(string resourceGroupName, string automationAccount, ConnectionPatchParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections/"; if (parameters.Name != null) { url = url + Uri.EscapeDataString(parameters.Name); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject connectionPatchParametersValue = new JObject(); requestDoc = connectionPatchParametersValue; if (parameters.Name != null) { connectionPatchParametersValue["name"] = parameters.Name; } JObject propertiesValue = new JObject(); connectionPatchParametersValue["properties"] = propertiesValue; if (parameters.Properties.Description != null) { propertiesValue["description"] = parameters.Properties.Description; } if (parameters.Properties.FieldDefinitionValues != null) { if (parameters.Properties.FieldDefinitionValues is ILazyCollection == false || ((ILazyCollection)parameters.Properties.FieldDefinitionValues).IsInitialized) { JObject fieldDefinitionValuesDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties.FieldDefinitionValues) { string fieldDefinitionValuesKey = pair.Key; string fieldDefinitionValuesValue = pair.Value; fieldDefinitionValuesDictionary[fieldDefinitionValuesKey] = fieldDefinitionValuesValue; } propertiesValue["fieldDefinitionValues"] = fieldDefinitionValuesDictionary; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft Open Technologies, Inc. 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.Web.WebPages.TestUtils; using Microsoft.AspNet.Razor.Text; using Xunit; namespace Microsoft.AspNet.Razor.Test.Text { public class TextBufferReaderTest : LookaheadTextReaderTestBase { protected override LookaheadTextReader CreateReader(string testString) { return new TextBufferReader(new StringTextBuffer(testString)); } [Fact] public void ConstructorRequiresNonNullTextBuffer() { Assert.Throws<ArgumentNullException>("buffer", () => new TextBufferReader(null)); } [Fact] public void PeekReturnsCurrentCharacterWithoutAdvancingPosition() { RunPeekTest("abc", peekAt: 2); } [Fact] public void PeekReturnsNegativeOneAtEndOfSourceReader() { RunPeekTest("abc", peekAt: 3); } [Fact] public void ReadReturnsCurrentCharacterAndAdvancesToNextCharacter() { RunReadTest("abc", readAt: 2); } [Fact] public void EndingLookaheadReturnsReaderToPreviousLocation() { RunLookaheadTest("abcdefg", "abcb", Read, Lookahead( Read, Read), Read); } [Fact] public void MultipleLookaheadsCanBePerformed() { RunLookaheadTest("abcdefg", "abcbcdc", Read, Lookahead( Read, Read), Read, Lookahead( Read, Read), Read); } [Fact] public void LookaheadsCanBeNested() { RunLookaheadTest("abcdefg", "abcdefebc", Read, // Appended: "a" Reader: "bcdefg" Lookahead( // Reader: "bcdefg" Read, // Appended: "b" Reader: "cdefg"; Read, // Appended: "c" Reader: "defg"; Read, // Appended: "d" Reader: "efg"; Lookahead( // Reader: "efg" Read, // Appended: "e" Reader: "fg"; Read // Appended: "f" Reader: "g"; ), // Reader: "efg" Read // Appended: "e" Reader: "fg"; ), // Reader: "bcdefg" Read, // Appended: "b" Reader: "cdefg"; Read); // Appended: "c" Reader: "defg"; } [Fact] public void SourceLocationIsZeroWhenInitialized() { RunSourceLocationTest("abcdefg", SourceLocation.Zero, checkAt: 0); } [Fact] public void CharacterAndAbsoluteIndicesIncreaseAsCharactersAreRead() { RunSourceLocationTest("abcdefg", new SourceLocation(4, 0, 4), checkAt: 4); } [Fact] public void CharacterAndAbsoluteIndicesIncreaseAsSlashRInTwoCharacterNewlineIsRead() { RunSourceLocationTest("f\r\nb", new SourceLocation(2, 0, 2), checkAt: 2); } [Fact] public void CharacterIndexResetsToZeroAndLineIndexIncrementsWhenSlashNInTwoCharacterNewlineIsRead() { RunSourceLocationTest("f\r\nb", new SourceLocation(3, 1, 0), checkAt: 3); } [Fact] public void CharacterIndexResetsToZeroAndLineIndexIncrementsWhenSlashRInSingleCharacterNewlineIsRead() { RunSourceLocationTest("f\rb", new SourceLocation(2, 1, 0), checkAt: 2); } [Fact] public void CharacterIndexResetsToZeroAndLineIndexIncrementsWhenSlashNInSingleCharacterNewlineIsRead() { RunSourceLocationTest("f\nb", new SourceLocation(2, 1, 0), checkAt: 2); } [Fact] public void EndingLookaheadResetsRawCharacterAndLineIndexToValuesWhenLookaheadBegan() { RunEndLookaheadUpdatesSourceLocationTest(); } [Fact] public void OnceBufferingBeginsReadsCanContinuePastEndOfBuffer() { RunLookaheadTest("abcdefg", "abcbcdefg", Read, Lookahead(Read(2)), Read(2), ReadToEnd); } [Fact] public void DisposeDisposesSourceReader() { RunDisposeTest(r => r.Dispose()); } [Fact] public void CloseDisposesSourceReader() { RunDisposeTest(r => r.Close()); } [Fact] public void ReadWithBufferSupportsLookahead() { RunBufferReadTest((reader, buffer, index, count) => reader.Read(buffer, index, count)); } [Fact] public void ReadBlockSupportsLookahead() { RunBufferReadTest((reader, buffer, index, count) => reader.ReadBlock(buffer, index, count)); } [Fact] public void ReadLineSupportsLookahead() { RunReadUntilTest(r => r.ReadLine(), expectedRaw: 8, expectedChar: 0, expectedLine: 2); } [Fact] public void ReadToEndSupportsLookahead() { RunReadUntilTest(r => r.ReadToEnd(), expectedRaw: 11, expectedChar: 3, expectedLine: 2); } [Fact] public void ReadLineMaintainsCorrectCharacterPosition() { RunSourceLocationTest("abc\r\ndef", new SourceLocation(5, 1, 0), r => r.ReadLine()); } [Fact] public void ReadToEndWorksAsInNormalTextReader() { RunReadToEndTest(); } [Fact] public void CancelBacktrackStopsNextEndLookaheadFromBacktracking() { RunLookaheadTest("abcdefg", "abcdefg", Lookahead( Read(2), CancelBacktrack ), ReadToEnd); } [Fact] public void CancelBacktrackThrowsInvalidOperationExceptionIfCalledOutsideOfLookahead() { RunCancelBacktrackOutsideLookaheadTest(); } [Fact] public void CancelBacktrackOnlyCancelsBacktrackingForInnermostNestedLookahead() { RunLookaheadTest("abcdefg", "abcdabcdefg", Lookahead( Read(2), Lookahead( Read, CancelBacktrack ), Read ), ReadToEnd); } private static void RunDisposeTest(Action<LookaheadTextReader> triggerAction) { // Arrange StringTextBuffer source = new StringTextBuffer("abcdefg"); LookaheadTextReader reader = new TextBufferReader(source); // Act triggerAction(reader); // Assert Assert.True(source.Disposed); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using NetGore.IO; using NUnit.Framework; namespace NetGore.Tests.IO { [TestFixture] public class ObjectStatePersisterTests { static readonly SafeRandom r = new SafeRandom(); static string CreateRandomString() { var length = r.Next(2, 10); var ret = new char[length]; for (var i = 0; i < ret.Length; i++) { int j; if (i == 0) j = r.Next(1, 3); // Don't let the first character be numeric else j = r.Next(0, 3); int min; int max; // ReSharper disable RedundantCast switch (j) { case 0: min = (int)'0'; max = (int)'9'; break; case 1: min = (int)'a'; max = (int)'z'; break; default: min = (int)'A'; max = (int)'Z'; break; } // ReSharper restore RedundantCast ret[i] = (char)r.Next(min, max + 1); } return new string(ret); } static InterfaceTester GetRandomInterfaceTester() { return new InterfaceTester { A = CreateRandomString(), B = r.Next(int.MinValue, int.MaxValue), C = (r.Next(-1000, 1000)) }; } #region Unit tests [Test] public void AddNewItemTest() { var t1 = new InterfaceTester { A = "Hello", B = 10, C = 5.135f }; var t2 = new InterfaceTester { A = "Goodbye", B = 44, C = 1897.01f }; var t3 = new InterfaceTester { A = "wb", B = 24, C = 1234.3f }; var retT1 = new InterfaceTester(); var retT2 = new InterfaceTester(); InterfaceTester retT3; var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { settingsWriter.Add("t1", t1); settingsWriter.Add("t2", t2); } using (var settingsReader = new ObjectStatePersister("TestSettings", filePath)) { settingsReader.Add("t3", t3); settingsReader.Add("t1", retT1); settingsReader.Add("t2", retT2); retT3 = t3; } } finally { if (File.Exists(filePath)) File.Delete(filePath); } Assert.IsTrue(t1.HaveSameValues(retT1)); Assert.IsTrue(t2.HaveSameValues(retT2)); Assert.IsTrue(t3.HaveSameValues(retT3)); } [Test] public void CaseInsensitiveLowerTest() { var t1 = new InterfaceTester { A = "Hello", B = 10, C = 5.135f }; var t2 = new InterfaceTester { A = "Goodbye", B = 44, C = 1897.01f }; var t3 = new InterfaceTester { A = "wb", B = 24, C = 1234.3f }; var retT1 = new InterfaceTester(); var retT2 = new InterfaceTester(); var retT3 = new InterfaceTester(); var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { settingsWriter.Add("T2", t2); settingsWriter.Add("T3", t3); settingsWriter.Add("T1", t1); } using (var settingsReader = new ObjectStatePersister("TestSettings", filePath)) { settingsReader.Add("t3", retT3); settingsReader.Add("t1", retT1); settingsReader.Add("t2", retT2); } } finally { if (File.Exists(filePath)) File.Delete(filePath); } Assert.IsTrue(t1.HaveSameValues(retT1)); Assert.IsTrue(t2.HaveSameValues(retT2)); Assert.IsTrue(t3.HaveSameValues(retT3)); } [Test] public void CaseInsensitiveUpperTest() { var t1 = new InterfaceTester { A = "Hello", B = 10, C = 5.135f }; var t2 = new InterfaceTester { A = "Goodbye", B = 44, C = 1897.01f }; var t3 = new InterfaceTester { A = "wb", B = 24, C = 1234.3f }; var retT1 = new InterfaceTester(); var retT2 = new InterfaceTester(); var retT3 = new InterfaceTester(); var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { settingsWriter.Add("t2", t2); settingsWriter.Add("t3", t3); settingsWriter.Add("t1", t1); } using (var settingsReader = new ObjectStatePersister("TestSettings", filePath)) { settingsReader.Add("T3", retT3); settingsReader.Add("T1", retT1); settingsReader.Add("T2", retT2); } } finally { if (File.Exists(filePath)) File.Delete(filePath); } Assert.IsTrue(t1.HaveSameValues(retT1)); Assert.IsTrue(t2.HaveSameValues(retT2)); Assert.IsTrue(t3.HaveSameValues(retT3)); } [Test] public void DuplicateKeyTest() { var t1 = new InterfaceTester { A = "Hello", B = 10, C = 5.135f }; var t2 = new InterfaceTester { A = "Goodbye", B = 44, C = 1897.01f }; var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { settingsWriter.Add("t1", t1); Assert.Throws<ArgumentException>(() => settingsWriter.Add("t1", t2)); } } finally { if (File.Exists(filePath)) File.Delete(filePath); } } [Test] public void MissingItemTest() { new InterfaceTester { A = "Hello", B = 10, C = 5.135f }; var t2 = new InterfaceTester { A = "Goodbye", B = 44, C = 1897.01f }; var t3 = new InterfaceTester { A = "wb", B = 24, C = 1234.3f }; var retT1 = new InterfaceTester(); var retT2 = new InterfaceTester(); var retT3 = new InterfaceTester(); var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { settingsWriter.Add("t2", t2); settingsWriter.Add("t3", t3); } using (var settingsReader = new ObjectStatePersister("TestSettings", filePath)) { settingsReader.Add("t3", retT3); settingsReader.Add("t1", retT1); settingsReader.Add("t2", retT2); } } finally { if (File.Exists(filePath)) File.Delete(filePath); } Assert.IsTrue(t2.HaveSameValues(retT2)); Assert.IsTrue(t3.HaveSameValues(retT3)); } [Test] public void ReadWriteTonsOfCrapTest() { const int iterations = 10000; var items = new List<InterfaceTester>(iterations); for (var i = 0; i < iterations; i++) { items.Add(GetRandomInterfaceTester()); } var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { for (var i = 0; i < items.Count; i++) { settingsWriter.Add("item" + Parser.Invariant.ToString(i), items[i]); } } using (var settingsReader = new ObjectStatePersister("TestSettings", filePath)) { for (var i = 0; i < items.Count; i++) { var newItem = new InterfaceTester(); settingsReader.Add("item" + Parser.Invariant.ToString(i), newItem); Assert.IsTrue(items[i].HaveSameValues(newItem), "Index: {0}", i); } } } finally { if (File.Exists(filePath)) File.Delete(filePath); } } [Test] public void VariableLoadOrderTest() { var t1 = new InterfaceTester { A = "Hello", B = 10, C = 5.135f }; var t2 = new InterfaceTester { A = "Goodbye", B = 44, C = 1897.01f }; var t3 = new InterfaceTester { A = "wb", B = 24, C = 1234.3f }; var retT1 = new InterfaceTester(); var retT2 = new InterfaceTester(); var retT3 = new InterfaceTester(); var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { settingsWriter.Add("t1", t1); settingsWriter.Add("t2", t2); settingsWriter.Add("t3", t3); } using (var settingsReader = new ObjectStatePersister("TestSettings", filePath)) { settingsReader.Add("t3", retT3); settingsReader.Add("t1", retT1); settingsReader.Add("t2", retT2); } } finally { if (File.Exists(filePath)) File.Delete(filePath); } Assert.IsTrue(t1.HaveSameValues(retT1)); Assert.IsTrue(t2.HaveSameValues(retT2)); Assert.IsTrue(t3.HaveSameValues(retT3)); } [Test] public void VariableSaveOrderTest() { var t1 = new InterfaceTester { A = "Hello", B = 10, C = 5.135f }; var t2 = new InterfaceTester { A = "Goodbye", B = 44, C = 1897.01f }; var t3 = new InterfaceTester { A = "wb", B = 24, C = 1234.3f }; var retT1 = new InterfaceTester(); var retT2 = new InterfaceTester(); var retT3 = new InterfaceTester(); var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { settingsWriter.Add("t2", t2); settingsWriter.Add("t3", t3); settingsWriter.Add("t1", t1); } using (var settingsReader = new ObjectStatePersister("TestSettings", filePath)) { settingsReader.Add("t3", retT3); settingsReader.Add("t1", retT1); settingsReader.Add("t2", retT2); } } finally { if (File.Exists(filePath)) File.Delete(filePath); } Assert.IsTrue(t1.HaveSameValues(retT1)); Assert.IsTrue(t2.HaveSameValues(retT2)); Assert.IsTrue(t3.HaveSameValues(retT3)); } [Test] public void WriteReadTest() { var t1 = new InterfaceTester { A = "Hello", B = 10, C = 5.135f }; var t2 = new InterfaceTester { A = "Goodbye", B = 44, C = 1897.01f }; var retT1 = new InterfaceTester(); var retT2 = new InterfaceTester(); var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { settingsWriter.Add("t1", t1); settingsWriter.Add("t2", t2); } using (var settingsReader = new ObjectStatePersister("TestSettings", filePath)) { settingsReader.Add("t1", retT1); settingsReader.Add("t2", retT2); } } finally { if (File.Exists(filePath)) File.Delete(filePath); } Assert.IsTrue(t1.HaveSameValues(retT1)); Assert.IsTrue(t2.HaveSameValues(retT2)); } [Test] public void WriteTonsOfCrapReadOnlySomeTest() { const int iterations = 10000; var items = new List<InterfaceTester>(iterations); for (var i = 0; i < iterations; i++) { items.Add(GetRandomInterfaceTester()); } var filePath = Path.GetTempFileName(); try { using (var settingsWriter = new ObjectStatePersister("TestSettings", filePath)) { for (var i = 0; i < items.Count; i++) { settingsWriter.Add("item" + Parser.Invariant.ToString(i), items[i]); } } using (var settingsReader = new ObjectStatePersister("TestSettings", filePath)) { for (var i = items.Count - 1; i > 0; i -= 22) { var newItem = new InterfaceTester(); settingsReader.Add("item" + Parser.Invariant.ToString(i), newItem); Assert.IsTrue(items[i].HaveSameValues(newItem), "Index: {0}", i); } } } finally { if (File.Exists(filePath)) File.Delete(filePath); } } #endregion class InterfaceTester : IPersistable { [SyncValue] public string A { get; set; } [SyncValue] public int B { get; set; } [SyncValue] public float C { get; set; } public bool HaveSameValues(InterfaceTester other) { return HaveSameValues(this, other); } static bool HaveSameValues(InterfaceTester l, InterfaceTester r) { return (l.A == r.A) && (l.B == r.B) && (l.C == r.C); } #region IPersistable Members /// <summary> /// Reads the state of the object from an <see cref="IValueReader"/>. Values should be read in the exact /// same order as they were written. /// </summary> /// <param name="reader">The <see cref="IValueReader"/> to read the values from.</param> public void ReadState(IValueReader reader) { PersistableHelper.Read(this, reader); } /// <summary> /// Writes the state of the object to an <see cref="IValueWriter"/>. /// </summary> /// <param name="writer">The <see cref="IValueWriter"/> to write the values to.</param> public void WriteState(IValueWriter writer) { PersistableHelper.Write(this, writer); } #endregion } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Security; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System.Runtime.Serialization { /// <SecurityNote> /// Critical - Class holds static instances used for code generation during serialization. /// Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// Safe - All get-only properties marked safe since they only need to be protected for write. /// </SecurityNote> internal static class XmlFormatGeneratorStatics { [SecurityCritical] private static MethodInfo s_writeStartElementMethod2; internal static MethodInfo WriteStartElementMethod2 { [SecuritySafeCritical] get { if (s_writeStartElementMethod2 == null) { s_writeStartElementMethod2 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); Debug.Assert(s_writeStartElementMethod2 != null); } return s_writeStartElementMethod2; } } [SecurityCritical] private static MethodInfo s_writeStartElementMethod3; internal static MethodInfo WriteStartElementMethod3 { [SecuritySafeCritical] get { if (s_writeStartElementMethod3 == null) { s_writeStartElementMethod3 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, new Type[] { typeof(string), typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); Debug.Assert(s_writeStartElementMethod3 != null); } return s_writeStartElementMethod3; } } [SecurityCritical] private static MethodInfo s_writeEndElementMethod; internal static MethodInfo WriteEndElementMethod { [SecuritySafeCritical] get { if (s_writeEndElementMethod == null) { s_writeEndElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteEndElement", Globals.ScanAllMembers, Array.Empty<Type>()); Debug.Assert(s_writeEndElementMethod != null); } return s_writeEndElementMethod; } } [SecurityCritical] private static MethodInfo s_writeNamespaceDeclMethod; internal static MethodInfo WriteNamespaceDeclMethod { [SecuritySafeCritical] get { if (s_writeNamespaceDeclMethod == null) { s_writeNamespaceDeclMethod = typeof(XmlWriterDelegator).GetMethod("WriteNamespaceDecl", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString) }); Debug.Assert(s_writeNamespaceDeclMethod != null); } return s_writeNamespaceDeclMethod; } } [SecurityCritical] private static ConstructorInfo s_dictionaryEnumeratorCtor; internal static ConstructorInfo DictionaryEnumeratorCtor { [SecuritySafeCritical] get { if (s_dictionaryEnumeratorCtor == null) s_dictionaryEnumeratorCtor = Globals.TypeOfDictionaryEnumerator.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator }); return s_dictionaryEnumeratorCtor; } } [SecurityCritical] private static MethodInfo s_ienumeratorMoveNextMethod; internal static MethodInfo MoveNextMethod { [SecuritySafeCritical] get { if (s_ienumeratorMoveNextMethod == null) { s_ienumeratorMoveNextMethod = typeof(IEnumerator).GetMethod("MoveNext"); Debug.Assert(s_ienumeratorMoveNextMethod != null); } return s_ienumeratorMoveNextMethod; } } [SecurityCritical] private static MethodInfo s_ienumeratorGetCurrentMethod; internal static MethodInfo GetCurrentMethod { [SecuritySafeCritical] get { if (s_ienumeratorGetCurrentMethod == null) { s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetMethod; Debug.Assert(s_ienumeratorGetCurrentMethod != null); } return s_ienumeratorGetCurrentMethod; } } [SecurityCritical] private static MethodInfo s_getItemContractMethod; internal static MethodInfo GetItemContractMethod { [SecuritySafeCritical] get { if (s_getItemContractMethod == null) { s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers).GetMethod; Debug.Assert(s_getItemContractMethod != null); } return s_getItemContractMethod; } } [SecurityCritical] private static MethodInfo s_isStartElementMethod2; internal static MethodInfo IsStartElementMethod2 { [SecuritySafeCritical] get { if (s_isStartElementMethod2 == null) { s_isStartElementMethod2 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); Debug.Assert(s_isStartElementMethod2 != null); } return s_isStartElementMethod2; } } [SecurityCritical] private static MethodInfo s_isStartElementMethod0; internal static MethodInfo IsStartElementMethod0 { [SecuritySafeCritical] get { if (s_isStartElementMethod0 == null) { s_isStartElementMethod0 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, Array.Empty<Type>()); Debug.Assert(s_isStartElementMethod0 != null); } return s_isStartElementMethod0; } } [SecurityCritical] private static MethodInfo s_getUninitializedObjectMethod; internal static MethodInfo GetUninitializedObjectMethod { [SecuritySafeCritical] get { if (s_getUninitializedObjectMethod == null) { s_getUninitializedObjectMethod = typeof(XmlFormatReaderGenerator).GetMethod("UnsafeGetUninitializedObject", Globals.ScanAllMembers, new Type[] { typeof(int) }); Debug.Assert(s_getUninitializedObjectMethod != null); } return s_getUninitializedObjectMethod; } } [SecurityCritical] private static PropertyInfo s_nodeTypeProperty; internal static PropertyInfo NodeTypeProperty { [SecuritySafeCritical] get { if (s_nodeTypeProperty == null) { s_nodeTypeProperty = typeof(XmlReaderDelegator).GetProperty("NodeType", Globals.ScanAllMembers); Debug.Assert(s_nodeTypeProperty != null); } return s_nodeTypeProperty; } } [SecurityCritical] private static ConstructorInfo s_hashtableCtor; internal static ConstructorInfo HashtableCtor { [SecuritySafeCritical] get { if (s_hashtableCtor == null) s_hashtableCtor = Globals.TypeOfHashtable.GetConstructor(Globals.ScanAllMembers, Array.Empty<Type>()); return s_hashtableCtor; } } [SecurityCritical] private static MethodInfo s_getStreamingContextMethod; internal static MethodInfo GetStreamingContextMethod { [SecuritySafeCritical] get { if (s_getStreamingContextMethod == null) { s_getStreamingContextMethod = typeof(XmlObjectSerializerContext).GetMethod("GetStreamingContext", Globals.ScanAllMembers); Debug.Assert(s_getStreamingContextMethod != null); } return s_getStreamingContextMethod; } } [SecurityCritical] private static MethodInfo s_getCollectionMemberMethod; internal static MethodInfo GetCollectionMemberMethod { [SecuritySafeCritical] get { if (s_getCollectionMemberMethod == null) { s_getCollectionMemberMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetCollectionMember", Globals.ScanAllMembers); Debug.Assert(s_getCollectionMemberMethod != null); } return s_getCollectionMemberMethod; } } [SecurityCritical] private static MethodInfo s_storeCollectionMemberInfoMethod; internal static MethodInfo StoreCollectionMemberInfoMethod { [SecuritySafeCritical] get { if (s_storeCollectionMemberInfoMethod == null) { s_storeCollectionMemberInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("StoreCollectionMemberInfo", Globals.ScanAllMembers, new Type[] { typeof(object) }); Debug.Assert(s_storeCollectionMemberInfoMethod != null); } return s_storeCollectionMemberInfoMethod; } } [SecurityCritical] private static MethodInfo s_storeIsGetOnlyCollectionMethod; internal static MethodInfo StoreIsGetOnlyCollectionMethod { [SecuritySafeCritical] get { if (s_storeIsGetOnlyCollectionMethod == null) { s_storeIsGetOnlyCollectionMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("StoreIsGetOnlyCollection", Globals.ScanAllMembers); Debug.Assert(s_storeIsGetOnlyCollectionMethod != null); } return s_storeIsGetOnlyCollectionMethod; } } [SecurityCritical] private static MethodInfo s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod; internal static MethodInfo ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod { [SecuritySafeCritical] get { if (s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod == null) { s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowNullValueReturnedForGetOnlyCollectionException", Globals.ScanAllMembers); Debug.Assert(s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod != null); } return s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod; } } private static MethodInfo s_throwArrayExceededSizeExceptionMethod; internal static MethodInfo ThrowArrayExceededSizeExceptionMethod { [SecuritySafeCritical] get { if (s_throwArrayExceededSizeExceptionMethod == null) { s_throwArrayExceededSizeExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowArrayExceededSizeException", Globals.ScanAllMembers); Debug.Assert(s_throwArrayExceededSizeExceptionMethod != null); } return s_throwArrayExceededSizeExceptionMethod; } } [SecurityCritical] private static MethodInfo s_incrementItemCountMethod; internal static MethodInfo IncrementItemCountMethod { [SecuritySafeCritical] get { if (s_incrementItemCountMethod == null) { s_incrementItemCountMethod = typeof(XmlObjectSerializerContext).GetMethod("IncrementItemCount", Globals.ScanAllMembers); Debug.Assert(s_incrementItemCountMethod != null); } return s_incrementItemCountMethod; } } [SecurityCritical] private static MethodInfo s_internalDeserializeMethod; internal static MethodInfo InternalDeserializeMethod { [SecuritySafeCritical] get { if (s_internalDeserializeMethod == null) { s_internalDeserializeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("InternalDeserialize", Globals.ScanAllMembers, new Type[] { typeof(XmlReaderDelegator), typeof(int), typeof(RuntimeTypeHandle), typeof(string), typeof(string) }); Debug.Assert(s_internalDeserializeMethod != null); } return s_internalDeserializeMethod; } } [SecurityCritical] private static MethodInfo s_moveToNextElementMethod; internal static MethodInfo MoveToNextElementMethod { [SecuritySafeCritical] get { if (s_moveToNextElementMethod == null) { s_moveToNextElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("MoveToNextElement", Globals.ScanAllMembers); Debug.Assert(s_moveToNextElementMethod != null); } return s_moveToNextElementMethod; } } [SecurityCritical] private static MethodInfo s_getMemberIndexMethod; internal static MethodInfo GetMemberIndexMethod { [SecuritySafeCritical] get { if (s_getMemberIndexMethod == null) { s_getMemberIndexMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndex", Globals.ScanAllMembers); Debug.Assert(s_getMemberIndexMethod != null); } return s_getMemberIndexMethod; } } [SecurityCritical] private static MethodInfo s_getMemberIndexWithRequiredMembersMethod; internal static MethodInfo GetMemberIndexWithRequiredMembersMethod { [SecuritySafeCritical] get { if (s_getMemberIndexWithRequiredMembersMethod == null) { s_getMemberIndexWithRequiredMembersMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndexWithRequiredMembers", Globals.ScanAllMembers); Debug.Assert(s_getMemberIndexWithRequiredMembersMethod != null); } return s_getMemberIndexWithRequiredMembersMethod; } } [SecurityCritical] private static MethodInfo s_throwRequiredMemberMissingExceptionMethod; internal static MethodInfo ThrowRequiredMemberMissingExceptionMethod { [SecuritySafeCritical] get { if (s_throwRequiredMemberMissingExceptionMethod == null) { s_throwRequiredMemberMissingExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowRequiredMemberMissingException", Globals.ScanAllMembers); Debug.Assert(s_throwRequiredMemberMissingExceptionMethod != null); } return s_throwRequiredMemberMissingExceptionMethod; } } [SecurityCritical] private static MethodInfo s_skipUnknownElementMethod; internal static MethodInfo SkipUnknownElementMethod { [SecuritySafeCritical] get { if (s_skipUnknownElementMethod == null) { s_skipUnknownElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("SkipUnknownElement", Globals.ScanAllMembers); Debug.Assert(s_skipUnknownElementMethod != null); } return s_skipUnknownElementMethod; } } [SecurityCritical] private static MethodInfo s_readIfNullOrRefMethod; internal static MethodInfo ReadIfNullOrRefMethod { [SecuritySafeCritical] get { if (s_readIfNullOrRefMethod == null) { s_readIfNullOrRefMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadIfNullOrRef", Globals.ScanAllMembers, new Type[] { typeof(XmlReaderDelegator), typeof(Type), typeof(bool) }); Debug.Assert(s_readIfNullOrRefMethod != null); } return s_readIfNullOrRefMethod; } } [SecurityCritical] private static MethodInfo s_readAttributesMethod; internal static MethodInfo ReadAttributesMethod { [SecuritySafeCritical] get { if (s_readAttributesMethod == null) { s_readAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadAttributes", Globals.ScanAllMembers); Debug.Assert(s_readAttributesMethod != null); } return s_readAttributesMethod; } } [SecurityCritical] private static MethodInfo s_resetAttributesMethod; internal static MethodInfo ResetAttributesMethod { [SecuritySafeCritical] get { if (s_resetAttributesMethod == null) { s_resetAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ResetAttributes", Globals.ScanAllMembers); Debug.Assert(s_resetAttributesMethod != null); } return s_resetAttributesMethod; } } [SecurityCritical] private static MethodInfo s_getObjectIdMethod; internal static MethodInfo GetObjectIdMethod { [SecuritySafeCritical] get { if (s_getObjectIdMethod == null) { s_getObjectIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetObjectId", Globals.ScanAllMembers); Debug.Assert(s_getObjectIdMethod != null); } return s_getObjectIdMethod; } } [SecurityCritical] private static MethodInfo s_getArraySizeMethod; internal static MethodInfo GetArraySizeMethod { [SecuritySafeCritical] get { if (s_getArraySizeMethod == null) { s_getArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetArraySize", Globals.ScanAllMembers); Debug.Assert(s_getArraySizeMethod != null); } return s_getArraySizeMethod; } } [SecurityCritical] private static MethodInfo s_addNewObjectMethod; internal static MethodInfo AddNewObjectMethod { [SecuritySafeCritical] get { if (s_addNewObjectMethod == null) { s_addNewObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObject", Globals.ScanAllMembers); Debug.Assert(s_addNewObjectMethod != null); } return s_addNewObjectMethod; } } [SecurityCritical] private static MethodInfo s_addNewObjectWithIdMethod; internal static MethodInfo AddNewObjectWithIdMethod { [SecuritySafeCritical] get { if (s_addNewObjectWithIdMethod == null) { s_addNewObjectWithIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObjectWithId", Globals.ScanAllMembers); Debug.Assert(s_addNewObjectWithIdMethod != null); } return s_addNewObjectWithIdMethod; } } [SecurityCritical] private static MethodInfo s_getExistingObjectMethod; internal static MethodInfo GetExistingObjectMethod { [SecuritySafeCritical] get { if (s_getExistingObjectMethod == null) { s_getExistingObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetExistingObject", Globals.ScanAllMembers); Debug.Assert(s_getExistingObjectMethod != null); } return s_getExistingObjectMethod; } } [SecurityCritical] private static MethodInfo s_ensureArraySizeMethod; internal static MethodInfo EnsureArraySizeMethod { [SecuritySafeCritical] get { if (s_ensureArraySizeMethod == null) { s_ensureArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("EnsureArraySize", Globals.ScanAllMembers); Debug.Assert(s_ensureArraySizeMethod != null); } return s_ensureArraySizeMethod; } } [SecurityCritical] private static MethodInfo s_trimArraySizeMethod; internal static MethodInfo TrimArraySizeMethod { [SecuritySafeCritical] get { if (s_trimArraySizeMethod == null) { s_trimArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("TrimArraySize", Globals.ScanAllMembers); Debug.Assert(s_trimArraySizeMethod != null); } return s_trimArraySizeMethod; } } [SecurityCritical] private static MethodInfo s_checkEndOfArrayMethod; internal static MethodInfo CheckEndOfArrayMethod { [SecuritySafeCritical] get { if (s_checkEndOfArrayMethod == null) { s_checkEndOfArrayMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CheckEndOfArray", Globals.ScanAllMembers); Debug.Assert(s_checkEndOfArrayMethod != null); } return s_checkEndOfArrayMethod; } } [SecurityCritical] private static MethodInfo s_getArrayLengthMethod; internal static MethodInfo GetArrayLengthMethod { [SecuritySafeCritical] get { if (s_getArrayLengthMethod == null) { s_getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length").GetMethod; Debug.Assert(s_getArrayLengthMethod != null); } return s_getArrayLengthMethod; } } [SecurityCritical] private static MethodInfo s_createSerializationExceptionMethod; internal static MethodInfo CreateSerializationExceptionMethod { [SecuritySafeCritical] get { if (s_createSerializationExceptionMethod == null) { s_createSerializationExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateSerializationException", Globals.ScanAllMembers, new Type[] { typeof(string) }); Debug.Assert(s_createSerializationExceptionMethod != null); } return s_createSerializationExceptionMethod; } } [SecurityCritical] private static MethodInfo s_createUnexpectedStateExceptionMethod; internal static MethodInfo CreateUnexpectedStateExceptionMethod { [SecuritySafeCritical] get { if (s_createUnexpectedStateExceptionMethod == null) { s_createUnexpectedStateExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateUnexpectedStateException", Globals.ScanAllMembers, new Type[] { typeof(XmlNodeType), typeof(XmlReaderDelegator) }); Debug.Assert(s_createUnexpectedStateExceptionMethod != null); } return s_createUnexpectedStateExceptionMethod; } } [SecurityCritical] private static MethodInfo s_internalSerializeReferenceMethod; internal static MethodInfo InternalSerializeReferenceMethod { [SecuritySafeCritical] get { if (s_internalSerializeReferenceMethod == null) { s_internalSerializeReferenceMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerializeReference", Globals.ScanAllMembers); Debug.Assert(s_internalSerializeReferenceMethod != null); } return s_internalSerializeReferenceMethod; } } [SecurityCritical] private static MethodInfo s_internalSerializeMethod; internal static MethodInfo InternalSerializeMethod { [SecuritySafeCritical] get { if (s_internalSerializeMethod == null) { s_internalSerializeMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerialize", Globals.ScanAllMembers); Debug.Assert(s_internalSerializeMethod != null); } return s_internalSerializeMethod; } } [SecurityCritical] private static MethodInfo s_writeNullMethod; internal static MethodInfo WriteNullMethod { [SecuritySafeCritical] get { if (s_writeNullMethod == null) { s_writeNullMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteNull", Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), typeof(Type), typeof(bool) }); Debug.Assert(s_writeNullMethod != null); } return s_writeNullMethod; } } [SecurityCritical] private static MethodInfo s_incrementArrayCountMethod; internal static MethodInfo IncrementArrayCountMethod { [SecuritySafeCritical] get { if (s_incrementArrayCountMethod == null) { s_incrementArrayCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementArrayCount", Globals.ScanAllMembers); Debug.Assert(s_incrementArrayCountMethod != null); } return s_incrementArrayCountMethod; } } [SecurityCritical] private static MethodInfo s_incrementCollectionCountMethod; internal static MethodInfo IncrementCollectionCountMethod { [SecuritySafeCritical] get { if (s_incrementCollectionCountMethod == null) { s_incrementCollectionCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCount", Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), typeof(ICollection) }); Debug.Assert(s_incrementCollectionCountMethod != null); } return s_incrementCollectionCountMethod; } } [SecurityCritical] private static MethodInfo s_incrementCollectionCountGenericMethod; internal static MethodInfo IncrementCollectionCountGenericMethod { [SecuritySafeCritical] get { if (s_incrementCollectionCountGenericMethod == null) { s_incrementCollectionCountGenericMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCountGeneric", Globals.ScanAllMembers); Debug.Assert(s_incrementCollectionCountGenericMethod != null); } return s_incrementCollectionCountGenericMethod; } } [SecurityCritical] private static MethodInfo s_getDefaultValueMethod; internal static MethodInfo GetDefaultValueMethod { [SecuritySafeCritical] get { if (s_getDefaultValueMethod == null) { s_getDefaultValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(nameof(XmlObjectSerializerWriteContext.GetDefaultValue), Globals.ScanAllMembers); Debug.Assert(s_getDefaultValueMethod != null); } return s_getDefaultValueMethod; } } internal static object GetDefaultValue(Type type) { return GetDefaultValueMethod.MakeGenericMethod(type).Invoke(null, Array.Empty<object>()); } [SecurityCritical] private static MethodInfo s_getNullableValueMethod; internal static MethodInfo GetNullableValueMethod { [SecuritySafeCritical] get { if (s_getNullableValueMethod == null) { s_getNullableValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetNullableValue", Globals.ScanAllMembers); Debug.Assert(s_getNullableValueMethod != null); } return s_getNullableValueMethod; } } [SecurityCritical] private static MethodInfo s_throwRequiredMemberMustBeEmittedMethod; internal static MethodInfo ThrowRequiredMemberMustBeEmittedMethod { [SecuritySafeCritical] get { if (s_throwRequiredMemberMustBeEmittedMethod == null) { s_throwRequiredMemberMustBeEmittedMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("ThrowRequiredMemberMustBeEmitted", Globals.ScanAllMembers); Debug.Assert(s_throwRequiredMemberMustBeEmittedMethod != null); } return s_throwRequiredMemberMustBeEmittedMethod; } } [SecurityCritical] private static MethodInfo s_getHasValueMethod; internal static MethodInfo GetHasValueMethod { [SecuritySafeCritical] get { if (s_getHasValueMethod == null) { s_getHasValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetHasValue", Globals.ScanAllMembers); Debug.Assert(s_getHasValueMethod != null); } return s_getHasValueMethod; } } [SecurityCritical] private static MethodInfo s_isMemberTypeSameAsMemberValue; internal static MethodInfo IsMemberTypeSameAsMemberValue { [SecuritySafeCritical] get { if (s_isMemberTypeSameAsMemberValue == null) { s_isMemberTypeSameAsMemberValue = typeof(XmlObjectSerializerWriteContext).GetMethod("IsMemberTypeSameAsMemberValue", Globals.ScanAllMembers, new Type[] { typeof(object), typeof(Type) }); Debug.Assert(s_isMemberTypeSameAsMemberValue != null); } return s_isMemberTypeSameAsMemberValue; } } [SecurityCritical] private static MethodInfo s_writeXmlValueMethod; internal static MethodInfo WriteXmlValueMethod { [SecuritySafeCritical] get { if (s_writeXmlValueMethod == null) { s_writeXmlValueMethod = typeof(DataContract).GetMethod("WriteXmlValue", Globals.ScanAllMembers); Debug.Assert(s_writeXmlValueMethod != null); } return s_writeXmlValueMethod; } } [SecurityCritical] private static MethodInfo s_readXmlValueMethod; internal static MethodInfo ReadXmlValueMethod { [SecuritySafeCritical] get { if (s_readXmlValueMethod == null) { s_readXmlValueMethod = typeof(DataContract).GetMethod("ReadXmlValue", Globals.ScanAllMembers); Debug.Assert(s_readXmlValueMethod != null); } return s_readXmlValueMethod; } } [SecurityCritical] private static PropertyInfo s_namespaceProperty; internal static PropertyInfo NamespaceProperty { [SecuritySafeCritical] get { if (s_namespaceProperty == null) { s_namespaceProperty = typeof(DataContract).GetProperty("Namespace", Globals.ScanAllMembers); Debug.Assert(s_namespaceProperty != null); } return s_namespaceProperty; } } [SecurityCritical] private static FieldInfo s_contractNamespacesField; internal static FieldInfo ContractNamespacesField { [SecuritySafeCritical] get { if (s_contractNamespacesField == null) { s_contractNamespacesField = typeof(ClassDataContract).GetField("ContractNamespaces", Globals.ScanAllMembers); Debug.Assert(s_contractNamespacesField != null); } return s_contractNamespacesField; } } [SecurityCritical] private static FieldInfo s_memberNamesField; internal static FieldInfo MemberNamesField { [SecuritySafeCritical] get { if (s_memberNamesField == null) { s_memberNamesField = typeof(ClassDataContract).GetField("MemberNames", Globals.ScanAllMembers); Debug.Assert(s_memberNamesField != null); } return s_memberNamesField; } } [SecurityCritical] private static PropertyInfo s_childElementNamespacesProperty; internal static PropertyInfo ChildElementNamespacesProperty { [SecuritySafeCritical] get { if (s_childElementNamespacesProperty == null) { s_childElementNamespacesProperty = typeof(ClassDataContract).GetProperty("ChildElementNamespaces", Globals.ScanAllMembers); Debug.Assert(s_childElementNamespacesProperty != null); } return s_childElementNamespacesProperty; } } [SecurityCritical] private static PropertyInfo s_collectionItemNameProperty; internal static PropertyInfo CollectionItemNameProperty { [SecuritySafeCritical] get { if (s_collectionItemNameProperty == null) { s_collectionItemNameProperty = typeof(CollectionDataContract).GetProperty("CollectionItemName", Globals.ScanAllMembers); Debug.Assert(s_collectionItemNameProperty != null); } return s_collectionItemNameProperty; } } [SecurityCritical] private static PropertyInfo s_childElementNamespaceProperty; internal static PropertyInfo ChildElementNamespaceProperty { [SecuritySafeCritical] get { if (s_childElementNamespaceProperty == null) { s_childElementNamespaceProperty = typeof(CollectionDataContract).GetProperty("ChildElementNamespace", Globals.ScanAllMembers); Debug.Assert(s_childElementNamespaceProperty != null); } return s_childElementNamespaceProperty; } } [SecurityCritical] private static MethodInfo s_getDateTimeOffsetMethod; internal static MethodInfo GetDateTimeOffsetMethod { [SecuritySafeCritical] get { if (s_getDateTimeOffsetMethod == null) { s_getDateTimeOffsetMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffset", Globals.ScanAllMembers); Debug.Assert(s_getDateTimeOffsetMethod != null); } return s_getDateTimeOffsetMethod; } } [SecurityCritical] private static MethodInfo s_getDateTimeOffsetAdapterMethod; internal static MethodInfo GetDateTimeOffsetAdapterMethod { [SecuritySafeCritical] get { if (s_getDateTimeOffsetAdapterMethod == null) { s_getDateTimeOffsetAdapterMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffsetAdapter", Globals.ScanAllMembers); Debug.Assert(s_getDateTimeOffsetAdapterMethod != null); } return s_getDateTimeOffsetAdapterMethod; } } #if !NET_NATIVE private static MethodInfo s_getTypeHandleMethod; internal static MethodInfo GetTypeHandleMethod { get { if (s_getTypeHandleMethod == null) { s_getTypeHandleMethod = typeof(Type).GetMethod("get_TypeHandle"); Debug.Assert(s_getTypeHandleMethod != null); } return s_getTypeHandleMethod; } } private static MethodInfo s_getTypeMethod; internal static MethodInfo GetTypeMethod { get { if (s_getTypeMethod == null) { s_getTypeMethod = typeof(object).GetMethod("GetType"); Debug.Assert(s_getTypeMethod != null); } return s_getTypeMethod; } } [SecurityCritical] private static MethodInfo s_throwInvalidDataContractExceptionMethod; internal static MethodInfo ThrowInvalidDataContractExceptionMethod { [SecuritySafeCritical] get { if (s_throwInvalidDataContractExceptionMethod == null) { s_throwInvalidDataContractExceptionMethod = typeof(DataContract).GetMethod("ThrowInvalidDataContractException", Globals.ScanAllMembers, new Type[] { typeof(string), typeof(Type) }); Debug.Assert(s_throwInvalidDataContractExceptionMethod != null); } return s_throwInvalidDataContractExceptionMethod; } } [SecurityCritical] private static PropertyInfo s_serializeReadOnlyTypesProperty; internal static PropertyInfo SerializeReadOnlyTypesProperty { [SecuritySafeCritical] get { if (s_serializeReadOnlyTypesProperty == null) { s_serializeReadOnlyTypesProperty = typeof(XmlObjectSerializerWriteContext).GetProperty("SerializeReadOnlyTypes", Globals.ScanAllMembers); Debug.Assert(s_serializeReadOnlyTypesProperty != null); } return s_serializeReadOnlyTypesProperty; } } [SecurityCritical] private static PropertyInfo s_classSerializationExceptionMessageProperty; internal static PropertyInfo ClassSerializationExceptionMessageProperty { [SecuritySafeCritical] get { if (s_classSerializationExceptionMessageProperty == null) { s_classSerializationExceptionMessageProperty = typeof(ClassDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers); Debug.Assert(s_classSerializationExceptionMessageProperty != null); } return s_classSerializationExceptionMessageProperty; } } [SecurityCritical] private static PropertyInfo s_collectionSerializationExceptionMessageProperty; internal static PropertyInfo CollectionSerializationExceptionMessageProperty { [SecuritySafeCritical] get { if (s_collectionSerializationExceptionMessageProperty == null) { s_collectionSerializationExceptionMessageProperty = typeof(CollectionDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers); Debug.Assert(s_collectionSerializationExceptionMessageProperty != null); } return s_collectionSerializationExceptionMessageProperty; } } #endif } }
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; using Xunit.Abstractions; using Tester; using Orleans.Hosting; using Microsoft.Extensions.Options; using Orleans.Configuration; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Orleans.Providers.Streams.AzureQueue; using Tester.AzureUtils.Streaming; namespace UnitTests.StreamingTests { [TestCategory("Streaming"), TestCategory("Cleanup")] public class StreamLifecycleTests : TestClusterPerTest { public const string AzureQueueStreamProviderName = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME; public const string SmsStreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; protected Guid StreamId; protected string StreamProviderName; protected string StreamNamespace; private readonly ITestOutputHelper output; private IActivateDeactivateWatcherGrain watcher; private const int queueCount = 8; protected override void ConfigureTestCluster(TestClusterBuilder builder) { TestUtils.CheckForAzureStorage(); builder.CreateSilo = AppDomainSiloHandle.Create; builder.AddSiloBuilderConfigurator<MySiloBuilderConfigurator>(); builder.AddClientBuilderConfigurator<MyClientBuilderConfigurator>(); } private class MyClientBuilderConfigurator : IClientBuilderConfigurator { public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { clientBuilder .AddSimpleMessageStreamProvider(SmsStreamProviderName) .AddAzureQueueStreams<AzureQueueDataAdapterV2>(AzureQueueStreamProviderName, ob=>ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount); })); } } private class MySiloBuilderConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder .AddSimpleMessageStreamProvider(SmsStreamProviderName) .AddSimpleMessageStreamProvider("SMSProviderDoNotOptimizeForImmutableData", options => options.OptimizeForImmutableData = false) .AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; options.DeleteStateOnClear = true; })) .AddAzureTableGrainStorage("PubSubStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.DeleteStateOnClear = true; options.ConnectionString = TestDefaultConfiguration.DataConnectionString; })) .AddAzureQueueStreams<AzureQueueDataAdapterV2>(AzureQueueStreamProviderName, ob=>ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount); })) .AddAzureQueueStreams<AzureQueueDataAdapterV2>("AzureQueueProvider2", ob=>ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; options.QueueNames = AzureQueueUtilities.GenerateQueueNames($"{dep.Value.ClusterId}2", queueCount); })) .AddMemoryGrainStorage("MemoryStore", options => options.NumStorageGrains = 1); } } public StreamLifecycleTests(ITestOutputHelper output) { this.output = output; this.watcher = this.GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0); StreamId = Guid.NewGuid(); StreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; StreamNamespace = StreamTestsConstants.StreamLifecycleTestsNamespace; } public override void Dispose() { watcher.Clear().WaitWithThrow(TimeSpan.FromSeconds(15)); AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames(this.HostedCluster.Options.ClusterId, queueCount), TestDefaultConfiguration.DataConnectionString).Wait(); AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames($"{this.HostedCluster.Options.ClusterId}2", queueCount), TestDefaultConfiguration.DataConnectionString).Wait(); base.Dispose(); } [SkippableFact, TestCategory("Functional")] public async Task StreamCleanup_Deactivate() { await DoStreamCleanupTest_Deactivate(false, false); } [SkippableFact, TestCategory("Functional")] public async Task StreamCleanup_BadDeactivate() { await DoStreamCleanupTest_Deactivate(true, false); } [SkippableFact, TestCategory("Functional")] public async Task StreamCleanup_UseAfter_Deactivate() { await DoStreamCleanupTest_Deactivate(false, true); } [SkippableFact, TestCategory("Functional")] public async Task StreamCleanup_UseAfter_BadDeactivate() { await DoStreamCleanupTest_Deactivate(true, true); } [SkippableFact, TestCategory("Functional")] public async Task Stream_Lifecycle_AddRemoveProducers() { string testName = "Stream_Lifecycle_AddRemoveProducers"; StreamTestUtils.LogStartTest(testName, StreamId, StreamProviderName, logger, HostedCluster); int numProducers = 10; var consumer = this.GrainFactory.GetGrain<IStreamLifecycleConsumerInternalGrain>(Guid.NewGuid()); await consumer.BecomeConsumer(StreamId, StreamNamespace, StreamProviderName); var producers = new IStreamLifecycleProducerInternalGrain[numProducers]; for (int i = 1; i <= producers.Length; i++) { var producer = this.GrainFactory.GetGrain<IStreamLifecycleProducerInternalGrain>(Guid.NewGuid()); producers[i - 1] = producer; } int expectedReceived = 0; string when = "round 1"; await IncrementalAddProducers(producers, when); expectedReceived += numProducers; Assert.Equal(expectedReceived, await consumer.GetReceivedCount()); for (int i = producers.Length; i > 0; i--) { var producer = producers[i - 1]; // Force Remove await producer.TestInternalRemoveProducer(StreamId, StreamProviderName); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "producer #" + i + " remove", (i - 1), 1, StreamId, StreamProviderName, StreamNamespace); } when = "round 2"; await IncrementalAddProducers(producers, when); expectedReceived += numProducers; Assert.Equal(expectedReceived, await consumer.GetReceivedCount()); List<Task> promises = new List<Task>(); for (int i = producers.Length; i > 0; i--) { var producer = producers[i - 1]; // Remove when Deactivate promises.Add(producer.DoDeactivateNoClose()); } await Task.WhenAll(promises); await WaitForDeactivation(); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "all producers deactivated", 0, 1, StreamId, StreamProviderName, StreamNamespace); when = "round 3"; await IncrementalAddProducers(producers, when); expectedReceived += numProducers; Assert.Equal(expectedReceived, await consumer.GetReceivedCount()); } private async Task IncrementalAddProducers(IStreamLifecycleProducerGrain[] producers, string when) { for (int i = 1; i <= producers.Length; i++) { var producer = producers[i - 1]; await producer.BecomeProducer(StreamId, StreamNamespace, StreamProviderName); // These Producers test grains always send first message when they register await StreamTestUtils.CheckPubSubCounts( this.InternalClient, output, string.Format("producer #{0} create - {1}", i, when), i, 1, StreamId, StreamProviderName, StreamNamespace); } } // ---------- Test support methods ---------- private async Task DoStreamCleanupTest_Deactivate(bool uncleanShutdown, bool useStreamAfterDeactivate, [CallerMemberName]string testName = null) { StreamTestUtils.LogStartTest(testName, StreamId, StreamProviderName, logger, HostedCluster); var producer1 = this.GrainFactory.GetGrain<IStreamLifecycleProducerInternalGrain>(Guid.NewGuid()); var producer2 = this.GrainFactory.GetGrain<IStreamLifecycleProducerInternalGrain>(Guid.NewGuid()); var consumer1 = this.GrainFactory.GetGrain<IStreamLifecycleConsumerInternalGrain>(Guid.NewGuid()); var consumer2 = this.GrainFactory.GetGrain<IStreamLifecycleConsumerInternalGrain>(Guid.NewGuid()); await consumer1.BecomeConsumer(StreamId, StreamNamespace, StreamProviderName); await producer1.BecomeProducer(StreamId, StreamNamespace, StreamProviderName); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after first producer added", 1, 1, StreamId, StreamProviderName, StreamNamespace); Assert.Equal(1, await producer1.GetSendCount()); // "SendCount after first send" var activations = await watcher.GetActivateCalls(); var deactivations = await watcher.GetDeactivateCalls(); Assert.Equal(2, activations.Length); Assert.Empty(deactivations); int expectedNumProducers; if (uncleanShutdown) { expectedNumProducers = 1; // Will not cleanup yet await producer1.DoBadDeactivateNoClose(); } else { expectedNumProducers = 0; // Should immediately cleanup on Deactivate await producer1.DoDeactivateNoClose(); } await WaitForDeactivation(); deactivations = await watcher.GetDeactivateCalls(); Assert.Single(deactivations); // Test grains that did unclean shutdown will not have cleaned up yet, so PubSub counts are unchanged here for them await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after deactivate first producer", expectedNumProducers, 1, StreamId, StreamProviderName, StreamNamespace); // Add another consumer - which forces cleanup of dead producers and PubSub counts should now always be correct await consumer2.BecomeConsumer(StreamId, StreamNamespace, StreamProviderName); // Runtime should have cleaned up after next consumer added await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after add second consumer", 0, 2, StreamId, StreamProviderName, StreamNamespace); if (useStreamAfterDeactivate) { // Add new producer await producer2.BecomeProducer(StreamId, StreamNamespace, StreamProviderName); // These Producer test grains always send first message when they BecomeProducer, so should be registered with PubSub await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after add second producer", 1, 2, StreamId, StreamProviderName, StreamNamespace); Assert.Equal(1, await producer1.GetSendCount()); // "SendCount (Producer#1) after second publisher added"); Assert.Equal(1, await producer2.GetSendCount()); // "SendCount (Producer#2) after second publisher added"); Assert.Equal(2, await consumer1.GetReceivedCount()); // "ReceivedCount (Consumer#1) after second publisher added"); Assert.Equal(1, await consumer2.GetReceivedCount()); // "ReceivedCount (Consumer#2) after second publisher added"); await producer2.SendItem(3); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after second producer send", 1, 2, StreamId, StreamProviderName, StreamNamespace); Assert.Equal(3, await consumer1.GetReceivedCount()); // "ReceivedCount (Consumer#1) after second publisher send"); Assert.Equal(2, await consumer2.GetReceivedCount()); // "ReceivedCount (Consumer#2) after second publisher send"); } StreamTestUtils.LogEndTest(testName, logger); } private async Task WaitForDeactivation() { var delay = TimeSpan.FromSeconds(1); logger.Info("Waiting for {0} to allow time for grain deactivation to occur", delay); await Task.Delay(delay); // Allow time for Deactivate logger.Info("Awake again."); } } }
//------------------------------------------------------------------------------ // <copyright file="UDPClient.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.Sockets { using System.Threading; using System.Threading.Tasks; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; /// <devdoc> /// <para> /// The <see cref='System.Net.Sockets.UdpClient'/> class provides access to UDP services at a /// higher abstraction level than the <see cref='System.Net.Sockets.Socket'/> class. <see cref='System.Net.Sockets.UdpClient'/> /// is used to connect to a remote host and to receive connections from a remote /// Client. /// </para> /// </devdoc> public class UdpClient : IDisposable { private const int MaxUDPSize = 0x10000; private Socket m_ClientSocket; private bool m_Active; private byte[] m_Buffer = new byte[MaxUDPSize]; /// <devdoc> /// <para> /// Address family for the client, defaults to IPv4. /// </para> /// </devdoc> private AddressFamily m_Family = AddressFamily.InterNetwork; // bind to arbitrary IP+Port /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.Sockets.UdpClient'/>class. /// </para> /// </devdoc> public UdpClient() : this(AddressFamily.InterNetwork){ } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.Sockets.UdpClient'/>class. /// </para> /// </devdoc> public UdpClient(AddressFamily family) { // // Validate the address family // if ( family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6 ) { throw new ArgumentException(SR.GetString(SR.net_protocol_invalid_family, "UDP"), "family"); } m_Family = family; createClientSocket(); } // bind specific port, arbitrary IP /// <devdoc> /// <para> /// Creates a new instance of the UdpClient class that communicates on the /// specified port number. /// </para> /// </devdoc> /// We should obsolete this. This also breaks IPv6-only scenarios. /// But fixing it has many complications that we have decided not /// to fix it and instead obsolete it post-Orcas. public UdpClient(int port) : this(port,AddressFamily.InterNetwork) { } /// <devdoc> /// <para> /// Creates a new instance of the UdpClient class that communicates on the /// specified port number. /// </para> /// </devdoc> public UdpClient(int port,AddressFamily family) { // // parameter validation // if (!ValidationHelper.ValidateTcpPort(port)) { throw new ArgumentOutOfRangeException("port"); } // // Validate the address family // if ( family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6 ) { throw new ArgumentException(SR.GetString(SR.net_protocol_invalid_family), "family"); } IPEndPoint localEP; m_Family = family; if ( m_Family == AddressFamily.InterNetwork ) { localEP = new IPEndPoint(IPAddress.Any, port); } else { localEP = new IPEndPoint(IPAddress.IPv6Any, port); } createClientSocket(); Client.Bind(localEP); } // bind to given local endpoint /// <devdoc> /// <para> /// Creates a new instance of the UdpClient class that communicates on the /// specified end point. /// </para> /// </devdoc> public UdpClient(IPEndPoint localEP) { // // parameter validation // if (localEP == null) { throw new ArgumentNullException("localEP"); } // // IPv6 Changes: Set the AddressFamily of this object before // creating the client socket. // m_Family = localEP.AddressFamily; createClientSocket(); Client.Bind(localEP); } // bind and connect /// <devdoc> /// <para> /// Creates a new instance of the <see cref='System.Net.Sockets.UdpClient'/> class and connects to the /// specified remote host on the specified port. /// </para> /// </devdoc> public UdpClient(string hostname, int port) { // // parameter validation // if (hostname == null) { throw new ArgumentNullException("hostname"); } if (!ValidationHelper.ValidateTcpPort(port)) { throw new ArgumentOutOfRangeException("port"); } // // NOTE: Need to create different kinds of sockets based on the addresses // returned from DNS. As a result, we defer the creation of the // socket until the Connect method. // //createClientSocket(); Connect(hostname, port); } /// <devdoc> /// <para> /// Used by the class to provide the underlying network socket. /// </para> /// </devdoc> public Socket Client { get { return m_ClientSocket; } set { m_ClientSocket = value; } } /// <devdoc> /// <para> /// Used by the class to indicate that a connection to a remote host has been /// made. /// </para> /// </devdoc> protected bool Active { get { return m_Active; } set { m_Active = value; } } public int Available{ get{ return m_ClientSocket.Available; } } public short Ttl{ get{ return m_ClientSocket.Ttl; } set{ m_ClientSocket.Ttl = value; } } //new public bool DontFragment{ get{ return m_ClientSocket.DontFragment; } set{ m_ClientSocket.DontFragment = value; } } //new public bool MulticastLoopback{ get{ return m_ClientSocket.MulticastLoopback; } set{ m_ClientSocket.MulticastLoopback = value; } } //new public bool EnableBroadcast{ get{ return m_ClientSocket.EnableBroadcast; } set{ m_ClientSocket.EnableBroadcast = value; } } //new public bool ExclusiveAddressUse { get{ return m_ClientSocket.ExclusiveAddressUse; } set{ m_ClientSocket.ExclusiveAddressUse = value; } } //new public void AllowNatTraversal(bool allowed) { if (allowed) { m_ClientSocket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted); } else { m_ClientSocket.SetIPProtectionLevel(IPProtectionLevel.EdgeRestricted); } } public void Close() { Dispose(true); } private bool m_CleanedUp = false; private void FreeResources() { // // only resource we need to free is the network stream, since this // is based on the client socket, closing the stream will cause us // to flush the data to the network, close the stream and (in the // NetoworkStream code) close the socket as well. // if (m_CleanedUp) { return; } Socket chkClientSocket = Client; if (chkClientSocket!=null) { // // if the NetworkStream wasn't retrieved, the Socket might // still be there and needs to be closed to release the effect // of the Bind() call and free the bound IPEndPoint. // chkClientSocket.InternalShutdown(SocketShutdown.Both); chkClientSocket.Close(); Client = null; } m_CleanedUp = true; } /// <internalonly/> void IDisposable.Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { GlobalLog.Print("UdpClient::Dispose()"); FreeResources(); GC.SuppressFinalize(this); } } /// <devdoc> /// <para> /// Establishes a connection to the specified port on the /// specified host. /// </para> /// </devdoc> public void Connect(string hostname, int port){ // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (hostname == null){ throw new ArgumentNullException("hostname"); } if (!ValidationHelper.ValidateTcpPort(port)){ throw new ArgumentOutOfRangeException("port"); } // // IPv6 Changes: instead of just using the first address in the list, // we must now look for addresses that use a compatible // address family to the client socket. // However, in the case of the <hostname,port> constructor // we will have deferred creating the socket and will // do that here instead. // In addition, the redundant CheckForBroadcast call was // removed here since it is called from Connect(). // IPAddress[] addresses = Dns.GetHostAddresses(hostname); Exception lastex = null; Socket ipv6Socket = null; Socket ipv4Socket = null; try { if (m_ClientSocket == null){ if (Socket.OSSupportsIPv4){ ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } if (Socket.OSSupportsIPv6){ ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); } } foreach (IPAddress address in addresses) { try { if (m_ClientSocket == null) { // // We came via the <hostname,port> constructor. Set the // address family appropriately, create the socket and // try to connect. // if (address.AddressFamily == AddressFamily.InterNetwork && ipv4Socket != null) { ipv4Socket.Connect(address, port); m_ClientSocket = ipv4Socket; if (ipv6Socket != null) ipv6Socket.Close(); } else if (ipv6Socket != null) { ipv6Socket.Connect(address, port); m_ClientSocket = ipv6Socket; if (ipv4Socket != null) ipv4Socket.Close(); } m_Family = address.AddressFamily; m_Active = true; break; } else if (address.AddressFamily == m_Family) { // // Only use addresses with a matching family // Connect(new IPEndPoint(address, port)); m_Active = true; break; } } catch ( Exception ex ) { if (NclUtilities.IsFatal(ex)) { throw; } lastex = ex; } } } catch (Exception ex){ if (NclUtilities.IsFatal(ex)) { throw; } lastex = ex; } finally { //cleanup temp sockets if failed //main socket gets closed when tcpclient gets closed //did we connect? if (!m_Active) { if (ipv6Socket != null){ ipv6Socket.Close(); } if (ipv4Socket != null){ ipv4Socket.Close(); } // // The connect failed - rethrow the last error we had // if (lastex != null) throw lastex; else throw new SocketException(SocketError.NotConnected); } } } /// <devdoc> /// <para> /// Establishes a connection with the host at the specified address on the /// specified port. /// </para> /// </devdoc> public void Connect(IPAddress addr, int port) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (addr==null){ throw new ArgumentNullException("addr"); } if (!ValidationHelper.ValidateTcpPort(port)) { throw new ArgumentOutOfRangeException("port"); } // // IPv6 Changes: Removed redundant call to CheckForBroadcast() since // it is made in the real Connect() method. // IPEndPoint endPoint = new IPEndPoint(addr, port); Connect(endPoint); } /// <devdoc> /// <para> /// Establishes a connection to a remote end point. /// </para> /// </devdoc> public void Connect(IPEndPoint endPoint) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (endPoint==null){ throw new ArgumentNullException("endPoint"); } // // IPv6 Changes: Actually, no changes but we might want to check for // compatible protocols here rather than push it down // to WinSock. // CheckForBroadcast(endPoint.Address); Client.Connect(endPoint); m_Active = true; } private bool m_IsBroadcast; private void CheckForBroadcast(IPAddress ipAddress) { // // Here we check to see if the user is trying to use a Broadcast IP address // we only detect IPAddress.Broadcast (which is not the only Broadcast address) // and in that case we set SocketOptionName.Broadcast on the socket to allow its use. // if the user really wants complete control over Broadcast addresses he needs to // inherit from UdpClient and gain control over the Socket and do whatever is appropriate. // if (Client!=null && !m_IsBroadcast && ipAddress.IsBroadcast) { // // we need to set the Broadcast socket option. // note that, once we set the option on the Socket, we never reset it. // m_IsBroadcast = true; Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); } } /// <devdoc> /// <para> /// Sends a UDP datagram to the host at the remote end point. /// </para> /// </devdoc> public int Send(byte[] dgram, int bytes, IPEndPoint endPoint) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (dgram==null){ throw new ArgumentNullException("dgram"); } if (m_Active && endPoint!=null) { // // Do not allow sending packets to arbitrary host when connected // throw new InvalidOperationException(SR.GetString(SR.net_udpconnected)); } if (endPoint==null) { return Client.Send(dgram, 0, bytes, SocketFlags.None); } CheckForBroadcast(endPoint.Address); return Client.SendTo(dgram, 0, bytes, SocketFlags.None, endPoint); } /// <devdoc> /// <para> /// Sends a UDP datagram to the specified port on the specified remote host. /// </para> /// </devdoc> public int Send(byte[] dgram, int bytes, string hostname, int port) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (dgram==null){ throw new ArgumentNullException("dgram"); } if (m_Active && ((hostname != null) || (port != 0))) { // // Do not allow sending packets to arbitrary host when connected // throw new InvalidOperationException(SR.GetString(SR.net_udpconnected)); } if (hostname==null || port==0) { return Client.Send(dgram, 0, bytes, SocketFlags.None); } IPAddress[] addresses = Dns.GetHostAddresses(hostname); int i=0; for (;i<addresses.Length && addresses[i].AddressFamily != m_Family; i++); if (addresses.Length == 0 || i == addresses.Length) { throw new ArgumentException(SR.GetString(SR.net_invalidAddressList), "hostname"); } CheckForBroadcast(addresses[i]); IPEndPoint ipEndPoint = new IPEndPoint(addresses[i], port); return Client.SendTo(dgram, 0, bytes, SocketFlags.None, ipEndPoint); } /// <devdoc> /// <para> /// Sends a UDP datagram to a /// remote host. /// </para> /// </devdoc> public int Send(byte[] dgram, int bytes) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (dgram==null){ throw new ArgumentNullException("dgram"); } if (!m_Active) { // // only allowed on connected socket // throw new InvalidOperationException(SR.GetString(SR.net_notconnected)); } return Client.Send(dgram, 0, bytes, SocketFlags.None); } [HostProtection(ExternalThreading=true)] public IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint endPoint, AsyncCallback requestCallback, object state) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (datagram==null){ throw new ArgumentNullException("datagram"); } if (bytes > datagram.Length) { throw new ArgumentOutOfRangeException("bytes"); } if (m_Active && endPoint!=null) { // // Do not allow sending packets to arbitrary host when connected // throw new InvalidOperationException(SR.GetString(SR.net_udpconnected)); } if (endPoint==null) { return Client.BeginSend(datagram, 0, bytes, SocketFlags.None, requestCallback, state); } CheckForBroadcast(endPoint.Address); return Client.BeginSendTo(datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state); } [HostProtection(ExternalThreading=true)] public IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, AsyncCallback requestCallback, object state) { if (m_Active && ((hostname != null) || (port != 0))) { // Do not allow sending packets to arbitrary host when connected throw new InvalidOperationException(SR.GetString(SR.net_udpconnected)); } IPEndPoint ipEndPoint = null; if (hostname!=null && port!=0) { IPAddress[] addresses = Dns.GetHostAddresses(hostname); int i=0; for (;i<addresses.Length && addresses[i].AddressFamily != m_Family; i++); if (addresses.Length == 0 || i == addresses.Length) { throw new ArgumentException(SR.GetString(SR.net_invalidAddressList), "hostname"); } CheckForBroadcast(addresses[i]); ipEndPoint = new IPEndPoint(addresses[i], port); } return BeginSend(datagram, bytes, ipEndPoint,requestCallback, state); } [HostProtection(ExternalThreading=true)] public IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback requestCallback, object state) { return BeginSend(datagram, bytes, null, requestCallback, state); } public int EndSend(IAsyncResult asyncResult){ if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (m_Active){ return Client.EndSend(asyncResult); } else{ return Client.EndSendTo(asyncResult); } } /// <devdoc> /// <para> /// Returns a datagram sent by a server. /// </para> /// </devdoc> public byte[] Receive(ref IPEndPoint remoteEP) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } // this is a fix due to the nature of the ReceiveFrom() call and the // ref parameter convention, we need to cast an IPEndPoint to it's base // class EndPoint and cast it back down to IPEndPoint. ugly but it works. // EndPoint tempRemoteEP; if ( m_Family == AddressFamily.InterNetwork ) { tempRemoteEP = IPEndPoint.Any; } else { tempRemoteEP = IPEndPoint.IPv6Any; } int received = Client.ReceiveFrom(m_Buffer, MaxUDPSize, 0 , ref tempRemoteEP); remoteEP = (IPEndPoint)tempRemoteEP; // because we don't return the actual length, we need to ensure the returned buffer // has the appropriate length. if (received < MaxUDPSize) { byte[] newBuffer = new byte[received]; Buffer.BlockCopy(m_Buffer,0,newBuffer,0,received); return newBuffer; } return m_Buffer; } [HostProtection(ExternalThreading=true)] public IAsyncResult BeginReceive(AsyncCallback requestCallback, object state) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } // this is a fix due to the nature of the ReceiveFrom() call and the // ref parameter convention, we need to cast an IPEndPoint to it's base // class EndPoint and cast it back down to IPEndPoint. ugly but it works. // EndPoint tempRemoteEP; if ( m_Family == AddressFamily.InterNetwork ) { tempRemoteEP = IPEndPoint.Any; } else { tempRemoteEP = IPEndPoint.IPv6Any; } return Client.BeginReceiveFrom(m_Buffer, 0, MaxUDPSize, SocketFlags.None , ref tempRemoteEP, requestCallback, state); } public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint remoteEP){ if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } EndPoint tempRemoteEP; if ( m_Family == AddressFamily.InterNetwork ) { tempRemoteEP = IPEndPoint.Any; } else { tempRemoteEP = IPEndPoint.IPv6Any; } int received = Client.EndReceiveFrom(asyncResult,ref tempRemoteEP); remoteEP = (IPEndPoint)tempRemoteEP; // because we don't return the actual length, we need to ensure the returned buffer // has the appropriate length. if (received < MaxUDPSize) { byte[] newBuffer = new byte[received]; Buffer.BlockCopy(m_Buffer,0,newBuffer,0,received); return newBuffer; } return m_Buffer; } /// <devdoc> /// <para> /// Joins a multicast address group. /// </para> /// </devdoc> public void JoinMulticastGroup(IPAddress multicastAddr) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (multicastAddr==null){ throw new ArgumentNullException("multicastAddr"); } // // IPv6 Changes: we need to create the correct MulticastOption and // must also check for address family compatibility // if ( multicastAddr.AddressFamily != m_Family ) { throw new ArgumentException(SR.GetString(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr"); } if ( m_Family == AddressFamily.InterNetwork ) { MulticastOption mcOpt = new MulticastOption(multicastAddr); Client.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.AddMembership, mcOpt ); } else { IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr); Client.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.AddMembership, mcOpt ); } } public void JoinMulticastGroup(IPAddress multicastAddr, IPAddress localAddress) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if ( m_Family != AddressFamily.InterNetwork ) { throw new SocketException(SocketError.OperationNotSupported); } MulticastOption mcOpt = new MulticastOption(multicastAddr,localAddress); Client.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.AddMembership, mcOpt ); } /// <devdoc> /// <para> /// Joins an IPv6 multicast address group. /// </para> /// </devdoc> public void JoinMulticastGroup(int ifindex,IPAddress multicastAddr) { // // parameter validation // if ( m_CleanedUp ){ throw new ObjectDisposedException(this.GetType().FullName); } if ( multicastAddr==null ) { throw new ArgumentNullException("multicastAddr"); } if ( ifindex < 0 ) { throw new ArgumentException(SR.GetString(SR.net_value_cannot_be_negative), "ifindex"); } // // Ensure that this is an IPv6 client, otherwise throw WinSock // Operation not supported socked exception. // if ( m_Family != AddressFamily.InterNetworkV6 ) { throw new SocketException(SocketError.OperationNotSupported); } IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr,ifindex); Client.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.AddMembership, mcOpt ); } /// <devdoc> /// <para> /// Joins a multicast address group with the specified time to live (TTL). /// </para> /// </devdoc> public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive) { // // parameter validation; // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (multicastAddr==null){ throw new ArgumentNullException("multicastAddr"); } if (!ValidationHelper.ValidateRange(timeToLive, 0, 255)) { throw new ArgumentOutOfRangeException("timeToLive"); } // // join the Multicast Group // JoinMulticastGroup(multicastAddr); // // set Time To Live (TLL) // Client.SetSocketOption( (m_Family == AddressFamily.InterNetwork) ? SocketOptionLevel.IP : SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, timeToLive ); } /// <devdoc> /// <para> /// Leaves a multicast address group. /// </para> /// </devdoc> public void DropMulticastGroup(IPAddress multicastAddr) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if (multicastAddr==null){ throw new ArgumentNullException("multicastAddr"); } // // IPv6 Changes: we need to create the correct MulticastOption and // must also check for address family compatibility // if ( multicastAddr.AddressFamily != m_Family ) { throw new ArgumentException(SR.GetString(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr"); } if ( m_Family == AddressFamily.InterNetwork ) { MulticastOption mcOpt = new MulticastOption(multicastAddr); Client.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.DropMembership, mcOpt ); } else { IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr); Client.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.DropMembership, mcOpt ); } } /// <devdoc> /// <para> /// Leaves an IPv6 multicast address group. /// </para> /// </devdoc> public void DropMulticastGroup(IPAddress multicastAddr,int ifindex) { // // parameter validation // if (m_CleanedUp){ throw new ObjectDisposedException(this.GetType().FullName); } if ( multicastAddr==null ) { throw new ArgumentNullException("multicastAddr"); } if ( ifindex < 0 ) { throw new ArgumentException(SR.GetString(SR.net_value_cannot_be_negative), "ifindex"); } // // Ensure that this is an IPv6 client, otherwise throw WinSock // Operation not supported socked exception. // if ( m_Family != AddressFamily.InterNetworkV6 ) { throw new SocketException(SocketError.OperationNotSupported); } IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr,ifindex); Client.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.DropMembership, mcOpt ); } //************* Task-based async public methods ************************* [HostProtection(ExternalThreading = true)] public Task<int> SendAsync(byte[] datagram, int bytes) { return Task<int>.Factory.FromAsync(BeginSend, EndSend, datagram, bytes, null); } [HostProtection(ExternalThreading = true)] public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint endPoint) { return Task<int>.Factory.FromAsync(BeginSend, EndSend, datagram, bytes, endPoint, null); } [HostProtection(ExternalThreading = true)] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "hostname", Justification="Original parameter spelling is preserved for consistency")] public Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port) { return Task<int>.Factory.FromAsync((callback, state) => BeginSend(datagram, bytes, hostname, port, callback, state), EndSend, null); } [HostProtection(ExternalThreading = true)] public Task<UdpReceiveResult> ReceiveAsync() { return Task<UdpReceiveResult>.Factory.FromAsync((callback, state) => BeginReceive(callback, state), (ar)=> { IPEndPoint remoteEP = null; Byte[] buffer = EndReceive(ar, ref remoteEP); return new UdpReceiveResult(buffer, remoteEP); }, null); } private void createClientSocket() { // // common initialization code // // IPv6 Changes: Use the AddressFamily of this class rather than hardcode. // Client = new Socket(m_Family, SocketType.Dgram, ProtocolType.Udp); } } // class UdpClient } // namespace System.Net.Sockets
/* Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; namespace XnaDevRu.BulletX { /// <summary> /// ConeShape implements a Cone shape, around the X axis /// </summary> public class ConeShapeX : ConeShape { public ConeShapeX(float radius, float height) : base(radius, height) { ConeUpIndex = 0; } } /// <summary> /// ConeShape implements a Cone shape, around the Z axis /// </summary> public class ConeShapeZ : ConeShape { public ConeShapeZ(float radius, float height) : base(radius, height) { ConeUpIndex = 2; } } /// <summary> /// ConeShape implements a Cone shape, around the Y axis /// </summary> public class ConeShape : ConvexShape { private float _sinAngle; private float _radius; private float _height; private int[] _coneIndices = new int[3]; public ConeShape(float radius, float height) { _radius = radius; _height = height; ConeUpIndex = 1; _sinAngle = (_radius / (float)Math.Sqrt(_radius * _radius + _height * _height)); } public float Radius { get { return _radius; } } public float Height { get { return _height; } } public override BroadphaseNativeTypes ShapeType { get { return BroadphaseNativeTypes.Cone; } } public override string Name { get { return "Cone"; } } //choose upAxis index public int ConeUpIndex { get { return _coneIndices[1]; } set { switch (value) { case 0: _coneIndices[0] = 1; _coneIndices[1] = 0; _coneIndices[2] = 2; break; case 1: _coneIndices[0] = 0; _coneIndices[1] = 1; _coneIndices[2] = 2; break; case 2: _coneIndices[0] = 0; _coneIndices[1] = 2; _coneIndices[2] = 1; break; default: BulletDebug.Assert(false); break; } } } private Vector3 ConeLocalSupport(Vector3 v) { float halfHeight = _height * 0.5f; bool condition; if (_coneIndices[1] == 0) condition = v.X > v.Length() * _sinAngle; else if (_coneIndices[1] == 1) condition = v.Y > v.Length() * _sinAngle; else condition = v.Z > v.Length() * _sinAngle; if (condition) { Vector3 tmp = new Vector3(); MathHelper.SetValueByIndex(ref tmp, _coneIndices[1], halfHeight); return tmp; } else { float s = (float)Math.Sqrt(MathHelper.GetValueByIndex(v, _coneIndices[0]) * MathHelper.GetValueByIndex(v, _coneIndices[0]) + MathHelper.GetValueByIndex(v, _coneIndices[2]) * MathHelper.GetValueByIndex(v, _coneIndices[2])); if (s > MathHelper.Epsilon) { float d = _radius / s; Vector3 tmp = new Vector3(); MathHelper.SetValueByIndex(ref tmp, _coneIndices[0], MathHelper.GetValueByIndex(v, _coneIndices[0]) * d); MathHelper.SetValueByIndex(ref tmp, _coneIndices[1], -halfHeight); MathHelper.SetValueByIndex(ref tmp, _coneIndices[2], MathHelper.GetValueByIndex(v, _coneIndices[2]) * d); return tmp; } else { Vector3 tmp = new Vector3(); MathHelper.SetValueByIndex(ref tmp, _coneIndices[1], -halfHeight); return tmp; } } } public override Vector3 LocalGetSupportingVertexWithoutMargin(Vector3 vec) { return ConeLocalSupport(vec); } public override void BatchedUnitVectorGetSupportingVertexWithoutMargin(Vector3[] vectors, Vector3[] supportVerticesOut) { for (int i = 0; i < vectors.Length; i++) supportVerticesOut[i] = ConeLocalSupport(vectors[i]); } public override void CalculateLocalInertia(float mass, out Vector3 inertia) { Matrix identity = Matrix.Identity; Vector3 aabbMin, aabbMax; GetAabb(identity, out aabbMin, out aabbMax); Vector3 halfExtents = (aabbMax - aabbMin) * 0.5f; float margin = Margin; float lx = 2f * (halfExtents.X + margin); float ly = 2f * (halfExtents.Y + margin); float lz = 2f * (halfExtents.Z + margin); float x2 = lx * lx; float y2 = ly * ly; float z2 = lz * lz; float scaledmass = mass * 0.08333333f; inertia = scaledmass * (new Vector3(y2 + z2, x2 + z2, x2 + y2)); } public override Vector3 LocalGetSupportingVertex(Vector3 vec) { Vector3 supVertex = ConeLocalSupport(vec); if (Margin != 0) { Vector3 vecnorm = vec; if (vecnorm.LengthSquared() < (MathHelper.Epsilon * MathHelper.Epsilon)) { vecnorm = new Vector3(-1f, -1f, -1f); } vecnorm = Vector3.Normalize(vecnorm); supVertex += Margin * vecnorm; } return supVertex; } } }
using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using Reusable; using Reusable.Collections; using Reusable.Exceptionizer; using Reusable.Extensions; using Reusable.Reflection; namespace Gunter.Data.Dtos { public class TripleTableDto { public TripleTableDto(IEnumerable<ColumnDto> columns, bool areHeaders = true) { //var columnList = columns.ToList(); Head = new TableDto(columns); if (areHeaders) { var row = Head.NewRow(); foreach (var column in columns) { row[column.Name] = column.Name.ToString(); } } Body = new TableDto(columns); Foot = new TableDto(columns); } //public TripleTableDto(IEnumerable<string> columns, bool areHeaders = true) // : this(columns.Select(SoftString.Create), areHeaders) //{ //} [NotNull] public TableDto Head { get; } [NotNull] public TableDto Body { get; } [NotNull] public TableDto Foot { get; } [NotNull] public IDictionary<string, IEnumerable<IEnumerable<object>>> Dump() { return new Dictionary<string, IEnumerable<IEnumerable<object>>> { [nameof(Head)] = Head.Dump(), [nameof(Body)] = Body.Dump(), [nameof(Foot)] = Foot.Dump(), }; } } public class TableDto { private readonly IDictionary<SoftString, ColumnDto> _columnByName; private readonly IDictionary<int, ColumnDto> _columnByOrdinal; private readonly List<RowDto> _rows = new List<RowDto>(); public TableDto(IEnumerable<ColumnDto> columns) { //var columns = names.Select((name, ordinal) => new ColumnDto { Name = name, Ordinal = ordinal }).ToList(); //var columnList = columns.ToList(); columns = columns.Select((column, ordinal) => new ColumnDto { Name = column.Name, Ordinal = ordinal, Type = column.Type }).ToList(); _columnByName = columns.ToDictionary(x => x.Name); _columnByOrdinal = columns.ToDictionary(x => x.Ordinal); } //public TableDto(params ColumnDto[] columns) : this((IEnumerable<ColumnDto>)columns) //{ //} internal IEnumerable<ColumnDto> Columns => _columnByName.Values; //[NotNull] //public RowDto LastRow => _rows.LastOrDefault() ?? throw new InvalidOperationException("There are no rows."); [NotNull] public RowDto NewRow() { var newRow = new RowDto ( _columnByName.Values, name => _columnByName.GetItemSafely(name), ordinal => _columnByOrdinal.GetItemSafely(ordinal) ); _rows.Add(newRow); return newRow; } //public void Add(IEnumerable<T> values) //{ // var newRow = NewRow(); // foreach (var (column, value) in _columnByName.Values.Zip(values, (column, value) => (column, value))) // { // newRow[column.Name] = value; // } //} //public void Add(params T[] values) => Add((IEnumerable<T>)values); [NotNull, ItemNotNull] public IEnumerable<IEnumerable<object>> Dump() => _rows.Select(row => row.Dump()); } public static class TableDtoExtensions { public static void Add(this TableDto table, IEnumerable<object> values) { var newRow = table.NewRow(); foreach (var (column, value) in table.Columns.Zip(values, (column, value) => (column, value))) { newRow[column.Name] = value; } } public static void Add(this TableDto table, params object[] values) => table.Add((IEnumerable<object>)values); } public class ColumnDto { public static readonly IComparer<ColumnDto> Comparer = ComparerFactory<ColumnDto>.Create ( isLessThan: (x, y) => x.Ordinal < y.Ordinal, areEqual: (x, y) => x.Ordinal == y.Ordinal, isGreaterThan: (x, y) => x.Ordinal > y.Ordinal ); public SoftString Name { get; internal set; } public int Ordinal { get; internal set; } public Type Type { get; internal set; } internal static ColumnDto Create<T>(SoftString name) => new ColumnDto { Name = name, //Ordinal = ordinal, Type = typeof(T) }; public override string ToString() => $"{Name}[{Ordinal}]"; } //public class ColumnDtoBuilder //{ // private readonly List<ColumnDto> _columns = new List<ColumnDto>(); // public ColumnDtoBuilder Add<T>(SoftString name) // { // _columns.Add(ColumnDto.Create<T>(name, _columns.Count)); // return this; // } // public static implicit operator List<ColumnDto>(ColumnDtoBuilder builder) => builder._columns; //} public class RowDto { private readonly IDictionary<ColumnDto, object> _data; private readonly Func<SoftString, ColumnDto> _getColumnByName; private readonly Func<int, ColumnDto> _getColumnByOrdinal; internal RowDto(IEnumerable<ColumnDto> columns, Func<SoftString, ColumnDto> getColumnByName, Func<int, ColumnDto> getColumnByOrdinal) { // All rows need to have the same length so initialize them with 'default' values. _data = new SortedDictionary<ColumnDto, object>(columns.ToDictionary(x => x, _ => default(object)), ColumnDto.Comparer); _getColumnByName = getColumnByName; _getColumnByOrdinal = getColumnByOrdinal; } [CanBeNull] public object this[SoftString name] { get => _data.GetItemSafely(_getColumnByName(name)); set => SetValue(_getColumnByName(name), value); } [CanBeNull] public object this[int ordinal] { get => _data.GetItemSafely(_getColumnByOrdinal(ordinal)); set => SetValue(_getColumnByOrdinal(ordinal), value); } private void SetValue(ColumnDto column, object value) { if (!(value is null) && value.GetType() != column.Type) { throw DynamicException.Create( $"{column.Name.ToString()}Type", $"The specified value has an invalid type for this column. Expected '{column.Type.Name}' but found '{value.GetType().ToPrettyString()}'." ); } _data[column] = value; } [NotNull, ItemCanBeNull] public IEnumerable<object> Dump() => _data.Values; } public static class RowDtoExtensions { public static T Value<T>(this RowDto row, SoftString name) => row[name] is T value ? value : default; public static T Value<T>(this RowDto row, int ordinal) => row[ordinal] is T value ? value : default; } internal static class ComparerFactory<T> { private class Comparer : IComparer<T> { private readonly Func<T, T, bool> _isLessThan; private readonly Func<T, T, bool> _areEqual; private readonly Func<T, T, bool> _isGreaterThan; public Comparer(Func<T, T, bool> isLessThan, Func<T, T, bool> areEqual, Func<T, T, bool> isGreaterThan) { _isLessThan = isLessThan; _areEqual = areEqual; _isGreaterThan = isGreaterThan; } public int Compare(T x, T y) { if (ReferenceEquals(x, y)) return 0; if (ReferenceEquals(x, null)) return -1; if (ReferenceEquals(y, null)) return 1; if (_isLessThan(x, y)) return -1; if (_areEqual(x, y)) return 0; if (_isGreaterThan(x, y)) return 1; // Makes the compiler very happy. return 0; } } public static IComparer<T> Create(Func<T, T, bool> isLessThan, Func<T, T, bool> areEqual, Func<T, T, bool> isGreaterThan) { return new Comparer(isLessThan, areEqual, isGreaterThan); } } }
/***************************************************************************** * * * OpenNI 1.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Permissions; namespace OpenNI { public static class WrapperUtils { public static string GetErrorMessage(Int32 status) { return Marshal.PtrToStringAnsi(SafeNativeMethods.xnGetStatusString(status)); } public static void ThrowOnError(Int32 status) { if (status != 0) { throw new StatusException(status); } } public static void CheckEnumeration(Int32 status, EnumerationErrors errors) { if (status != 0) { if (errors != null && !errors.IsEmpty()) { throw new GeneralException(errors.ToString()); } else { throw new StatusException(status); } } } } public abstract class HandleWrapper { internal HandleWrapper(Int32 handle) { this.handle = handle; } /// <summary> /// Gets the native (C language) OpenNI handle. This method should only be used for native-managed transitions. /// </summary> /// <returns>An OpenNI handle</returns> public Int32 ToNative() { return this.handle; } internal Int32 InternalHandle { get { return this.handle; } } private Int32 handle; } public abstract class ObjectWrapper : IDisposable { internal ObjectWrapper(IntPtr ptr) { if (ptr == IntPtr.Zero) { throw new GeneralException("c# wrappers: Trying to wrap a null object!"); } this.ptr = ptr; } ~ObjectWrapper() { Dispose(false); } /// <summary> /// Gets the native (C language) OpenNI object. This method should only be used for native-managed transitions. /// </summary> /// <returns>A pointer to the OpenNI object</returns> public IntPtr ToNative() { return this.InternalObject; } #region IDisposable Members public virtual void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion internal IntPtr InternalObject { get { if (this.ptr == IntPtr.Zero) { throw new ObjectDisposedException(GetType().Name); } return this.ptr; } } protected internal void UnsafeReplaceInternalObject(IntPtr ptr) { this.ptr = ptr; } protected abstract void FreeObject(IntPtr ptr, bool disposing); protected virtual void Dispose(bool disposing) { if (this.ptr != IntPtr.Zero) { FreeObject(this.ptr, disposing); this.ptr = IntPtr.Zero; } } private IntPtr ptr; } [Serializable] public class GeneralException : System.Exception { public GeneralException() : base() { } public GeneralException(string message) : base(message) { } public GeneralException(string message, Exception innerException) : base(message, innerException) { } protected GeneralException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class StatusException : GeneralException { public StatusException() : this(0) { } public StatusException(Int32 status) : base(WrapperUtils.GetErrorMessage(status)) { this.status = status; } public StatusException(string message) : base(message) { } public StatusException(string message, Exception innerException) : base(message, innerException) { } protected StatusException(SerializationInfo info, StreamingContext context) : base(info, context) { } public Int32 Status { get { return status; } } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Status", status); base.GetObjectData(info, context); } private Int32 status; } public class LockHandle : HandleWrapper { internal LockHandle(Int32 handle) : base(handle) { } /// <summary> /// Creates a managed LockHandle object to wrap a native one. /// </summary> /// <param name="handle">The native lock handle</param> /// <returns>A managed LockHandle object</returns> static public LockHandle FromNative(Int32 handle) { return new LockHandle(handle); } } public struct CodecID { public CodecID(int internalValue) { this.val = internalValue; } public CodecID(byte byte1, byte byte2, byte byte3, byte byte4) : this(byte4 << 24 | byte3 << 16 | byte2 << 8 | byte1) { } public CodecID(char char1, char char2, char char3, char char4) : this((byte)char1, (byte)char2, (byte)char3, (byte)char4) { } public static readonly CodecID Null = new CodecID(0, 0, 0, 0); public static readonly CodecID Uncompressed = new CodecID('N', 'O', 'N', 'E'); public static readonly CodecID Jpeg = new CodecID('J', 'P', 'E', 'G'); public static readonly CodecID Z16 = new CodecID('1', '6', 'z', 'P'); public static readonly CodecID Z16WithTables = new CodecID('1', '6', 'z', 'T'); public static readonly CodecID Z8 = new CodecID('I', 'm', '8', 'z'); internal int InternalValue { get { return this.val; } } private int val; } public class NodeWrapper : ObjectWrapper { internal NodeWrapper(IntPtr hNode, bool addRef) : base(hNode) { this.contextShuttingDownHandler = OnContextShuttingDown; if (addRef) { WrapperUtils.ThrowOnError(SafeNativeMethods.xnProductionNodeAddRef(hNode)); } IntPtr pContext = SafeNativeMethods.xnGetRefContextFromNodeHandle(hNode); int status = SafeNativeMethods.xnContextRegisterForShutdown(pContext, this.contextShuttingDownHandler, IntPtr.Zero, out this.hShutdownCallback); WrapperUtils.ThrowOnError(status); SafeNativeMethods.xnContextRelease(pContext); } public override bool Equals(object obj) { return Equals(obj as NodeWrapper); } public bool Equals(NodeWrapper other) { if (other == null) return false; return (this.InternalObject == other.InternalObject); } public override int GetHashCode() { return this.InternalObject.GetHashCode(); } /// TRUE if the object points to an actual node, FALSE otherwise. public bool IsValid { get { return (this.InternalObject != IntPtr.Zero); } } public string Name { get { return Marshal.PtrToStringAnsi(SafeNativeMethods.xnGetNodeName(this.InternalObject)); } } protected override void FreeObject(IntPtr ptr, bool disposing) { IntPtr pContext = SafeNativeMethods.xnGetRefContextFromNodeHandle(ptr); SafeNativeMethods.xnContextUnregisterFromShutdown(pContext, this.hShutdownCallback); SafeNativeMethods.xnContextRelease(pContext); SafeNativeMethods.xnProductionNodeRelease(ptr); } private void OnContextShuttingDown(IntPtr pContext, IntPtr pCookie) { // the context is shutting down // no need to unregister from shutting down event - the event is destroyed anyway UnsafeReplaceInternalObject(IntPtr.Zero); Dispose(); } private SafeNativeMethods.XnContextShuttingDownHandler contextShuttingDownHandler; private IntPtr hShutdownCallback; }; public class Capability : NodeWrapper { public Capability(ProductionNode node) : base(node.InternalObject, true) { this.node = node; } internal ProductionNode node; /// @todo this is a temporary solution for capability not being disposed by anyone external public override void Dispose() { // we do nothing because we basically want to make the public dispose do nothing! } /// @todo this is a temporary solution for capability not being disposed by anyone external internal virtual void InternalDispose() { base.Dispose(); } } public interface IMarshaler : IDisposable { IntPtr Native { get; } } public class Marshaler<T> : IMarshaler { public Marshaler(T obj, bool marshalOut, params IMarshaler[] inner) { this.obj = obj; this.marshalOut = marshalOut; this.native = this.Allocate(); // we always have to copy in (so that pointers are set correctly) ManagedToNative(obj, this.native); this.inner = inner; } #region IMarshaler Members public IntPtr Native { get { return this.native; } } #endregion #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion protected virtual IntPtr Allocate() { return Marshal.AllocHGlobal(Marshal.SizeOf(this.obj)); } protected virtual void Free(IntPtr ptr) { Marshal.FreeHGlobal(ptr); } protected virtual void ManagedToNative(T source, IntPtr dest) { Marshal.StructureToPtr(source, dest, false); } protected virtual void NativeToManaged(IntPtr source, T dest) { Marshal.PtrToStructure(source, dest); } private void Dispose(bool disposing) { if (this.native != IntPtr.Zero) { if (this.marshalOut) { NativeToManaged(this.native, this.obj); } Free(this.native); this.native = IntPtr.Zero; foreach (IMarshaler marshaler in this.inner) { marshaler.Dispose(); } this.inner = null; } } private T obj; private bool marshalOut; private IntPtr native; private IMarshaler[] inner; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Lucene.Net.Support; using NUnit.Framework; using Lucene.Net.Analysis; using Lucene.Net.Documents; using Lucene.Net.Store; using Lucene.Net.Util; using English = Lucene.Net.Util.English; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Index { [TestFixture] public class TestTransactions:LuceneTestCase { private System.Random RANDOM; private static volatile bool doFail; private class RandomFailure:MockRAMDirectory.Failure { public RandomFailure(TestTransactions enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestTransactions enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTransactions enclosingInstance; public TestTransactions Enclosing_Instance { get { return enclosingInstance; } } public override void Eval(MockRAMDirectory dir) { if (TestTransactions.doFail && Enclosing_Instance.RANDOM.Next() % 10 <= 3) throw new System.IO.IOException("now failing randomly but on purpose"); } } abstract public class TimedThread:ThreadClass { internal bool failed; private static int RUN_TIME_SEC = 6; private TimedThread[] allThreads; abstract public void DoWork(); internal TimedThread(TimedThread[] threads) { this.allThreads = threads; } override public void Run() { long stopTime = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000 * RUN_TIME_SEC; try { while ((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) < stopTime && !AnyErrors()) DoWork(); } catch (System.Exception e) { System.Console.Out.WriteLine(ThreadClass.Current() + ": exc"); System.Console.Out.WriteLine(e.StackTrace); failed = true; } } private bool AnyErrors() { for (int i = 0; i < allThreads.Length; i++) if (allThreads[i] != null && allThreads[i].failed) return true; return false; } } private class IndexerThread:TimedThread { private void InitBlock(TestTransactions enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTransactions enclosingInstance; public TestTransactions Enclosing_Instance { get { return enclosingInstance; } } internal Directory dir1; internal Directory dir2; internal System.Object lock_Renamed; internal int nextID; public IndexerThread(TestTransactions enclosingInstance, System.Object lock_Renamed, Directory dir1, Directory dir2, TimedThread[] threads):base(threads) { InitBlock(enclosingInstance); this.lock_Renamed = lock_Renamed; this.dir1 = dir1; this.dir2 = dir2; } public override void DoWork() { IndexWriter writer1 = new IndexWriter(dir1, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); writer1.SetMaxBufferedDocs(3); writer1.MergeFactor = 2; ((ConcurrentMergeScheduler) writer1.MergeScheduler).SetSuppressExceptions(); IndexWriter writer2 = new IndexWriter(dir2, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); // Intentionally use different params so flush/merge // happen @ different times writer2.SetMaxBufferedDocs(2); writer2.MergeFactor = 3; ((ConcurrentMergeScheduler) writer2.MergeScheduler).SetSuppressExceptions(); Update(writer1); Update(writer2); TestTransactions.doFail = true; try { lock (lock_Renamed) { try { writer1.PrepareCommit(); } catch (System.Exception t) { writer1.Rollback(); writer2.Rollback(); return ; } try { writer2.PrepareCommit(); } catch (System.Exception t) { writer1.Rollback(); writer2.Rollback(); return ; } writer1.Commit(); writer2.Commit(); } } finally { TestTransactions.doFail = false; } writer1.Close(); writer2.Close(); } public virtual void Update(IndexWriter writer) { // Add 10 docs: for (int j = 0; j < 10; j++) { Document d = new Document(); int n = Enclosing_Instance.RANDOM.Next(); d.Add(new Field("id", System.Convert.ToString(nextID++), Field.Store.YES, Field.Index.NOT_ANALYZED)); d.Add(new Field("contents", English.IntToEnglish(n), Field.Store.NO, Field.Index.ANALYZED)); writer.AddDocument(d); } // Delete 5 docs: int deleteID = nextID - 1; for (int j = 0; j < 5; j++) { writer.DeleteDocuments(new Term("id", "" + deleteID)); deleteID -= 2; } } } private class SearcherThread:TimedThread { internal Directory dir1; internal Directory dir2; internal System.Object lock_Renamed; public SearcherThread(System.Object lock_Renamed, Directory dir1, Directory dir2, TimedThread[] threads):base(threads) { this.lock_Renamed = lock_Renamed; this.dir1 = dir1; this.dir2 = dir2; } public override void DoWork() { IndexReader r1, r2; lock (lock_Renamed) { r1 = IndexReader.Open(dir1, true); r2 = IndexReader.Open(dir2, true); } if (r1.NumDocs() != r2.NumDocs()) throw new System.SystemException("doc counts differ: r1=" + r1.NumDocs() + " r2=" + r2.NumDocs()); r1.Close(); r2.Close(); } } public virtual void InitIndex(Directory dir) { IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); for (int j = 0; j < 7; j++) { Document d = new Document(); int n = RANDOM.Next(); d.Add(new Field("contents", English.IntToEnglish(n), Field.Store.NO, Field.Index.ANALYZED)); writer.AddDocument(d); } writer.Close(); } [Test] public virtual void TestTransactions_Rename() { RANDOM = NewRandom(); MockRAMDirectory dir1 = new MockRAMDirectory(); MockRAMDirectory dir2 = new MockRAMDirectory(); dir1.SetPreventDoubleWrite(false); dir2.SetPreventDoubleWrite(false); dir1.FailOn(new RandomFailure(this)); dir2.FailOn(new RandomFailure(this)); InitIndex(dir1); InitIndex(dir2); TimedThread[] threads = new TimedThread[3]; int numThread = 0; IndexerThread indexerThread = new IndexerThread(this, this, dir1, dir2, threads); threads[numThread++] = indexerThread; indexerThread.Start(); SearcherThread searcherThread1 = new SearcherThread(this, dir1, dir2, threads); threads[numThread++] = searcherThread1; searcherThread1.Start(); SearcherThread searcherThread2 = new SearcherThread(this, dir1, dir2, threads); threads[numThread++] = searcherThread2; searcherThread2.Start(); for (int i = 0; i < numThread; i++) threads[i].Join(); for (int i = 0; i < numThread; i++) Assert.IsTrue(!((TimedThread) threads[i]).failed); } } }
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Hazelcast.Client.Model; using Hazelcast.Config; using Hazelcast.Core; using Hazelcast.IO; using Hazelcast.IO.Serialization; using Hazelcast.Map; using NUnit.Framework; namespace Hazelcast.Client.Test { [TestFixture] public class ClientMapTest : SingleMemberBaseTest { [SetUp] public void Init() { map = Client.GetMap<object, object>(TestSupport.RandomString()); } [TearDown] public static void Destroy() { map.Clear(); } protected override void ConfigureClient(ClientConfig config) { base.ConfigureClient(config); config.GetSerializationConfig().AddPortableFactory(1, new PortableFactory()); config.GetSerializationConfig() .AddDataSerializableFactory(IdentifiedFactory.FactoryId, new IdentifiedFactory()); } //internal const string name = "test"; internal static IMap<object, object> map; private void FillMap() { for (var i = 0; i < 10; i++) { map.Put("key" + i, "value" + i); } } [Serializable] internal class Deal { internal int id; internal Deal(int id) { this.id = id; } public virtual int GetId() { return id; } public virtual void SetId(int id) { this.id = id; } } private class Interceptor : IMapInterceptor, IIdentifiedDataSerializable { public void WriteData(IObjectDataOutput output) { } public int GetFactoryId() { return 1; } public int GetId() { return 0; } public void ReadData(IObjectDataInput input) { } public object InterceptGet(object value) { throw new NotImplementedException(); } public void AfterGet(object value) { throw new NotImplementedException(); } public object InterceptPut(object oldValue, object newValue) { throw new NotImplementedException(); } public void AfterPut(object value) { throw new NotImplementedException(); } public object InterceptRemove(object removedValue) { throw new NotImplementedException(); } public void AfterRemove(object value) { throw new NotImplementedException(); } } [Test] public virtual void TestAddIndex() { map.AddIndex("name", true); } [Ignore("not currently possible to test this")] [Test] public void TestAddInterceptor() { Assert.Throws<HazelcastException>(() => { //TODO: not currently possible to test this var id = map.AddInterceptor(new Interceptor()); }); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestAsyncGet() { FillMap(); var f = map.GetAsync("key1"); var o = f.Result; Assert.AreEqual("value1", o); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestAsyncPut() { FillMap(); var f = map.PutAsync("key3", "value"); Assert.False(f.IsCompleted); var o = f.Result; Assert.AreEqual("value3", o); Assert.AreEqual("value", map.Get("key3")); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestAsyncPutWithTtl() { var latch = new CountdownEvent(1); map.AddEntryListener(new EntryAdapter<object, object>( delegate { }, delegate { }, delegate { }, delegate { latch.Signal(); } ), true); var f1 = map.PutAsync("key", "value1", 1, TimeUnit.Seconds); Assert.IsNull(f1.Result); Assert.AreEqual("value1", map.Get("key")); Assert.IsTrue(latch.Wait(TimeSpan.FromSeconds(10))); TestSupport.AssertTrueEventually(() => { Assert.IsNull(map.Get("key")); }); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestAsyncRemove() { FillMap(); var f = map.RemoveAsync("key4"); Assert.False(f.IsCompleted); var o = f.Result; Assert.AreEqual("value4", o); Assert.AreEqual(9, map.Size()); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestContains() { FillMap(); Assert.IsFalse(map.ContainsKey("key10")); Assert.IsTrue(map.ContainsKey("key1")); Assert.IsFalse(map.ContainsValue("value10")); Assert.IsTrue(map.ContainsValue("value1")); } [Test] public virtual void TestEntrySet() { map.Put("key1", "value1"); map.Put("key2", "value2"); map.Put("key3", "value3"); var keyValuePairs = map.EntrySet(); IDictionary<object, object> tempDict = new Dictionary<object, object>(); foreach (var keyValuePair in keyValuePairs) { tempDict.Add(keyValuePair); } Assert.True(tempDict.ContainsKey("key1")); Assert.True(tempDict.ContainsKey("key2")); Assert.True(tempDict.ContainsKey("key3")); object value; tempDict.TryGetValue("key1", out value); Assert.AreEqual("value1", value); tempDict.TryGetValue("key2", out value); Assert.AreEqual("value2", value); tempDict.TryGetValue("key3", out value); Assert.AreEqual("value3", value); } [Test] public virtual void TestEntrySetPredicate() { map.Put("key1", "value1"); map.Put("key2", "value2"); map.Put("key3", "value3"); var keyValuePairs = map.EntrySet(new SqlPredicate("this == value1")); Assert.AreEqual(1, keyValuePairs.Count); var enumerator = keyValuePairs.GetEnumerator(); enumerator.MoveNext(); Assert.AreEqual("key1", enumerator.Current.Key); Assert.AreEqual("value1", enumerator.Current.Value); } [Test] public virtual void TestEntryView() { var item = ItemGenerator.GenerateItem(1); map.Put("key1", item); map.Get("key1"); map.Get("key1"); var entryview = map.GetEntryView("key1"); var value = entryview.GetValue() as Item; Assert.AreEqual("key1", entryview.GetKey()); Assert.True(item.Equals(value)); //Assert.AreEqual(2, entryview.GetHits()); //Assert.True(entryview.GetCreationTime() > 0); //Assert.True(entryview.GetLastAccessTime() > 0); //Assert.True(entryview.GetLastUpdateTime() > 0); } [Test] public virtual void TestEvict() { map.Put("key1", "value1"); Assert.AreEqual("value1", map.Get("key1")); map.Evict("key1"); Assert.AreEqual(0, map.Size()); Assert.AreNotEqual("value1", map.Get("key1")); } [Test] public void TestEvictAll() { map.Put("key1", "value1"); map.Put("key2", "value2"); map.Put("key3", "value3"); Assert.AreEqual(3, map.Size()); map.Lock("key3"); map.EvictAll(); Assert.AreEqual(1, map.Size()); Assert.AreEqual("value3", map.Get("key3")); } [Test] public virtual void TestFlush() { map.Flush(); } [Test] public virtual void TestExecuteOnKey() { FillMap(); const string key = "key1"; const string value = "value10"; var entryProcessor = new IdentifiedEntryProcessor(value); var result = map.ExecuteOnKey(key, entryProcessor); Assert.AreEqual(result, value); Assert.AreEqual(result, map.Get(key)); } [Test] public void TestExecuteOnKey_nullKey() { Assert.Throws<ArgumentNullException>(() => { FillMap(); const string key = null; const string value = "value10"; var entryProcessor = new IdentifiedEntryProcessor(value); map.ExecuteOnKey(key, entryProcessor); }); } [Test] public virtual void TestExecuteOnKeys() { FillMap(); var keys = new HashSet<object> {"key1", "key5"}; const string value = "valueX"; var entryProcessor = new IdentifiedEntryProcessor(value); var result = map.ExecuteOnKeys(keys, entryProcessor); foreach (var resultKV in result) { Assert.AreEqual(resultKV.Value, value); Assert.AreEqual(value, map.Get(resultKV.Key)); } } [Test] public void TestExecuteOnKeys_keysNotNull() { Assert.Throws<ArgumentNullException>(() => { FillMap(); ISet<object> keys = null; const string value = "valueX"; var entryProcessor = new IdentifiedEntryProcessor(value); map.ExecuteOnKeys(keys, entryProcessor); }); } [Test] public virtual void TestExecuteOnKeys_keysEmpty() { FillMap(); ISet<object> keys = new HashSet<object>(); const string value = "valueX"; var entryProcessor = new IdentifiedEntryProcessor(value); var result = map.ExecuteOnKeys(keys, entryProcessor); Assert.AreEqual(result.Count, 0); } [Test] public virtual void TestExecuteOnEntries() { FillMap(); const string value = "valueX"; var entryProcessor = new IdentifiedEntryProcessor(value); var result = map.ExecuteOnEntries(entryProcessor); foreach (var resultKV in result) { Assert.AreEqual(resultKV.Value, value); Assert.AreEqual(value, map.Get(resultKV.Key)); } } [Test] public virtual void TestExecuteOnEntriesWithPredicate() { FillMap(); const string value = "valueX"; var entryProcessor = new IdentifiedEntryProcessor(value); var result = map.ExecuteOnEntries(entryProcessor, Predicates.Sql("this == value5")); Assert.AreEqual(result.Count, 1); foreach (var resultKV in result) { Assert.AreEqual(resultKV.Value, value); Assert.AreEqual(value, map.Get(resultKV.Key)); } } [Test] public virtual void TestSubmitToKey() { FillMap(); const string key = "key1"; const string value = "value10"; var entryProcessor = new IdentifiedEntryProcessor(value); var task = map.SubmitToKey(key, entryProcessor); Assert.AreEqual(task.Result, value); Assert.AreEqual(task.Result, map.Get(key)); } [Test] public void TestSubmitToKey_nullKey() { Assert.Throws<ArgumentNullException>(() => { const string key = null; const string value = "value10"; var entryProcessor = new IdentifiedEntryProcessor(value); map.SubmitToKey(key, entryProcessor); }); } [Test] public virtual void TestForceUnlock() { map.Lock("key1"); var latch = new CountdownEvent(1); var t1 = new Thread(delegate(object o) { map.ForceUnlock("key1"); latch.Signal(); }); t1.Start(); Assert.IsTrue(latch.Wait(TimeSpan.FromSeconds(100))); Assert.IsFalse(map.IsLocked("key1")); } [Test] public virtual void TestGet() { FillMap(); for (var i = 0; i < 10; i++) { var o = map.Get("key" + i); Assert.AreEqual("value" + i, o); } } [Test] public virtual void TestGetAllExtreme() { IDictionary<object, object> mm = new Dictionary<object, object>(); const int keycount = 1000; //insert dummy keys and values foreach (var itemIndex in Enumerable.Range(0, keycount)) { mm.Add(itemIndex.ToString(), itemIndex.ToString()); } map.PutAll(mm); Assert.AreEqual(map.Size(), keycount); var dictionary = map.GetAll(mm.Keys); Assert.AreEqual(dictionary.Count, keycount); } [Test] public virtual void TestGetAllPutAll() { IDictionary<object, object> mm = new Dictionary<object, object>(); for (var i = 0; i < 100; i++) { mm.Add(i, i); } map.PutAll(mm); Assert.AreEqual(map.Size(), 100); for (var i_1 = 0; i_1 < 100; i_1++) { Assert.AreEqual(map.Get(i_1), i_1); } var ss = new HashSet<object> {1, 3}; var m2 = map.GetAll(ss); Assert.AreEqual(m2.Count, 2); object gv; m2.TryGetValue(1, out gv); Assert.AreEqual(gv, 1); m2.TryGetValue(3, out gv); Assert.AreEqual(gv, 3); } [Test] public virtual void TestGetEntryView() { map.Put("item0", "value0"); map.Put("item1", "value1"); map.Put("item2", "value2"); var entryView = map.GetEntryView("item1"); Assert.AreEqual(0, entryView.GetHits()); Assert.AreEqual("item1", entryView.GetKey()); Assert.AreEqual("value1", entryView.GetValue()); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestIsEmpty() { Assert.IsTrue(map.IsEmpty()); map.Put("key1", "value1"); Assert.IsFalse(map.IsEmpty()); } [Test] public virtual void TestKeySet() { map.Put("key1", "value1"); var keySet = map.KeySet(); var enumerator = keySet.GetEnumerator(); enumerator.MoveNext(); Assert.AreEqual("key1", enumerator.Current); } [Test] public void TestKeySetPredicate() { FillMap(); var values = map.KeySet(new SqlPredicate("this == value1")); Assert.AreEqual(1, values.Count); var enumerator = values.GetEnumerator(); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual("key1", enumerator.Current); } [Test] public void TestListener() { var latch1Add = new CountdownEvent(5); var latch1Remove = new CountdownEvent(2); var latch2Add = new CountdownEvent(1); var latch2Remove = new CountdownEvent(1); var listener1 = new EntryAdapter<object, object>( delegate { latch1Add.Signal(); }, delegate { latch1Remove.Signal(); }, delegate { }, delegate { }); var listener2 = new EntryAdapter<object, object>( delegate { latch2Add.Signal(); }, delegate { latch2Remove.Signal(); }, delegate { }, delegate { }); var reg1 = map.AddEntryListener(listener1, false); var reg2 = map.AddEntryListener(listener2, "key3", true); map.Put("key1", "value1"); map.Put("key2", "value2"); map.Put("key3", "value3"); map.Put("key4", "value4"); map.Put("key5", "value5"); map.Remove("key1"); map.Remove("key3"); Assert.IsTrue(latch1Add.Wait(TimeSpan.FromSeconds(10))); Assert.IsTrue(latch1Remove.Wait(TimeSpan.FromSeconds(10))); Assert.IsTrue(latch2Add.Wait(TimeSpan.FromSeconds(5))); Assert.IsTrue(latch2Remove.Wait(TimeSpan.FromSeconds(5))); Assert.IsTrue(map.RemoveEntryListener(reg1)); Assert.IsTrue(map.RemoveEntryListener(reg2)); } [Test] public void TestListener_SingleEventListeners() { var listener = new ListenerImpl<object, object>(); var reg1 = map.AddEntryListener(listener, false); map.Put("key1", "value1"); Assert.IsTrue(listener.GetLatch(EntryEventType.Added).WaitOne(TimeSpan.FromSeconds(10))); map.Put("key1", "value2"); Assert.IsTrue(listener.GetLatch(EntryEventType.Updated).WaitOne(TimeSpan.FromSeconds(10))); map.Remove("key1"); Assert.IsTrue(listener.GetLatch(EntryEventType.Removed).WaitOne(TimeSpan.FromSeconds(10))); map.Put("key1", "value2"); map.Clear(); Assert.IsTrue(listener.GetLatch(EntryEventType.ClearAll).WaitOne(TimeSpan.FromSeconds(10))); map.Put("key1", "value2"); map.EvictAll(); Assert.IsTrue(listener.GetLatch(EntryEventType.EvictAll).WaitOne(TimeSpan.FromSeconds(10))); map.Put("key2", "value2"); map.Evict("key2"); Assert.IsTrue(listener.GetLatch(EntryEventType.Evicted).WaitOne(TimeSpan.FromSeconds(10))); map.Put("key3", "value2", 1L, TimeUnit.Seconds); Assert.IsTrue(listener.GetLatch(EntryEventType.Expired).WaitOne(TimeSpan.FromSeconds(10))); Assert.IsTrue(map.RemoveEntryListener(reg1)); } [Test] public void TestListenerClearAll() { var latchClearAll = new CountdownEvent(1); var listener1 = new EntryAdapter<object, object>( delegate { }, delegate { }, delegate { }, delegate { }, delegate { }, delegate { latchClearAll.Signal(); }); var reg1 = map.AddEntryListener(listener1, false); map.Put("key1", "value1"); map.Clear(); Assert.IsTrue(latchClearAll.Wait(TimeSpan.FromSeconds(15))); } [Test] public void TestListenerEventOrder() { const int maxSize = 10000; var map2 = Client.GetMap<int, int>(TestSupport.RandomString()); map2.Put(1, 0); var eventDataReceived = new Queue<int>(); var listener = new EntryAdapter<int, int>( e => { }, e => { }, e => { var value = e.GetValue(); eventDataReceived.Enqueue(value); }, e => { }); map2.AddEntryListener(listener, true); for (var i = 1; i < maxSize; i++) { map2.Put(1, i); } TestSupport.AssertTrueEventually(() => Assert.AreEqual(maxSize - 1, eventDataReceived.Count)); var oldEventData = -1; foreach (var eventData in eventDataReceived) { Assert.Less(oldEventData, eventData); oldEventData = eventData; } } [Test] public void TestListenerExtreme() { const int TestItemCount = 1 * 1000; var latch = new CountdownEvent(TestItemCount); var listener = new EntryAdapter<object, object>( delegate { }, delegate { latch.Signal(); }, delegate { }, delegate { }); for (var i = 0; i < TestItemCount; i++) { map.Put("key" + i, new[] {byte.MaxValue}); } Assert.AreEqual(map.Size(), TestItemCount); for (var i = 0; i < TestItemCount; i++) { map.AddEntryListener(listener, "key" + i, false); } for (var i = 0; i < TestItemCount; i++) { var o = map.RemoveAsync("key" + i).Result; } latch.Wait(TimeSpan.FromSeconds(10)); //Console.WriteLine(latch.CurrentCount); latch.Wait(TimeSpan.FromSeconds(10)); //Console.WriteLine(latch.CurrentCount); latch.Wait(TimeSpan.FromSeconds(10)); //Console.WriteLine(latch.CurrentCount); latch.Wait(TimeSpan.FromSeconds(10)); //Console.WriteLine(latch.CurrentCount); latch.Wait(TimeSpan.FromSeconds(10)); //Console.WriteLine(latch.CurrentCount); latch.Wait(TimeSpan.FromSeconds(10)); //Console.WriteLine(latch.CurrentCount); latch.Wait(TimeSpan.FromSeconds(10)); //Console.WriteLine(latch.CurrentCount); Assert.True(latch.Wait(TimeSpan.FromSeconds(100))); } [Test] public void TestListenerPredicate() { var latch1Add = new CountdownEvent(1); var latch1Remove = new CountdownEvent(1); var latch2Add = new CountdownEvent(1); var latch2Remove = new CountdownEvent(1); var listener1 = new EntryAdapter<object, object>( delegate { latch1Add.Signal(); }, delegate { latch1Remove.Signal(); }, delegate { }, delegate { }); var listener2 = new EntryAdapter<object, object>( delegate { latch2Add.Signal(); }, delegate { latch2Remove.Signal(); }, delegate { }, delegate { }); map.AddEntryListener(listener1, new SqlPredicate("this == value1"), false); map.AddEntryListener(listener2, new SqlPredicate("this == value3"), "key3", true); map.Put("key1", "value1"); map.Put("key2", "value2"); map.Put("key3", "value3"); map.Put("key4", "value4"); map.Put("key5", "value5"); map.Remove("key1"); map.Remove("key3"); Assert.IsTrue(latch1Add.Wait(TimeSpan.FromSeconds(10))); Assert.IsTrue(latch1Remove.Wait(TimeSpan.FromSeconds(10))); Assert.IsTrue(latch2Add.Wait(TimeSpan.FromSeconds(5))); Assert.IsTrue(latch2Remove.Wait(TimeSpan.FromSeconds(5))); } [Test] public void TestListenerRemove() { var latch1Add = new CountdownEvent(1); var listener1 = new EntryAdapter<object, object>( delegate { latch1Add.Signal(); }, delegate { }, delegate { }, delegate { }); var reg1 = map.AddEntryListener(listener1, false); Assert.IsTrue(map.RemoveEntryListener(reg1)); map.Put("key1", "value1"); Assert.IsFalse(latch1Add.Wait(TimeSpan.FromSeconds(1))); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestLock() { map.Put("key1", "value1"); Assert.AreEqual("value1", map.Get("key1")); map.Lock("key1"); var latch = new CountdownEvent(1); var t1 = new Thread(delegate(object o) { map.TryPut("key1", "value2", 1, TimeUnit.Seconds); latch.Signal(); }); t1.Start(); Assert.IsTrue(latch.Wait(TimeSpan.FromSeconds(5))); Assert.AreEqual("value1", map.Get("key1")); map.ForceUnlock("key1"); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestLockTtl() { map.Put("key1", "value1"); Assert.AreEqual("value1", map.Get("key1")); var leaseTime = 500; map.Lock("key1", leaseTime, TimeUnit.Milliseconds); var latch = new CountdownEvent(1); var t1 = new Thread(delegate(object o) { map.TryPut("key1", "value2", 2000, TimeUnit.Milliseconds); latch.Signal(); }); t1.Start(); Assert.IsTrue(latch.Wait(TimeSpan.FromSeconds(10))); Assert.IsFalse(map.IsLocked("key1")); Assert.AreEqual("value2", map.Get("key1")); map.ForceUnlock("key1"); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestLockTtl2() { map.Lock("key1", 1, TimeUnit.Seconds); var latch = new CountdownEvent(2); var t1 = new Thread(delegate(object o) { if (!map.TryLock("key1")) { latch.Signal(); } try { if (map.TryLock("key1", 2, TimeUnit.Seconds)) { latch.Signal(); } } catch { } }); t1.Start(); Assert.IsTrue(latch.Wait(TimeSpan.FromSeconds(10))); map.ForceUnlock("key1"); } [Test] public virtual void TestPutBigData() { const int dataSize = 128000; var largeString = string.Join(",", Enumerable.Range(0, dataSize)); map.Put("large_value", largeString); Assert.AreEqual(map.Size(), 1); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestPutIfAbsent() { Assert.IsNull(map.PutIfAbsent("key1", "value1")); Assert.AreEqual("value1", map.PutIfAbsent("key1", "value3")); } [Test] public void TestPutIfAbsentNewValueTTL_whenKeyPresent() { object key = "Key"; object value = "Value"; object newValue = "newValue"; map.Put(key, value); var result = map.PutIfAbsent(key, newValue, 5, TimeUnit.Minutes); Assert.AreEqual(value, result); Assert.AreEqual(value, map.Get(key)); } [Test] public void TestPutIfAbsentTtl() { object key = "Key"; object value = "Value"; var result = map.PutIfAbsent(key, value, 5, TimeUnit.Minutes); Assert.AreEqual(null, result); Assert.AreEqual(value, map.Get(key)); } [Test] public void TestPutIfAbsentTTL_whenExpire() { object key = "Key"; object value = "Value"; var ttl = 100; var result = map.PutIfAbsent(key, value, ttl, TimeUnit.Milliseconds); TestSupport.AssertTrueEventually(() => { Assert.AreEqual(null, result); Assert.AreEqual(null, map.Get(key)); }); } [Test] public void TestPutIfAbsentTTL_whenKeyPresent() { object key = "Key"; object value = "Value"; map.Put(key, value); var result = map.PutIfAbsent(key, value, 5, TimeUnit.Minutes); Assert.AreEqual(value, result); Assert.AreEqual(value, map.Get(key)); } [Test] public void TestPutIfAbsentTTL_whenKeyPresentAfterExpire() { object key = "Key"; object value = "Value"; map.Put(key, value); var result = map.PutIfAbsent(key, value, 1, TimeUnit.Seconds); Assert.AreEqual(value, result); Assert.AreEqual(value, map.Get(key)); } [Test] public virtual void TestPutTransient() { Assert.AreEqual(0, map.Size()); map.PutTransient("key1", "value1", 100, TimeUnit.Milliseconds); Assert.AreEqual("value1", map.Get("key1")); TestSupport.AssertTrueEventually(() => { Assert.AreNotEqual("value1", map.Get("key1")); }); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestPutTtl() { var ttl = 100; map.Put("key1", "value1", ttl, TimeUnit.Milliseconds); Assert.IsNotNull(map.Get("key1")); TestSupport.AssertTrueEventually(() => { Assert.IsNull(map.Get("key1")); }); } [Test] public virtual void TestRemoveAndDelete() { FillMap(); Assert.IsNull(map.Remove("key10")); map.Delete("key9"); Assert.AreEqual(9, map.Size()); for (var i = 0; i < 9; i++) { var o = map.Remove("key" + i); Assert.AreEqual("value" + i, o); } Assert.AreEqual(0, map.Size()); } [Test] public virtual void TestRemoveIfSame() { FillMap(); Assert.IsFalse(map.Remove("key2", "value")); Assert.AreEqual(10, map.Size()); Assert.IsTrue(map.Remove("key2", "value2")); Assert.AreEqual(9, map.Size()); } [Test] public void TestRemoveInterceptor() { map.RemoveInterceptor("interceptor"); } [Test] [Category("3.8")] public void TestRemoveAllWithPredicate() { FillMap(); map.RemoveAll(new SqlPredicate("this != value1")); Assert.AreEqual(1, map.Values().Count); Assert.AreEqual("value1", map.Get("key1")); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestReplace() { Assert.IsNull(map.Replace("key1", "value1")); map.Put("key1", "value1"); Assert.AreEqual("value1", map.Replace("key1", "value2")); Assert.AreEqual("value2", map.Get("key1")); Assert.IsFalse(map.Replace("key1", "value1", "value3")); Assert.AreEqual("value2", map.Get("key1")); Assert.IsTrue(map.Replace("key1", "value2", "value3")); Assert.AreEqual("value3", map.Get("key1")); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestSet() { map.Set("key1", "value1"); Assert.AreEqual("value1", map.Get("key1")); map.Set("key1", "value2"); Assert.AreEqual("value2", map.Get("key1")); map.Set("key1", "value3", 100, TimeUnit.Milliseconds); Assert.AreEqual("value3", map.Get("key1")); TestSupport.AssertTrueEventually(() => Assert.IsNull(map.Get("key1"))); } /// <exception cref="System.Exception"></exception> [Test] public virtual void TestTryPutRemove() { Assert.IsTrue(map.TryPut("key1", "value1", 1, TimeUnit.Seconds)); Assert.IsTrue(map.TryPut("key2", "value2", 1, TimeUnit.Seconds)); map.Lock("key1"); map.Lock("key2"); var latch = new CountdownEvent(2); var t1 = new Thread(delegate(object o) { var result = map.TryPut("key1", "value3", 1, TimeUnit.Seconds); if (!result) { latch.Signal(); } }); var t2 = new Thread(delegate(object o) { var result = map.TryRemove("key2", 1, TimeUnit.Seconds); if (!result) { latch.Signal(); } }); t1.Start(); t2.Start(); Assert.IsTrue(latch.Wait(TimeSpan.FromSeconds(20))); Assert.AreEqual("value1", map.Get("key1")); Assert.AreEqual("value2", map.Get("key2")); map.ForceUnlock("key1"); map.ForceUnlock("key2"); } [Test] public virtual void TestUnlock() { map.ForceUnlock("key1"); map.Put("key1", "value1"); Assert.AreEqual("value1", map.Get("key1")); map.Lock("key1"); Assert.IsTrue(map.IsLocked("key1")); map.Unlock("key1"); Assert.IsFalse(map.IsLocked("key1")); map.ForceUnlock("key1"); } [Test] public virtual void TestValues() { map.Put("key1", "value1"); var values = map.Values(); var enumerator = values.GetEnumerator(); enumerator.MoveNext(); Assert.AreEqual("value1", enumerator.Current); } [Test] public void TestValuesPredicate() { FillMap(); var values = map.Values(new SqlPredicate("this == value1")); Assert.AreEqual(1, values.Count); var enumerator = values.GetEnumerator(); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual("value1", enumerator.Current); } private class ListenerImpl<TKey, TValue> : EntryAddedListener<TKey, TValue>, EntryUpdatedListener<TKey, TValue>, EntryRemovedListener<TKey, TValue>, EntryEvictedListener<TKey, TValue>, MapClearedListener, MapEvictedListener, EntryMergedListener<TKey, TValue>, EntryExpiredListener<TKey, TValue> { private readonly ConcurrentDictionary<EntryEventType, AutoResetEvent> latches; public ListenerImpl() { latches = new ConcurrentDictionary<EntryEventType, AutoResetEvent>(); foreach (EntryEventType et in Enum.GetValues(typeof(EntryEventType))) { latches.TryAdd(et, new AutoResetEvent(false)); } } public void EntryAdded(EntryEvent<TKey, TValue> @event) { latches[EntryEventType.Added].Set(); } public void EntryUpdated(EntryEvent<TKey, TValue> @event) { latches[EntryEventType.Updated].Set(); } public void EntryRemoved(EntryEvent<TKey, TValue> @event) { latches[EntryEventType.Removed].Set(); } public void EntryEvicted(EntryEvent<TKey, TValue> @event) { latches[EntryEventType.Evicted].Set(); } public void MapCleared(MapEvent @event) { latches[EntryEventType.ClearAll].Set(); } public void MapEvicted(MapEvent @event) { latches[EntryEventType.EvictAll].Set(); } public void EntryMerged(EntryEvent<TKey, TValue> @event) { latches[EntryEventType.Merged].Set(); } public void EntryExpired(EntryEvent<TKey, TValue> @event) { latches[EntryEventType.Expired].Set(); } public AutoResetEvent GetLatch(EntryEventType key) { return latches[key]; } } } }
using System; using System.Windows.Forms; using System.Reflection; using System.IO; namespace SpiffCode { /// <summary> /// Summary description for Globals. /// </summary> public class Globals { private static AnimDoc s_doc; private static Strip s_stpActive = null; private static int s_ifrActive = 0; private static int s_cfrActive = 1; private static int s_msFrameRate = 80; private static int s_nPreviewScale = 4; private static int s_nStripScale = 1; private static bool s_fSideColorMappingOn = true; private static bool s_fGridOn = true; private static bool s_fShowOriginPoint = false; private static bool s_fShowSpecialPoint = false; private static AnimDoc s_docNull; private static Control s_ctlStrip; private static Control s_ctlPreview; private static Form s_frmStrips; private static Form s_frmStrip; private static Form s_frmMain; private static Cursor s_crsrHand; private static Cursor s_crsrGrab; private static int s_nTileSize = 32; private static int s_cxGrid = 32; private static int s_cyGrid = 32; public static event EventHandler ActiveDocumentChanged; public static AnimDoc ActiveDocument { get { return s_doc; } set { // Keep track of the ActiveDoc's ActiveStrip if (s_doc != null) s_doc.ActiveStripChanged -= new EventHandler(OnActiveStripChanged); s_doc = value; if (ActiveDocumentChanged != null) ActiveDocumentChanged(null, EventArgs.Empty); ActiveStrip = s_doc == null ? null : s_doc.ActiveStrip; if (s_doc != null) s_doc.ActiveStripChanged += new EventHandler(OnActiveStripChanged); } } private static void OnActiveStripChanged(object obSender, EventArgs e) { ActiveStrip = s_doc.ActiveStrip; } public static event EventHandler ActiveStripChanged; public static Strip ActiveStrip { get { return s_stpActive; } set { // Keep track of the ActiveStrip's ActiveFrame if (s_stpActive != null) { s_stpActive.ActiveFrameChanged -= new EventHandler(OnActiveFrameChanged); s_stpActive.ActiveFrameCountChanged -= new EventHandler(OnActiveFrameCountChanged); } s_stpActive = value; if (ActiveStripChanged != null) ActiveStripChanged(null, EventArgs.Empty); ActiveFrame = s_stpActive == null ? 0 : s_stpActive.ActiveFrame; if (s_stpActive != null) { s_stpActive.ActiveFrameChanged += new EventHandler(OnActiveFrameChanged); s_stpActive.ActiveFrameCountChanged += new EventHandler(OnActiveFrameCountChanged); } } } private static void OnActiveFrameChanged(object obSender, EventArgs e) { ActiveFrame = s_stpActive.ActiveFrame; } private static void OnActiveFrameCountChanged(object obSender, EventArgs e) { ActiveFrameCount = s_stpActive.ActiveFrameCount; } public static event EventHandler ActiveFrameChanged; public static int ActiveFrame { get { return s_ifrActive; } set { s_ifrActive = value; if (ActiveFrameChanged != null) ActiveFrameChanged(null, EventArgs.Empty); } } public static event EventHandler ActiveFrameCountChanged; public static int ActiveFrameCount { get { return s_cfrActive; } set { s_cfrActive = value; if (ActiveFrameCountChanged != null) ActiveFrameCountChanged(null, EventArgs.Empty); } } public static int FrameRate { get { return s_msFrameRate; } set { s_msFrameRate = value; } } public static event EventHandler GridChanged; public static bool GridOn { get { return s_fGridOn; } set { s_fGridOn = value; if (GridChanged != null) GridChanged(null, EventArgs.Empty); } } public static int GridWidth { get { return s_cxGrid; } set { s_cxGrid = value; if (GridChanged != null) GridChanged(null, EventArgs.Empty); } } public static int GridHeight { get { return s_cyGrid; } set { s_cyGrid = value; if (GridChanged != null) GridChanged(null, EventArgs.Empty); } } public static event EventHandler TileSizeChanged; public static int TileSize { set { s_nTileSize = value; GridWidth = s_nTileSize; GridHeight = s_nTileSize; if (s_nTileSize < 24) { StripScale = 2; } else { StripScale = 1; } if (TileSizeChanged != null) TileSizeChanged(null, EventArgs.Empty); } get { return s_nTileSize; } } public static Cursor HandCursor { get { if (s_crsrHand == null) { Assembly ass = Assembly.GetAssembly(typeof(Globals)); // string[] astr = ass.GetManifestResourceNames(); Stream stm = ass.GetManifestResourceStream("SpiffCode.Resources.hand.cur"); s_crsrHand = new Cursor(stm); stm.Close(); } return s_crsrHand; } } public static Cursor GrabCursor { get { if (s_crsrGrab == null) { Assembly ass = Assembly.GetAssembly(typeof(Globals)); Stream stm = ass.GetManifestResourceStream("SpiffCode.Resources.grab.cur"); s_crsrGrab = new Cursor(stm); stm.Close(); } return s_crsrGrab; } } public static event EventHandler SideColorMappingOnChanged; public static bool SideColorMappingOn { get { return s_fSideColorMappingOn; } set { s_fSideColorMappingOn = value; if (SideColorMappingOnChanged != null) SideColorMappingOnChanged(null, EventArgs.Empty); } } public static event EventHandler ShowOriginPointChanged; public static bool ShowOriginPoint { get { return s_fShowOriginPoint; } set { s_fShowOriginPoint = value; if (ShowOriginPointChanged != null) ShowOriginPointChanged(null, EventArgs.Empty); } } public static event EventHandler ShowSpecialPointChanged; public static bool ShowSpecialPoint { get { return s_fShowSpecialPoint; } set { s_fShowSpecialPoint = value; if (ShowSpecialPointChanged != null) ShowSpecialPointChanged(null, EventArgs.Empty); } } public static event EventHandler PreviewScaleChanged; public static int PreviewScale { get { return s_nPreviewScale; } set { s_nPreviewScale = value; if (PreviewScaleChanged != null) PreviewScaleChanged(null, EventArgs.Empty); } } public static event EventHandler StripScaleChanged; public static int StripScale { get { return s_nStripScale; } set { s_nStripScale = value; if (StripScaleChanged != null) StripScaleChanged(null, EventArgs.Empty); } } public static AnimDoc NullDocument { get { return s_docNull; } set { s_docNull = value; } } public static Control StripControl { get { return s_ctlStrip; } set { s_ctlStrip = value; } } public static Control PreviewControl { get { return s_ctlPreview; } set { s_ctlPreview = value; } } public static Form StripsForm { get { return s_frmStrips; } set { s_frmStrips = value; } } public static Form StripForm { get { return s_frmStrip; } set { s_frmStrip = value; } } public static Form MainForm { get { return s_frmMain; } set { s_frmMain = value; } } public static event KeyPressEventHandler KeyPress; // UNDONE: this will send to every handler even after one has handled // the event. public static void OnKeyPress(Object sender, KeyPressEventArgs e) { if (KeyPress != null) KeyPress(sender, e); } public static event KeyEventHandler KeyDown; public static void OnKeyDown(Object sender, KeyEventArgs e) { if (KeyDown != null) KeyDown(sender, e); } public static event KeyEventHandler KeyUp; public static void OnKeyUp(Object sender, KeyEventArgs e) { if (KeyUp != null) KeyUp(sender, e); } public static event EventHandler FrameContentChanged; // UNDONE: this will send to every handler even after one has handled // the event. public static void OnFrameContentChanged(Object sender, EventArgs e) { if (FrameContentChanged != null) FrameContentChanged(sender, e); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace UnitTests.General { [TestCategory("Elasticity"), TestCategory("Placement")] public class ElasticPlacementTests : TestClusterPerTest { private readonly List<IActivationCountBasedPlacementTestGrain> grains = new List<IActivationCountBasedPlacementTestGrain>(); private const int leavy = 300; private const int perSilo = 1000; protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.ConfigureLegacyConfiguration(legacy => { legacy.ClusterConfiguration.ApplyToAllNodes(nodeConfig => nodeConfig.LoadSheddingEnabled = true); }); builder.AddSiloBuilderConfigurator<SiloConfigurator>(); } private class SiloConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddMemoryGrainStorage("MemoryStore") .AddMemoryGrainStorageAsDefault(); } } /// <summary> /// Test placement behaviour for newly added silos. The grain placement strategy should favor them /// until they reach a similar load as the other silos. /// </summary> [SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")] public async Task ElasticityTest_CatchingUp() { logger.Info("\n\n\n----- Phase 1 -----\n\n"); AddTestGrains(perSilo).Wait(); AddTestGrains(perSilo).Wait(); var activationCounts = await GetPerSiloActivationCounts(); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); AssertIsInRange(activationCounts[this.HostedCluster.Primary], perSilo, leavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], perSilo, leavy); SiloHandle silo3 = this.HostedCluster.StartAdditionalSilo(); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); logger.Info("\n\n\n----- Phase 2 -----\n\n"); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); logger.Info("-----------------------------------------------------------------"); activationCounts = await GetPerSiloActivationCounts(); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); double expected = (6.0 * perSilo) / 3.0; AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, leavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, leavy); AssertIsInRange(activationCounts[silo3], expected, leavy); logger.Info("\n\n\n----- Phase 3 -----\n\n"); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); logger.Info("-----------------------------------------------------------------"); activationCounts = await GetPerSiloActivationCounts(); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); expected = (9.0 * perSilo) / 3.0; AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, leavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, leavy); AssertIsInRange(activationCounts[silo3], expected, leavy); logger.Info("-----------------------------------------------------------------"); logger.Info("Test finished OK. Expected per silo = {0}", expected); } /// <summary> /// This evaluates the how the placement strategy behaves once silos are stopped: The strategy should /// balance the activations from the stopped silo evenly among the remaining silos. /// </summary> [SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")] public async Task ElasticityTest_StoppingSilos() { List<SiloHandle> runtimes = await this.HostedCluster.StartAdditionalSilos(2); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); int stopLeavy = leavy; await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); var activationCounts = await GetPerSiloActivationCounts(); logger.Info("-----------------------------------------------------------------"); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); AssertIsInRange(activationCounts[this.HostedCluster.Primary], perSilo, stopLeavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], perSilo, stopLeavy); AssertIsInRange(activationCounts[runtimes[0]], perSilo, stopLeavy); AssertIsInRange(activationCounts[runtimes[1]], perSilo, stopLeavy); this.HostedCluster.StopSilo(runtimes[0]); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); await InvokeAllGrains(); activationCounts = await GetPerSiloActivationCounts(); logger.Info("-----------------------------------------------------------------"); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); double expected = perSilo * 1.33; AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, stopLeavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, stopLeavy); AssertIsInRange(activationCounts[runtimes[1]], expected, stopLeavy); logger.Info("-----------------------------------------------------------------"); logger.Info("Test finished OK. Expected per silo = {0}", expected); } /// <summary> /// Do not place activation in case all silos are above 110 CPU utilization. /// </summary> [SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")] public async Task ElasticityTest_AllSilosCPUTooHigh() { var taintedGrainPrimary = await GetGrainAtSilo(this.HostedCluster.Primary.SiloAddress); var taintedGrainSecondary = await GetGrainAtSilo(this.HostedCluster.SecondarySilos.First().SiloAddress); await taintedGrainPrimary.EnableOverloadDetection(false); await taintedGrainSecondary.EnableOverloadDetection(false); await taintedGrainPrimary.LatchCpuUsage(110.0f); await taintedGrainSecondary.LatchCpuUsage(110.0f); await Assert.ThrowsAsync<OrleansException>(() => this.AddTestGrains(1)); } /// <summary> /// Do not place activation in case all silos are above 110 CPU utilization or have overloaded flag set. /// </summary> [SkippableFact(Skip= "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")] public async Task ElasticityTest_AllSilosOverloaded() { var taintedGrainPrimary = await GetGrainAtSilo(this.HostedCluster.Primary.SiloAddress); var taintedGrainSecondary = await GetGrainAtSilo(this.HostedCluster.SecondarySilos.First().SiloAddress); await taintedGrainPrimary.LatchCpuUsage(110.0f); await taintedGrainSecondary.LatchOverloaded(); // OrleansException or GateWayTooBusyException var exception = await Assert.ThrowsAnyAsync<Exception>(() => this.AddTestGrains(1)); Assert.True(exception is OrleansException || exception is GatewayTooBusyException); } [Fact, TestCategory("Functional")] public async Task LoadAwareGrainShouldNotAttemptToCreateActivationsOnOverloadedSilo() { await ElasticityGrainPlacementTest( g => g.LatchOverloaded(), g => g.UnlatchOverloaded(), "LoadAwareGrainShouldNotAttemptToCreateActivationsOnOverloadedSilo", "A grain instantiated with the load-aware placement strategy should not attempt to create activations on an overloaded silo."); } [Fact, TestCategory("Functional")] public async Task LoadAwareGrainShouldNotAttemptToCreateActivationsOnBusySilos() { // a CPU usage of 110% will disqualify a silo from getting new grains. const float undesirability = (float)110.0; await ElasticityGrainPlacementTest( g => g.LatchCpuUsage(undesirability), g => g.UnlatchCpuUsage(), "LoadAwareGrainShouldNotAttemptToCreateActivationsOnBusySilos", "A grain instantiated with the load-aware placement strategy should not attempt to create activations on a busy silo."); } private async Task<IPlacementTestGrain> GetGrainAtSilo(SiloAddress silo) { while (true) { IPlacementTestGrain grain = this.GrainFactory.GetGrain<IRandomPlacementTestGrain>(Guid.NewGuid()); SiloAddress address = await grain.GetLocation(); if (address.Equals(silo)) return grain; } } private static void AssertIsInRange(int actual, double expected, int leavy) { Assert.True(expected - leavy <= actual && actual <= expected + leavy, String.Format("Expecting a value in the range between {0} and {1}, but instead got {2} outside the range.", expected - leavy, expected + leavy, actual)); } private async Task ElasticityGrainPlacementTest( Func<IPlacementTestGrain, Task> taint, Func<IPlacementTestGrain, Task> restore, string name, string assertMsg) { await this.HostedCluster.WaitForLivenessToStabilizeAsync(); logger.Info("********************** Starting the test {0} ******************************", name); var taintedSilo = this.HostedCluster.StartAdditionalSilo(); const long sampleSize = 10; var taintedGrain = await GetGrainAtSilo(taintedSilo.SiloAddress); var testGrains = Enumerable.Range(0, (int)sampleSize). Select( n => this.GrainFactory.GetGrain<IActivationCountBasedPlacementTestGrain>(Guid.NewGuid())); // make the grain's silo undesirable for new grains. taint(taintedGrain).Wait(); List<IPEndPoint> actual; try { actual = testGrains.Select( g => g.GetEndpoint().Result).ToList(); } finally { // i don't know if this necessary but to be safe, i'll restore the silo's desirability. logger.Info("********************** Finalizing the test {0} ******************************", name); restore(taintedGrain).Wait(); } var unexpected = taintedSilo.SiloAddress.Endpoint; Assert.True( actual.All( i => !i.Equals(unexpected)), assertMsg); } private Task AddTestGrains(int amount) { var promises = new List<Task>(); for (var i = 0; i < amount; i++) { IActivationCountBasedPlacementTestGrain grain = this.GrainFactory.GetGrain<IActivationCountBasedPlacementTestGrain>(Guid.NewGuid()); this.grains.Add(grain); // Make sure we activate grain: promises.Add(grain.Nop()); } return Task.WhenAll(promises); } private Task InvokeAllGrains() { var promises = new List<Task>(); foreach (var grain in grains) { promises.Add(grain.Nop()); } return Task.WhenAll(promises); } private async Task<Dictionary<SiloHandle, int>> GetPerSiloActivationCounts() { string fullTypeName = "UnitTests.Grains.ActivationCountBasedPlacementTestGrain"; IManagementGrain mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0); SimpleGrainStatistic[] stats = await mgmtGrain.GetSimpleGrainStatistics(); return this.HostedCluster.GetActiveSilos() .ToDictionary( s => s, s => stats .Where(stat => stat.SiloAddress.Equals(s.SiloAddress) && stat.GrainType == fullTypeName) .Select(stat => stat.ActivationCount).SingleOrDefault()); } private void LogCounts(Dictionary<SiloHandle, int> activationCounts) { var sb = new StringBuilder(); foreach (var silo in this.HostedCluster.GetActiveSilos()) { int count; activationCounts.TryGetValue(silo, out count); sb.AppendLine($"{silo.Name}.ActivationCount = {count}"); } logger.Info(sb.ToString()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections.Generic; using System.Linq; namespace Test { public class ThenByTests { // // Thenby // [Fact] public static void RunThenByTests() { // Simple Thenby tests. RunThenByTest1(1024 * 128, false); RunThenByTest1(1024 * 128, true); RunThenByTest2(1024 * 128, false); RunThenByTest2(1024 * 128, true); } [Fact] public static void RunThenByComposedWithTests() { // composition tests (WHERE, WHERE/WHERE, WHERE/SELECT). RunThenByComposedWithWhere1(1024 * 128, false); RunThenByComposedWithWhere1(1024 * 128, true); RunThenByComposedWithJoinJoin(32, 32, false); RunThenByComposedWithJoinJoin(32, 32, true); RunThenByComposedWithWhereWhere1(1024 * 128, false); RunThenByComposedWithWhereWhere1(1024 * 128, true); RunThenByComposedWithWhereSelect1(1024 * 128, false); RunThenByComposedWithWhereSelect1(1024 * 128, true); } // To-do: Re-enable this long-running test as an outer-loop test // [Fact] public static void RunThenByComposedWithJoinJoinTests_LongRunning() { RunThenByComposedWithJoinJoin(1024 * 512, 1024 * 128, false); RunThenByComposedWithJoinJoin(1024 * 512, 1024 * 128, true); } [Fact] public static void RunThenByTestRecursive() { // Multiple levels. RunThenByTestRecursive1(8, false); RunThenByTestRecursive1(1024 * 128, false); RunThenByTestRecursive1(1024 * 128, true); RunThenByTestRecursive2(1024 * 128, false); RunThenByTestRecursive2(1024 * 128, true); } private static void RunThenByTest1(int dataSize, bool descending) { //Random rand = new Random(); // We sort on a very dense (lots of dups) set of ints first, and then // a more volatile set, to ensure we end up stressing secondary sort logic. Pair<int, int>[] pairs = new Pair<int, int>[dataSize]; var rangeNumbers = Enumerable.Range(0, (dataSize / 250)).ToList(); if (rangeNumbers.Count == 0) rangeNumbers.Add(0); for (int i = 0; i < dataSize; i++) { int index = i % rangeNumbers.Count; pairs[i].First = rangeNumbers[index]; pairs[i].Second = 10 - (i % 10); } ParallelQuery<Pair<int, int>> q; if (descending) { q = pairs.AsParallel().OrderByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } else { q = pairs.AsParallel<Pair<int, int>>().OrderBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } // Force synchronous execution before validating results. List<Pair<int, int>> r = q.ToList<Pair<int, int>>(); for (int i = 1; i < r.Count; i++) { if (CompareInts(r[i - 1].First, r[i].First, descending) == 0 && CompareInts(r[i - 1].Second, r[i].Second, descending) > 0) { string method = string.Format("RunThenByTest1(dataSize = {0}, descending = {1}) - synchronous/no pipeline", dataSize, descending); Assert.True(false, string.Format(method + " > **ERROR** {0}.{1} came before {2}.{3} -- but isn't what we expected", r[i - 1].First, r[i - 1].Second, r[i].First, r[i].Second)); } } } //----------------------------------------------------------------------------------- // Exercises basic OrderBy behavior by sorting a fixed set of integers. This always // uses asynchronous channels internally, i.e. by pipelining. // private static void RunThenByTest2(int dataSize, bool descending) { //Random rand = new Random(); // We sort on a very dense (lots of dups) set of ints first, and then // a more volatile set, to ensure we end up stressing secondary sort logic. Pair<int, int>[] pairs = new Pair<int, int>[dataSize]; var rangeNumbers = Enumerable.Range(0, (dataSize / 250)).ToList(); if (rangeNumbers.Count == 0) rangeNumbers.Add(0); for (int i = 0; i < dataSize; i++) { int index = i % rangeNumbers.Count; pairs[i].First = rangeNumbers[index]; pairs[i].Second = 10 - (i % 10); } ParallelQuery<Pair<int, int>> q; if (descending) { q = pairs.AsParallel<Pair<int, int>>().OrderByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }). ThenByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } else { q = pairs.AsParallel<Pair<int, int>>().OrderBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } List<Pair<int, int>> r = new List<Pair<int, int>>(); foreach (Pair<int, int> x in q) { r.Add(x); } for (int i = 1; i < r.Count; i++) { if (CompareInts(r[i - 1].First, r[i].First, descending) == 0 && CompareInts(r[i - 1].Second, r[i].Second, descending) > 0) { string method = string.Format("RunThenByTest2(dataSize = {0}, descending = {1}) - asynchronous/pipeline", dataSize, descending); Assert.True(false, string.Format(method + " > **ERROR** {0}.{1} came before {2}.{3} -- but isn't what we expected", r[i - 1].First, r[i - 1].Second, r[i].First, r[i].Second)); } } } //----------------------------------------------------------------------------------- // If sort is followed by another operator, we need to preserve key ordering all the // way back up to the merge. That is true even if some elements are missing in the // output data stream. This test tries to compose ORDERBY with WHERE. This test // processes output sequentially (not pipelined). // private static void RunThenByComposedWithWhere1(int dataSize, bool descending) { // We sort on a very dense (lots of dups) set of ints first, and then // a more volatile set, to ensure we end up stressing secondary sort logic. Pair<int, int>[] pairs = new Pair<int, int>[dataSize]; var rangeNumbers = Enumerable.Range(0, (dataSize / 250)).ToList(); if (rangeNumbers.Count == 0) rangeNumbers.Add(0); for (int i = 0; i < dataSize; i++) { int index = i % rangeNumbers.Count; pairs[i].First = rangeNumbers[index]; pairs[i].Second = 10 - (i % 10); } ParallelQuery<Pair<int, int>> q; // Create the ORDERBY: if (descending) { q = pairs.AsParallel<Pair<int, int>>() .OrderByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } else { q = pairs.AsParallel<Pair<int, int>>() .OrderBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } // Wrap with a WHERE: q = q.Where<Pair<int, int>>(delegate (Pair<int, int> x) { return (x.First % 2) == 0; }); // Force synchronous execution before validating results. List<Pair<int, int>> r = q.ToList<Pair<int, int>>(); for (int i = 1; i < r.Count; i++) { if (CompareInts(r[i - 1].First, r[i].First, descending) == 0 && CompareInts(r[i - 1].Second, r[i].Second, descending) > 0) { string method = string.Format("RunThenByComposedWithWhere1(dataSize = {0}, descending = {1}) - sequential/no pipeline", dataSize, descending); Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", r[i - 1], r[i])); } } } //----------------------------------------------------------------------------------- // If sort is followed by another operator, we need to preserve key ordering all the // way back up to the merge. That is true even if some elements are missing in the // output data stream. This test tries to compose ORDERBY with WHERE. This test // processes output asynchronously via pipelining. // private static void RunThenByComposedWithWhere2(int dataSize, bool descending) { // We sort on a very dense (lots of dups) set of ints first, and then // a more volatile set, to ensure we end up stressing secondary sort logic. Pair<int, int>[] pairs = new Pair<int, int>[dataSize]; var rangeNumbers = Enumerable.Range(0, (dataSize / 250)).ToList(); if (rangeNumbers.Count == 0) rangeNumbers.Add(0); for (int i = 0; i < dataSize; i++) { int index = i % rangeNumbers.Count; pairs[i].First = rangeNumbers[index]; pairs[i].Second = 10 - (i % 10); } ParallelQuery<Pair<int, int>> q; // Create the ORDERBY: if (descending) { q = pairs.AsParallel<Pair<int, int>>() .OrderByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } else { q = pairs.AsParallel<Pair<int, int>>() .OrderBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } // Wrap with a WHERE: q = q.Where<Pair<int, int>>(delegate (Pair<int, int> x) { return (x.First % 2) == 0; }); List<Pair<int, int>> r = new List<Pair<int, int>>(); foreach (Pair<int, int> x in q) r.Add(x); for (int i = 1; i < r.Count; i++) { if (CompareInts(r[i - 1].First, r[i].First, descending) == 0 && CompareInts(r[i - 1].Second, r[i].Second, descending) > 0) { string method = string.Format("RunThenByComposedWithWhere2(dataSize = {0}, descending = {1}) - async/pipeline", dataSize, descending); Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", r[i - 1], r[i])); } } } private static void RunThenByComposedWithJoinJoin(int outerSize, int innerSize, bool descending) { // Generate data in the reverse order in which it'll be sorted. DataDistributionType type = descending ? DataDistributionType.AlreadyAscending : DataDistributionType.AlreadyDescending; int[] leftPartOne = CreateOrderByInput(outerSize, type); int[] leftPartTwo = CreateOrderByInput(outerSize, DataDistributionType.Random); Pair<int, int>[] left = new Pair<int, int>[outerSize]; for (int i = 0; i < outerSize; i++) left[i] = new Pair<int, int>(leftPartOne[i] / 1024, leftPartTwo[i]); int[] right = CreateOrderByInput(innerSize, type); int minValue = outerSize >= innerSize ? innerSize : outerSize; int[] middle = new int[minValue]; if (descending) for (int i = middle.Length; i > 0; i--) middle[i - 1] = i; else for (int i = 0; i < middle.Length; i++) middle[i] = i; Func<int, int> identityKeySelector = delegate (int x) { return x; }; // Create the sort object. ParallelQuery<Pair<int, int>> sortedLeft; if (descending) { sortedLeft = left.AsParallel() .OrderByDescending<Pair<int, int>, int>(delegate (Pair<int, int> p) { return p.First; }) .ThenByDescending<Pair<int, int>, int>(delegate (Pair<int, int> p) { return p.Second; }); } else { sortedLeft = left.AsParallel() .OrderBy<Pair<int, int>, int>(delegate (Pair<int, int> p) { return p.First; }) .ThenBy<Pair<int, int>, int>(delegate (Pair<int, int> p) { return p.Second; }); } // and now the join... ParallelQuery<Pair<int, int>> innerJoin = sortedLeft.Join<Pair<int, int>, int, int, Pair<int, int>>( right.AsParallel(), delegate (Pair<int, int> p) { return p.First; }, identityKeySelector, delegate (Pair<int, int> x, int y) { return x; }); ParallelQuery<Pair<int, int>> outerJoin = innerJoin.Join<Pair<int, int>, int, int, Pair<int, int>>( middle.AsParallel(), delegate (Pair<int, int> p) { return p.First; }, identityKeySelector, delegate (Pair<int, int> x, int y) { return x; }); //Assert.True(false, string.Format(" > Invoking join of {0} outer elems with {1} inner elems", left.Length, right.Length)); // Ensure pairs are of equal values, and that they are in ascending or descending order. int cnt = 0, secondaryCnt = 0; Pair<int, int>? last = null; string methodName = string.Format("RunThenByComposedWithJoinJoin(outerSize = {0}, innerSize = {1}, descending = {2})", outerSize, innerSize, descending); foreach (Pair<int, int> p in outerJoin) { cnt++; if (!((last == null || ((last.Value.First <= p.First && !descending) || (last.Value.First >= p.First && descending))))) { Assert.True(false, string.Format(methodName + " > *ERROR: outer sort order not correct: last = {0}, curr = {1}", last.Value.First, p.First)); break; } if (last != null && last.Value.First == p.First) secondaryCnt++; if (!((last == null || (last.Value.First != p.First) || ((last.Value.Second <= p.Second && !descending) || (last.Value.Second >= p.Second && descending))))) { Assert.True(false, string.Format(methodName + " > *ERROR: inner sort order not correct: last = {0}, curr = {1}", last.Value.Second, p.Second)); } last = p; } } //----------------------------------------------------------------------------------- // If sort is followed by another operator, we need to preserve key ordering all the // way back up to the merge. That is true even if some elements are missing in the // output data stream. This test tries to compose ORDERBY with two WHEREs. This test // processes output sequentially (not pipelined). // private static void RunThenByComposedWithWhereWhere1(int dataSize, bool descending) { // We sort on a very dense (lots of dups) set of ints first, and then // a more volatile set, to ensure we end up stressing secondary sort logic. Pair<int, int>[] pairs = new Pair<int, int>[dataSize]; var rangeNumbers = Enumerable.Range(0, (dataSize / 250)).ToList(); if (rangeNumbers.Count == 0) rangeNumbers.Add(0); for (int i = 0; i < dataSize; i++) { int index = i % rangeNumbers.Count; pairs[i].First = rangeNumbers[index]; pairs[i].Second = 10 - (i % 10); } ParallelQuery<Pair<int, int>> q; // Create the ORDERBY: if (descending) { q = pairs.AsParallel<Pair<int, int>>() .OrderByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } else { q = pairs.AsParallel<Pair<int, int>>() .OrderBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } // Wrap with a WHERE: q = q.Where<Pair<int, int>>(delegate (Pair<int, int> x) { return (x.First % 2) == 0; }); // Wrap with another WHERE: q = q.Where<Pair<int, int>>(delegate (Pair<int, int> x) { return (x.First % 4) == 0; }); // Force synchronous execution before validating results. List<Pair<int, int>> r = q.ToList<Pair<int, int>>(); for (int i = 1; i < r.Count; i++) { if (CompareInts(r[i - 1].First, r[i].First, descending) == 0 && CompareInts(r[i - 1].Second, r[i].Second, descending) > 0) { string method = string.Format("RunThenByComposedWithWhereWhere1(dataSize = {0}, descending = {1}) - sequential/no pipeline", dataSize, descending); Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", r[i - 1], r[i])); } } } //----------------------------------------------------------------------------------- // If sort is followed by another operator, we need to preserve key ordering all the // way back up to the merge. That is true even if some elements are missing in the // output data stream. This test tries to compose ORDERBY with WHERE and SELECT. // This test processes output sequentially (not pipelined). // // This is particularly interesting because the SELECT completely loses the original // type information in the tree, yet the merge is able to put things back in order. // private static void RunThenByComposedWithWhereSelect1(int dataSize, bool descending) { // We sort on a very dense (lots of dups) set of ints first, and then // a more volatile set, to ensure we end up stressing secondary sort logic. Pair<int, int>[] pairs = new Pair<int, int>[dataSize]; var rangeNumbers = Enumerable.Range(0, (dataSize / 250)).ToList(); if (rangeNumbers.Count == 0) rangeNumbers.Add(0); for (int i = 0; i < dataSize; i++) { int index = i % rangeNumbers.Count; pairs[i].First = rangeNumbers[index]; pairs[i].Second = 10 - (i % 10); } ParallelQuery<Pair<int, int>> q0; // Create the ORDERBY: if (descending) { q0 = pairs.AsParallel<Pair<int, int>>() .OrderByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenByDescending<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.Second; }); } else { q0 = pairs.AsParallel<Pair<int, int>>() .OrderBy<Pair<int, int>, int>(delegate (Pair<int, int> x) { return x.First; }) .ThenBy<Pair<int, int>, int>( delegate (Pair<int, int> x) { return x.Second; }); } // Wrap with a WHERE: q0 = q0.Where<Pair<int, int>>(delegate (Pair<int, int> x) { return (x.First % 2) == 0; }); // Wrap with a SELECT: ParallelQuery<string> q1 = q0.Select<Pair<int, int>, string>(delegate (Pair<int, int> x) { return x.First + "." + x.Second; }); // Force synchronous execution before validating results. List<string> r = q1.ToList<string>(); for (int i = 1; i < r.Count; i++) { int i0idx = r[i - 1].IndexOf('.'); int i1idx = r[i].IndexOf('.'); Pair<int, int> i0 = new Pair<int, int>( int.Parse(r[i - 1].Substring(0, i0idx)), int.Parse(r[i - 1].Substring(i0idx + 1))); Pair<int, int> i1 = new Pair<int, int>( int.Parse(r[i].Substring(0, i1idx)), int.Parse(r[i].Substring(i1idx + 1))); ; if (CompareInts(i0.First, i1.First, descending) == 0 && CompareInts(i0.Second, i1.Second, descending) > 0) { string method = string.Format("RunThenByComposedWithWhereSelect1(dataSize = {0}, descending = {1}) - sequential/no pipeline", dataSize, descending); Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", i0, i1)); } } } private static void RunThenByTestRecursive1(int dataSize, bool descending) { // We sort on a very dense (lots of dups) set of ints first, and then // a more volatile set, to ensure we end up stressing secondary sort logic. Pair<int, Pair<int, int>>[] pairs = new Pair<int, Pair<int, int>>[dataSize]; var rangeNumbers = Enumerable.Range(0, (dataSize / 250)).ToList(); if (rangeNumbers.Count == 0) rangeNumbers.Add(0); for (int i = 0; i < dataSize; i++) { int index = i % rangeNumbers.Count; pairs[i].First = rangeNumbers[index]; pairs[i].Second = new Pair<int, int>(10 - (i % 10), 3 - (i % 3)); } ParallelQuery<Pair<int, Pair<int, int>>> q; if (descending) { q = pairs.AsParallel<Pair<int, Pair<int, int>>>() .OrderByDescending<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.First; }) .ThenByDescending<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.Second.First; }) .ThenByDescending<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.Second.Second; }); } else { q = pairs.AsParallel<Pair<int, Pair<int, int>>>() .OrderBy<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.First; }) .ThenBy<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.Second.First; }) .ThenBy<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.Second.Second; }); } // Force synchronous execution before validating results. List<Pair<int, Pair<int, int>>> r = q.ToList<Pair<int, Pair<int, int>>>(); for (int i = 1; i < r.Count; i++) { if (CompareInts(r[i - 1].First, r[i].First, descending) == 0 && CompareInts(r[i - 1].Second.First, r[i].Second.First, descending) == 0 && CompareInts(r[i - 1].Second.Second, r[i].Second.Second, descending) > 0) { string method = string.Format("RunThenByTestRecursive1(dataSize = {0}, descending = {1}) - synchronous/no pipeline", dataSize, descending); Assert.True(false, string.Format(method + " > **ERROR** {0}.{1} came before {2}.{3} -- but isn't what we expected", r[i - 1].First, r[i - 1].Second, r[i].First, r[i].Second)); } } } private static void RunThenByTestRecursive2(int dataSize, bool descending) { // We sort on a very dense (lots of dups) set of ints first, and then // a more volatile set, to ensure we end up stressing secondary sort logic. Pair<int, Pair<int, int>>[] pairs = new Pair<int, Pair<int, int>>[dataSize]; var rangeNumbers = Enumerable.Range(0, (dataSize / 250)).ToList(); if (rangeNumbers.Count == 0) rangeNumbers.Add(0); for (int i = 0; i < dataSize; i++) { int index = i % rangeNumbers.Count; pairs[i].First = rangeNumbers[index]; pairs[i].Second = new Pair<int, int>(10 - (i % 10), 3 - (i % 3)); } ParallelQuery<Pair<int, Pair<int, int>>> q; if (descending) { q = pairs.AsParallel<Pair<int, Pair<int, int>>>() .OrderByDescending<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.First; }) .ThenByDescending<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.Second.First; }) .ThenByDescending<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.Second.Second; }); } else { q = pairs.AsParallel<Pair<int, Pair<int, int>>>() .OrderBy<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.First; }) .ThenBy<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.Second.First; }) .ThenBy<Pair<int, Pair<int, int>>, int>(delegate (Pair<int, Pair<int, int>> x) { return x.Second.Second; }); } // Force synchronous execution before validating results. List<Pair<int, Pair<int, int>>> r = new List<Pair<int, Pair<int, int>>>(); foreach (Pair<int, Pair<int, int>> x in q) r.Add(x); for (int i = 1; i < r.Count; i++) { if (CompareInts(r[i - 1].First, r[i].First, descending) == 0 && CompareInts(r[i - 1].Second.First, r[i].Second.First, descending) == 0 && CompareInts(r[i - 1].Second.Second, r[i].Second.Second, descending) > 0) { string method = string.Format("RunThenByTestRecursive2(dataSize = {0}, descending = {1}) - asynchronous/pipelining", dataSize, descending); Assert.True(false, string.Format(method + " > **ERROR** {0}.{1} came before {2}.{3} -- but isn't what we expected", r[i - 1].First, r[i - 1].Second, r[i].First, r[i].Second)); } } } #region Helper Classes / Methods //----------------------------------------------------------------------------------- // A pair just wraps two bits of data into a single addressable unit. This is a // value type to ensure it remains very lightweight, since it is frequently used // with other primitive data types as well. // // Note: this class is another copy of the Pair<T, U> class defined in CommonDataTypes.cs. // For now, we have a copy of the class here, because we can't import the System.Linq.Parallel // namespace. // private struct Pair<T, U> { // The first and second bits of data. internal T m_first; internal U m_second; //----------------------------------------------------------------------------------- // A simple constructor that initializes the first/second fields. // public Pair(T first, U second) { m_first = first; m_second = second; } //----------------------------------------------------------------------------------- // Accessors for the left and right data. // public T First { get { return m_first; } set { m_first = value; } } public U Second { get { return m_second; } set { m_second = value; } } } private static int CompareInts(int x, int y, bool descending) { int c = x.CompareTo(y); if (descending) return -c; return c; } enum DataDistributionType { AlreadyAscending, AlreadyDescending, Random } private static int[] CreateOrderByInput(int dataSize, DataDistributionType type) { int[] data = new int[dataSize]; switch (type) { case DataDistributionType.AlreadyAscending: for (int i = 0; i < data.Length; i++) data[i] = i; break; case DataDistributionType.AlreadyDescending: for (int i = 0; i < data.Length; i++) data[i] = dataSize - i; break; case DataDistributionType.Random: //Random rand = new Random(); for (int i = 0; i < data.Length; i++) { data[i] = i % ValueHelper.Next(); } break; } return data; } private static class ValueHelper { private const string text = @"Pseudo-random numbers are chosen with equal probability from a finite set of numbers. The chosen numbers are not completely random because a definite mathematical algorithm is used to select them, but they are sufficiently random for practical purposes. The current implementation of the Random class is based on a modified version of Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth. The Art of Computer Programming, volume 2: Seminumerical Algorithms. Addison-Wesley, Reading, MA, second edition, 1981. The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers. The following example illustrates that two Random objects that are instantiated in close succession generate an identical series of random numbers. "; private static int _currentPosition = 0; private static StartPosition _currentStart = StartPosition.Beginning; private static readonly int _middlePosition = text.Length / 2; public static int Next() { int nextPosition; switch (_currentStart) { case StartPosition.Beginning: case StartPosition.Middle: nextPosition = (_currentPosition + 1) % text.Length; break; case StartPosition.End: nextPosition = (_currentPosition - 1) % text.Length; break; default: throw new ArgumentException(string.Format("Enum does not exist {0}", _currentStart)); } if ((nextPosition == 0 && _currentStart != StartPosition.Middle) || (nextPosition == _middlePosition && _currentStart == StartPosition.Middle)) { _currentStart = (StartPosition)(((int)_currentStart + 1) % 3); switch (_currentStart) { case StartPosition.Beginning: nextPosition = 0; break; case StartPosition.Middle: nextPosition = _middlePosition; break; case StartPosition.End: nextPosition = text.Length - 1; break; default: throw new ArgumentException(string.Format("Enum does not exist {0}", _currentStart)); } } int lengthOfText = text.Length; _currentPosition = nextPosition; char charValue = text[_currentPosition]; return (int)charValue; } enum StartPosition { Beginning = 0, Middle = 1, End = 2 } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // ---------------------------------------------------------------------------- // This class takes an EXPRMEMGRP and a set of arguments and binds the arguments // to the best applicable method in the group. // ---------------------------------------------------------------------------- internal sealed partial class ExpressionBinder { internal sealed class GroupToArgsBinder { private enum Result { Success, Failure_SearchForExpanded, Failure_NoSearchForExpanded } private readonly ExpressionBinder _pExprBinder; private bool _fCandidatesUnsupported; private readonly BindingFlag _fBindFlags; private readonly ExprMemberGroup _pGroup; private readonly ArgInfos _pArguments; private readonly ArgInfos _pOriginalArguments; private readonly NamedArgumentsKind _namedArgumentsKind; private AggregateType _pCurrentType; private MethodOrPropertySymbol _pCurrentSym; private TypeArray _pCurrentTypeArgs; private TypeArray _pCurrentParameters; private int _nArgBest; // end of current namespaces extension method list private readonly GroupToArgsBinderResult _results; private readonly List<CandidateFunctionMember> _methList; private readonly MethPropWithInst _mpwiParamTypeConstraints; private readonly MethPropWithInst _mpwiBogus; private readonly MethPropWithInst _misnamed; private readonly MethPropWithInst _mpwiCantInferInstArg; private readonly MethWithType _mwtBadArity; private Name _pInvalidSpecifiedName; private Name _pNameUsedInPositionalArgument; private Name _pDuplicateSpecifiedName; // When we find a type with an interface, then we want to mark all other interfaces that it // implements as being hidden. We also want to mark object as being hidden. So stick them // all in this list, and then for subsequent types, if they're in this list, then we // ignore them. private readonly List<CType> _HiddenTypes; private bool _bArgumentsChangedForNamedOrOptionalArguments; public GroupToArgsBinder(ExpressionBinder exprBinder, BindingFlag bindFlags, ExprMemberGroup grp, ArgInfos args, ArgInfos originalArgs, NamedArgumentsKind namedArgumentsKind) { Debug.Assert(grp != null); Debug.Assert(exprBinder != null); Debug.Assert(args != null); _pExprBinder = exprBinder; _fCandidatesUnsupported = false; _fBindFlags = bindFlags; _pGroup = grp; _pArguments = args; _pOriginalArguments = originalArgs; _namedArgumentsKind = namedArgumentsKind; _pCurrentType = null; _pCurrentSym = null; _pCurrentTypeArgs = null; _pCurrentParameters = null; _nArgBest = -1; _results = new GroupToArgsBinderResult(); _methList = new List<CandidateFunctionMember>(); _mpwiParamTypeConstraints = new MethPropWithInst(); _mpwiBogus = new MethPropWithInst(); _misnamed = new MethPropWithInst(); _mpwiCantInferInstArg = new MethPropWithInst(); _mwtBadArity = new MethWithType(); _HiddenTypes = new List<CType>(); } // ---------------------------------------------------------------------------- // This method does the actual binding. // ---------------------------------------------------------------------------- public void Bind() { Debug.Assert(_pGroup.SymKind == SYMKIND.SK_MethodSymbol || _pGroup.SymKind == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.Flags & EXPRFLAG.EXF_INDEXER)); LookForCandidates(); if (!GetResultOfBind()) { throw ReportErrorsOnFailure(); } } public GroupToArgsBinderResult GetResultsOfBind() { return _results; } private SymbolLoader GetSymbolLoader() { return _pExprBinder.GetSymbolLoader(); } private CSemanticChecker GetSemanticChecker() { return _pExprBinder.GetSemanticChecker(); } private ErrorHandling GetErrorContext() { return _pExprBinder.GetErrorContext(); } private static CType GetTypeQualifier(ExprMemberGroup pGroup) { Debug.Assert(pGroup != null); return (pGroup.Flags & EXPRFLAG.EXF_CTOR) != 0 ? pGroup.ParentType : pGroup.OptionalObject?.Type; } private void LookForCandidates() { bool fExpanded = false; bool bSearchForExpanded = true; bool allCandidatesUnsupported = true; bool lookedAtCandidates = false; // Calculate the mask based on the type of the sym we've found so far. This // is to ensure that if we found a propsym (or methsym, or whatever) the // iterator will only return propsyms (or methsyms, or whatever) symbmask_t mask = (symbmask_t)(1 << (int)_pGroup.SymKind); CMemberLookupResults.CMethodIterator iterator = _pGroup.MemberLookupResults.GetMethodIterator(GetSemanticChecker(), GetSymbolLoader(), GetTypeQualifier(_pGroup), _pExprBinder.ContextForMemberLookup(), _pGroup.TypeArgs.Count, _pGroup.Flags, mask, _namedArgumentsKind == NamedArgumentsKind.NonTrailing ? _pOriginalArguments : null); while (true) { bool bFoundExpanded; bFoundExpanded = false; if (bSearchForExpanded && !fExpanded) { bFoundExpanded = fExpanded = ConstructExpandedParameters(); } // Get the next sym to search for. if (!bFoundExpanded) { fExpanded = false; if (!GetNextSym(iterator)) { break; } // Get the parameters. _pCurrentParameters = _pCurrentSym.Params; bSearchForExpanded = true; } if (_bArgumentsChangedForNamedOrOptionalArguments) { // If we changed them last time, then we need to reset them. _bArgumentsChangedForNamedOrOptionalArguments = false; CopyArgInfos(_pOriginalArguments, _pArguments); } // If we have named arguments, reorder them for this method. // If we don't have Exprs, its because we're doing a method group conversion. // In those scenarios, we never want to add named arguments or optional arguments. if (_namedArgumentsKind == NamedArgumentsKind.Positioning) { if (!ReOrderArgsForNamedArguments()) { continue; } } else if (HasOptionalParameters()) { if (!AddArgumentsForOptionalParameters()) { continue; } } if (!bFoundExpanded) { lookedAtCandidates = true; allCandidatesUnsupported &= CSemanticChecker.CheckBogus(_pCurrentSym); // If we have the wrong number of arguments and still have room in our cache of 20, // then store it in our cache and go to the next sym. if (_pCurrentParameters.Count != _pArguments.carg) { bSearchForExpanded = true; continue; } } // If we cant use the current symbol, then we've filtered it, so get the next one. if (!iterator.CanUseCurrentSymbol) { continue; } // Get the current type args. Result currentTypeArgsResult = DetermineCurrentTypeArgs(); if (currentTypeArgsResult != Result.Success) { bSearchForExpanded = (currentTypeArgsResult == Result.Failure_SearchForExpanded); continue; } // Check access. bool fCanAccess = !iterator.IsCurrentSymbolInaccessible; if (!fCanAccess && (!_methList.IsEmpty() || _results.InaccessibleResult)) { // We'll never use this one for error reporting anyway, so just skip it. bSearchForExpanded = false; continue; } // Check misnamed. bool misnamed = fCanAccess && iterator.IsCurrentSymbolMisnamed; if (misnamed && (!_methList.IsEmpty() || _results.InaccessibleResult || _misnamed)) { bSearchForExpanded = false; continue; } // Check bogus. bool fBogus = fCanAccess && !misnamed && iterator.IsCurrentSymbolBogus; if (fBogus && (!_methList.IsEmpty() || _results.InaccessibleResult || _mpwiBogus || _misnamed)) { // We'll never use this one for error reporting anyway, so just skip it. bSearchForExpanded = false; continue; } // Check convertibility of arguments. if (!ArgumentsAreConvertible()) { bSearchForExpanded = true; continue; } // We know we have the right number of arguments and they are all convertible. if (!fCanAccess) { // In case we never get an accessible method, this will allow us to give // a better error... Debug.Assert(!_results.InaccessibleResult); _results.InaccessibleResult.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs); } else if (misnamed) { Debug.Assert(!_misnamed); _misnamed.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs); } else if (fBogus) { // In case we never get a good method, this will allow us to give // a better error... Debug.Assert(!_mpwiBogus); _mpwiBogus.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs); } else { // This is a plausible method / property to call. // Link it in at the end of the list. _methList.Add(new CandidateFunctionMember( new MethPropWithInst(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs), _pCurrentParameters, 0, fExpanded)); // When we find a method, we check if the type has interfaces. If so, mark the other interfaces // as hidden, and object as well. if (_pCurrentType.IsInterfaceType) { foreach (AggregateType type in _pCurrentType.IfacesAll.Items) { Debug.Assert(type.IsInterfaceType); _HiddenTypes.Add(type); } // Mark object. AggregateType typeObject = GetSymbolLoader().GetPredefindType(PredefinedType.PT_OBJECT); _HiddenTypes.Add(typeObject); } } // Don't look at the expanded form. bSearchForExpanded = false; } _fCandidatesUnsupported = allCandidatesUnsupported && lookedAtCandidates; // Restore the arguments to their original state if we changed them for named/optional arguments. // ILGen will take care of putting the real arguments in there. if (_bArgumentsChangedForNamedOrOptionalArguments) { // If we changed them last time, then we need to reset them. CopyArgInfos(_pOriginalArguments, _pArguments); } } private void CopyArgInfos(ArgInfos src, ArgInfos dst) { dst.carg = src.carg; dst.types = src.types; dst.prgexpr.Clear(); for (int i = 0; i < src.prgexpr.Count; i++) { dst.prgexpr.Add(src.prgexpr[i]); } } private bool GetResultOfBind() { // We looked at all the evidence, and we come to render the verdict: if (!_methList.IsEmpty()) { CandidateFunctionMember pmethBest; if (_methList.Count == 1) { // We found the single best method to call. pmethBest = _methList.Head(); } else { // We have some ambiguities, lets sort them out. CType pTypeThrough = _pGroup.OptionalObject?.Type; pmethBest = _pExprBinder.FindBestMethod(_methList, pTypeThrough, _pArguments, out CandidateFunctionMember pAmbig1, out CandidateFunctionMember pAmbig2); if (null == pmethBest) { _results.AmbiguousResult = pAmbig2.mpwi; if (pAmbig1.@params != pAmbig2.@params || pAmbig1.mpwi.MethProp().Params.Count != pAmbig2.mpwi.MethProp().Params.Count || pAmbig1.mpwi.TypeArgs != pAmbig2.mpwi.TypeArgs || pAmbig1.mpwi.GetType() != pAmbig2.mpwi.GetType() || pAmbig1.mpwi.MethProp().Params == pAmbig2.mpwi.MethProp().Params) { throw GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi, pAmbig2.mpwi); } // The two signatures are identical so don't use the type args in the error message. throw GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi.MethProp(), pAmbig2.mpwi.MethProp()); } } // This is the "success" exit path. Debug.Assert(pmethBest != null); _results.BestResult = pmethBest.mpwi; // Record our best match in the memgroup as well. This is temporary. if (true) { ReportErrorsOnSuccess(); } return true; } return false; } ///////////////////////////////////////////////////////////////////////////////// // This method returns true if we're able to match arguments to their names. // If we either have too many arguments, or we cannot match their names, then // we return false. // // Note that if we have not enough arguments, we still return true as long as // we can find matching parameters for each named arguments, and all parameters // that do not have a matching argument are optional parameters. private bool ReOrderArgsForNamedArguments() { // First we need to find the method that we're actually trying to call. MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject); if (methprop == null) { return false; } int numParameters = _pCurrentParameters.Count; // If we have no parameters, or fewer parameters than we have arguments, bail. if (numParameters == 0 || numParameters < _pArguments.carg) { return false; } // Make sure all the names we specified are in the list and we don't have duplicates. if (!NamedArgumentNamesAppearInParameterList(methprop)) { return false; } _bArgumentsChangedForNamedOrOptionalArguments = ReOrderArgsForNamedArguments( methprop, _pCurrentParameters, _pCurrentType, _pGroup, _pArguments, _pExprBinder.GetTypes(), _pExprBinder.GetExprFactory(), GetSymbolLoader()); return _bArgumentsChangedForNamedOrOptionalArguments; } internal static bool ReOrderArgsForNamedArguments( MethodOrPropertySymbol methprop, TypeArray pCurrentParameters, AggregateType pCurrentType, ExprMemberGroup pGroup, ArgInfos pArguments, TypeManager typeManager, ExprFactory exprFactory, SymbolLoader symbolLoader) { // We use the param count from pCurrentParameters because they may have been resized // for param arrays. int numParameters = pCurrentParameters.Count; Expr[] pExprArguments = new Expr[numParameters]; // Now go through the parameters. First set all positional arguments in the new argument // set, then for the remainder, look for a named argument with a matching name. int index = 0; Expr paramArrayArgument = null; TypeArray @params = typeManager.SubstTypeArray( pCurrentParameters, pCurrentType, pGroup.TypeArgs); foreach (Name name in methprop.ParameterNames) { // This can happen if we had expanded our param array to size 0. if (index >= pCurrentParameters.Count) { break; } // If: // (1) we have a param array method // (2) we're on the last arg // (3) the thing we have is an array init thats generated for param array // then let us through. if (methprop.isParamArray && index < pArguments.carg && pArguments.prgexpr[index] is ExprArrayInit arrayInit && arrayInit.GeneratedForParamArray) { paramArrayArgument = pArguments.prgexpr[index]; } // Positional. if (index < pArguments.carg && !(pArguments.prgexpr[index] is ExprNamedArgumentSpecification) && !(pArguments.prgexpr[index] is ExprArrayInit arrayInitPos && arrayInitPos.GeneratedForParamArray)) { pExprArguments[index] = pArguments.prgexpr[index++]; continue; } // Look for names. Expr pNewArg = FindArgumentWithName(pArguments, name); if (pNewArg == null) { if (methprop.IsParameterOptional(index)) { pNewArg = GenerateOptionalArgument(symbolLoader, exprFactory, methprop, @params[index], index); } else if (paramArrayArgument != null && index == methprop.Params.Count - 1) { // If we have a param array argument and we're on the last one, then use it. pNewArg = paramArrayArgument; } else { // No name and no default value. return false; } } pExprArguments[index++] = pNewArg; } // Here we've found all the arguments, or have default values for them. CType[] prgTypes = new CType[pCurrentParameters.Count]; for (int i = 0; i < numParameters; i++) { if (i < pArguments.prgexpr.Count) { pArguments.prgexpr[i] = pExprArguments[i]; } else { pArguments.prgexpr.Add(pExprArguments[i]); } prgTypes[i] = pArguments.prgexpr[i].Type; } pArguments.carg = pCurrentParameters.Count; pArguments.types = symbolLoader.getBSymmgr().AllocParams(pCurrentParameters.Count, prgTypes); return true; } ///////////////////////////////////////////////////////////////////////////////// private static Expr GenerateOptionalArgument( SymbolLoader symbolLoader, ExprFactory exprFactory, MethodOrPropertySymbol methprop, CType type, int index) { CType pParamType = type; CType pRawParamType = type.StripNubs(); Expr optionalArgument; if (methprop.HasDefaultParameterValue(index)) { CType pConstValType = methprop.GetDefaultParameterValueConstValType(index); ConstVal cv = methprop.GetDefaultParameterValue(index); if (pConstValType.IsPredefType(PredefinedType.PT_DATETIME) && (pRawParamType.IsPredefType(PredefinedType.PT_DATETIME) || pRawParamType.IsPredefType(PredefinedType.PT_OBJECT) || pRawParamType.IsPredefType(PredefinedType.PT_VALUE))) { // This is the specific case where we want to create a DateTime // but the constval that stores it is a long. AggregateType dateTimeType = symbolLoader.GetPredefindType(PredefinedType.PT_DATETIME); optionalArgument = exprFactory.CreateConstant(dateTimeType, ConstVal.Get(DateTime.FromBinary(cv.Int64Val))); } else if (pConstValType.IsSimpleOrEnumOrString) { // In this case, the constval is a simple type (all the numerics, including // decimal), or an enum or a string. This covers all the substantial values, // and everything else that can be encoded is just null or default(something). // For enum parameters, we create a constant of the enum type. For everything // else, we create the appropriate constant. optionalArgument = exprFactory.CreateConstant( pRawParamType.IsEnumType && pConstValType == pRawParamType.UnderlyingEnumType ? pRawParamType : pConstValType, cv); } else if ((pParamType.IsReferenceType || pParamType is NullableType) && cv.IsNullRef) { // We have an "= null" default value with a reference type or a nullable type. optionalArgument = exprFactory.CreateNull(); } else { // We have a default value that is encoded as a nullref, and that nullref is // interpreted as default(something). For instance, the pParamType could be // a type parameter type or a non-simple value type. optionalArgument = exprFactory.CreateZeroInit(pParamType); } } else { // There was no default parameter specified, so generally use default(T), // except for some cases when the parameter type in metatdata is object. if (pParamType.IsPredefType(PredefinedType.PT_OBJECT)) { if (methprop.MarshalAsObject(index)) { // For [opt] parameters of type object, if we have marshal(iunknown), // marshal(idispatch), or marshal(interface), then we emit a null. optionalArgument = exprFactory.CreateNull(); } else { // Otherwise, we generate Type.Missing AggregateSymbol agg = symbolLoader.GetPredefAgg(PredefinedType.PT_MISSING); Name name = NameManager.GetPredefinedName(PredefinedName.PN_CAP_VALUE); FieldSymbol field = symbolLoader.LookupAggMember(name, agg, symbmask_t.MASK_FieldSymbol) as FieldSymbol; FieldWithType fwt = new FieldWithType(field, agg.getThisType()); ExprField exprField = exprFactory.CreateField(agg.getThisType(), null, fwt, false); optionalArgument = exprFactory.CreateCast(type, exprField); } } else { // Every type aside from object that doesn't have a default value gets // its default value. optionalArgument = exprFactory.CreateZeroInit(pParamType); } } Debug.Assert(optionalArgument != null); optionalArgument.IsOptionalArgument = true; return optionalArgument; } ///////////////////////////////////////////////////////////////////////////////// private MethodOrPropertySymbol FindMostDerivedMethod( MethodOrPropertySymbol pMethProp, Expr pObject) { return FindMostDerivedMethod(GetSymbolLoader(), pMethProp, pObject?.Type); } ///////////////////////////////////////////////////////////////////////////////// public static MethodOrPropertySymbol FindMostDerivedMethod( SymbolLoader symbolLoader, MethodOrPropertySymbol pMethProp, CType pType) { bool bIsIndexer = false; if (!(pMethProp is MethodSymbol method)) { PropertySymbol prop = (PropertySymbol)pMethProp; method = prop.GetterMethod ?? prop.SetterMethod; if (method == null) { return null; } bIsIndexer = prop is IndexerSymbol; } if (!method.isVirtual || pType == null) { // if pType is null, this must be a static call. return method; } // Now get the slot method. var slotMethod = method.swtSlot?.Meth(); if (slotMethod != null) { method = slotMethod; } if (!(pType is AggregateType agg)) { // Not something that can have overrides anyway. return method; } for (AggregateSymbol pAggregate = agg.OwningAggregate; pAggregate?.GetBaseAgg() != null; pAggregate = pAggregate.GetBaseAgg()) { for (MethodOrPropertySymbol meth = symbolLoader.LookupAggMember(method.name, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol) as MethodOrPropertySymbol; meth != null; meth = SymbolLoader.LookupNextSym(meth, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol) as MethodOrPropertySymbol) { if (!meth.isOverride) { continue; } if (meth.swtSlot.Sym != null && meth.swtSlot.Sym == method) { if (bIsIndexer) { Debug.Assert(meth is MethodSymbol); return ((MethodSymbol)meth).getProperty(); } else { return meth; } } } } // If we get here, it means we can have two cases: one is that we have // a delegate. This is because the delegate invoke method is virtual and is // an override, but we won't have the slots set up correctly, and will // not find the base type in the inheritance hierarchy. The second is that // we're calling off of the base itself. Debug.Assert(method.parent is AggregateSymbol); return method; } ///////////////////////////////////////////////////////////////////////////////// private bool HasOptionalParameters() { MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject); return methprop != null && methprop.HasOptionalParameters(); } ///////////////////////////////////////////////////////////////////////////////// // Returns true if we can either add enough optional parameters to make the // argument list match, or if we don't need to at all. private bool AddArgumentsForOptionalParameters() { if (_pCurrentParameters.Count <= _pArguments.carg) { // If we have enough arguments, or too many, no need to add any optionals here. return true; } // First we need to find the method that we're actually trying to call. MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject); if (methprop == null) { return false; } // If we're here, we know we're not in a named argument case. As such, we can // just generate defaults for every missing argument. int i = _pArguments.carg; int index = 0; TypeArray @params = _pExprBinder.GetTypes().SubstTypeArray( _pCurrentParameters, _pCurrentType, _pGroup.TypeArgs); Expr[] pArguments = new Expr[_pCurrentParameters.Count - i]; for (; i < @params.Count; i++, index++) { if (!methprop.IsParameterOptional(i)) { // We don't have an optional here, but we need to fill it in. return false; } pArguments[index] = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), methprop, @params[i], i); } // Success. Lets copy them in now. for (int n = 0; n < index; n++) { _pArguments.prgexpr.Add(pArguments[n]); } CType[] prgTypes = new CType[@params.Count]; for (int n = 0; n < @params.Count; n++) { prgTypes[n] = _pArguments.prgexpr[n].Type; } _pArguments.types = GetSymbolLoader().getBSymmgr().AllocParams(@params.Count, prgTypes); _pArguments.carg = @params.Count; _bArgumentsChangedForNamedOrOptionalArguments = true; return true; } ///////////////////////////////////////////////////////////////////////////////// private static Expr FindArgumentWithName(ArgInfos pArguments, Name pName) { List<Expr> prgexpr = pArguments.prgexpr; for (int i = 0; i < pArguments.carg; i++) { Expr expr = prgexpr[i]; if (expr is ExprNamedArgumentSpecification named && named.Name == pName) { return expr; } } return null; } ///////////////////////////////////////////////////////////////////////////////// private bool NamedArgumentNamesAppearInParameterList( MethodOrPropertySymbol methprop) { // Keep track of the current position in the parameter list so that we can check // containment from this point onwards as well as complete containment. This is // for error reporting. The user cannot specify a named argument for a parameter // that has a fixed argument value. List<Name> currentPosition = methprop.ParameterNames; HashSet<Name> names = new HashSet<Name>(); for (int i = 0; i < _pArguments.carg; i++) { if (!(_pArguments.prgexpr[i] is ExprNamedArgumentSpecification named)) { if (!currentPosition.IsEmpty()) { currentPosition = currentPosition.Tail(); } continue; } Name name = named.Name; if (!methprop.ParameterNames.Contains(name)) { if (_pInvalidSpecifiedName == null) { _pInvalidSpecifiedName = name; } return false; } else if (!currentPosition.Contains(name)) { if (_pNameUsedInPositionalArgument == null) { _pNameUsedInPositionalArgument = name; } return false; } if (!names.Add(name)) { if (_pDuplicateSpecifiedName == null) { _pDuplicateSpecifiedName = name; } return false; } } return true; } // This method returns true if we have another sym to consider. // If we've found a match in the current type, and have no more syms to consider in this type, then we // return false. private bool GetNextSym(CMemberLookupResults.CMethodIterator iterator) { if (!iterator.MoveNext()) { return false; } _pCurrentSym = iterator.CurrentSymbol; AggregateType type = iterator.CurrentType; // If our current type is null, this is our first iteration, so set the type. // If our current type is not null, and we've got a new type now, and we've already matched // a symbol, then bail out. if (_pCurrentType != type && _pCurrentType != null && !_methList.IsEmpty() && !_methList.Head().mpwi.GetType().IsInterfaceType) { return false; } _pCurrentType = type; // We have a new type. If this type is hidden, we need another type. while (_HiddenTypes.Contains(_pCurrentType)) { // Move through this type and get the next one. for (; iterator.CurrentType == _pCurrentType; iterator.MoveNext()) ; _pCurrentSym = iterator.CurrentSymbol; _pCurrentType = iterator.CurrentType; if (iterator.AtEnd) { return false; } } return true; } private bool ConstructExpandedParameters() { // Deal with params. if (_pCurrentSym == null || _pArguments == null || _pCurrentParameters == null) { return false; } if (0 != (_fBindFlags & BindingFlag.BIND_NOPARAMS)) { return false; } if (!_pCurrentSym.isParamArray) { return false; } // Count the number of optionals in the method. If there are enough optionals // and actual arguments, then proceed. { int numOptionals = 0; for (int i = _pArguments.carg; i < _pCurrentSym.Params.Count; i++) { if (_pCurrentSym.IsParameterOptional(i)) { numOptionals++; } } if (_pArguments.carg + numOptionals < _pCurrentParameters.Count - 1) { return false; } } Debug.Assert(_methList.IsEmpty() || _methList.Head().mpwi.MethProp() != _pCurrentSym); // Construct the expanded params. return _pExprBinder.TryGetExpandedParams(_pCurrentSym.Params, _pArguments.carg, out _pCurrentParameters); } private Result DetermineCurrentTypeArgs() { TypeArray typeArgs = _pGroup.TypeArgs; // Get the type args. if (_pCurrentSym is MethodSymbol methSym && methSym.typeVars.Count != typeArgs.Count) { // Can't infer if some type args are specified. if (typeArgs.Count > 0) { if (!_mwtBadArity) { _mwtBadArity.Set(methSym, _pCurrentType); } return Result.Failure_NoSearchForExpanded; } Debug.Assert(methSym.typeVars.Count > 0); // Try to infer. If we have an errorsym in the type arguments, we know we cant infer, // but we want to attempt it anyway. We'll mark this as "cant infer" so that we can // report the appropriate error, but we'll continue inferring, since we want // error sym to go to any type. bool inferenceSucceeded = MethodTypeInferrer.Infer( _pExprBinder, GetSymbolLoader(), methSym, _pCurrentParameters, _pArguments, out _pCurrentTypeArgs); if (!inferenceSucceeded) { if (_results.IsBetterUninferableResult(_pCurrentTypeArgs)) { TypeArray pTypeVars = methSym.typeVars; if (pTypeVars != null && _pCurrentTypeArgs != null && pTypeVars.Count == _pCurrentTypeArgs.Count) { _mpwiCantInferInstArg.Set(methSym, _pCurrentType, _pCurrentTypeArgs); } else { _mpwiCantInferInstArg.Set(methSym, _pCurrentType, pTypeVars); } } return Result.Failure_SearchForExpanded; } } else { _pCurrentTypeArgs = typeArgs; } return Result.Success; } private bool ArgumentsAreConvertible() { bool containsErrorSym = false; if (_pArguments.carg != 0) { UpdateArguments(); for (int ivar = 0; ivar < _pArguments.carg; ivar++) { CType var = _pCurrentParameters[ivar]; bool constraintErrors = !TypeBind.CheckConstraints(GetSemanticChecker(), GetErrorContext(), var, CheckConstraintsFlags.NoErrors); if (constraintErrors && !DoesTypeArgumentsContainErrorSym(var)) { _mpwiParamTypeConstraints.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs); return false; } } for (int ivar = 0; ivar < _pArguments.carg; ivar++) { CType var = _pCurrentParameters[ivar]; containsErrorSym |= DoesTypeArgumentsContainErrorSym(var); bool fresult; Expr pArgument = _pArguments.prgexpr[ivar]; // If we have a named argument, strip it to do the conversion. if (pArgument is ExprNamedArgumentSpecification named) { pArgument = named.Value; } fresult = _pExprBinder.canConvert(pArgument, var); // Mark this as a legitimate error if we didn't have any error syms. if (!fresult && !containsErrorSym) { if (ivar > _nArgBest) { _nArgBest = ivar; // If we already have best method for instance methods don't overwrite with extensions if (!_results.BestResult) { _results.BestResult.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs); } } else if (ivar == _nArgBest && _pArguments.types[ivar] != var) { // this is to eliminate the paranoid case of types that are equal but can't convert // (think ErrorType != ErrorType) // See if they just differ in out / ref. CType argStripped = _pArguments.types[ivar] is ParameterModifierType modArg ? modArg.ParameterType : _pArguments.types[ivar]; CType varStripped = var is ParameterModifierType modVar ? modVar.ParameterType : var; if (argStripped == varStripped) { // If we already have best method for instance methods don't overwrite with extensions if (!_results.BestResult) { _results.BestResult.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs); } } } return false; } } } if (containsErrorSym) { if (_results.IsBetterUninferableResult(_pCurrentTypeArgs) && _pCurrentSym is MethodSymbol meth) { // If we're an instance method then mark us down. _results.UninferableResult.Set(meth, _pCurrentType, _pCurrentTypeArgs); } return false; } return true; } private void UpdateArguments() { // Parameter types might have changed as a result of // method type inference. _pCurrentParameters = _pExprBinder.GetTypes().SubstTypeArray( _pCurrentParameters, _pCurrentType, _pCurrentTypeArgs); // It is also possible that an optional argument has changed its value // as a result of method type inference. For example, when inferring // from Foo(10) to Foo<T>(T t1, T t2 = default(T)), the fabricated // argument list starts off as being (10, default(T)). After type // inference has successfully inferred T as int, it needs to be // transformed into (10, default(int)) before applicability checking // notices that default(T) is not assignable to int. if (_pArguments.prgexpr == null || _pArguments.prgexpr.Count == 0) { return; } MethodOrPropertySymbol pMethod = null; for (int iParam = 0; iParam < _pCurrentParameters.Count; ++iParam) { Expr pArgument = _pArguments.prgexpr[iParam]; if (!pArgument.IsOptionalArgument) { continue; } CType pType = _pCurrentParameters[iParam]; if (pType == pArgument.Type) { continue; } // Argument has changed its type because of method type inference. Recompute it. if (pMethod == null) { pMethod = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject); Debug.Assert(pMethod != null); } Debug.Assert(pMethod.IsParameterOptional(iParam)); Expr pArgumentNew = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), pMethod, _pCurrentParameters[iParam], iParam); _pArguments.prgexpr[iParam] = pArgumentNew; } } private bool DoesTypeArgumentsContainErrorSym(CType var) { if (!(var is AggregateType varAgg)) { return false; } TypeArray typeVars = varAgg.TypeArgsAll; for (int i = 0; i < typeVars.Count; i++) { CType type = typeVars[i]; if (type == null) { return true; } else if (type is AggregateType) { // If we have an agg type sym, check if its type args have errors. if (DoesTypeArgumentsContainErrorSym(type)) { return true; } } } return false; } // ---------------------------------------------------------------------------- private void ReportErrorsOnSuccess() { // used for Methods and Indexers Debug.Assert(_pGroup.SymKind == SYMKIND.SK_MethodSymbol || _pGroup.SymKind == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.Flags & EXPRFLAG.EXF_INDEXER)); Debug.Assert(_pGroup.TypeArgs.Count == 0 || _pGroup.SymKind == SYMKIND.SK_MethodSymbol); Debug.Assert(0 == (_pGroup.Flags & EXPRFLAG.EXF_USERCALLABLE) || _results.BestResult.MethProp().isUserCallable()); if (_pGroup.SymKind == SYMKIND.SK_MethodSymbol) { Debug.Assert(_results.BestResult.MethProp() is MethodSymbol); if (_results.BestResult.TypeArgs.Count > 0) { // Check method type variable constraints. TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_results.BestResult)); } } } private RuntimeBinderException ReportErrorsOnFailure() { // First and foremost, report if the user specified a name more than once. if (_pDuplicateSpecifiedName != null) { return GetErrorContext().Error(ErrorCode.ERR_DuplicateNamedArgument, _pDuplicateSpecifiedName); } Debug.Assert(_methList.IsEmpty()); // Report inaccessible. if (_results.InaccessibleResult) { // We might have called this, but it is inaccessible... return GetSemanticChecker().ReportAccessError(_results.InaccessibleResult, _pExprBinder.ContextForMemberLookup(), GetTypeQualifier(_pGroup)); } if (_misnamed) { // Get exception immediately for the non-trailing named argument being misplaced. // Handle below for the name not being present at all. List<Name> paramNames = FindMostDerivedMethod(_misnamed.MethProp(), _pGroup.OptionalObject).ParameterNames; for (int i = 0; ; ++i) { if (i == _pOriginalArguments.carg) { // If we're here we had the correct name used for the first params argument. // Report it as not matching the correct number of arguments below. break; } if (_pOriginalArguments.prgexpr[i] is ExprNamedArgumentSpecification named) { Name name = named.Name; if (paramNames[i] != name) { // We have the bad name. Is it misplaced or absent? if (paramNames.Contains(name)) { return GetErrorContext().Error(ErrorCode.ERR_BadNonTrailingNamedArgument, name); } // Let this be handled by _pInvalidSpecifiedName handling. _pInvalidSpecifiedName = name; break; } } } } else if (_mpwiBogus) { // We might have called this, but it is bogus... return GetErrorContext().Error(ErrorCode.ERR_BindToBogus, _mpwiBogus); } bool bUseDelegateErrors = false; Name nameErr = _pGroup.Name; // Check for an invoke. if (_pGroup.OptionalObject?.Type != null && _pGroup.OptionalObject.Type.IsDelegateType && _pGroup.Name == NameManager.GetPredefinedName(PredefinedName.PN_INVOKE)) { Debug.Assert(!_results.BestResult || _results.BestResult.MethProp().getClass().IsDelegate()); Debug.Assert(!_results.BestResult || _results.BestResult.GetType().OwningAggregate.IsDelegate()); bUseDelegateErrors = true; nameErr = ((AggregateType)_pGroup.OptionalObject.Type).OwningAggregate.name; } if (_results.BestResult) { // If we had some invalid arguments for best matching. return ReportErrorsForBestMatching(bUseDelegateErrors); } if (_results.UninferableResult || _mpwiCantInferInstArg) { if (!_results.UninferableResult) { //copy the extension method for which instance argument type inference failed _results.UninferableResult.Set(_mpwiCantInferInstArg.Sym as MethodSymbol, _mpwiCantInferInstArg.GetType(), _mpwiCantInferInstArg.TypeArgs); } Debug.Assert(_results.UninferableResult.Sym is MethodSymbol); MethWithType mwtCantInfer = new MethWithType(); mwtCantInfer.Set(_results.UninferableResult.Meth(), _results.UninferableResult.GetType()); return GetErrorContext().Error(ErrorCode.ERR_CantInferMethTypeArgs, mwtCantInfer); } if (_mwtBadArity) { int cvar = _mwtBadArity.Meth().typeVars.Count; return GetErrorContext().Error(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _mwtBadArity, new ErrArgSymKind(_mwtBadArity.Meth()), _pArguments.carg); } if (_mpwiParamTypeConstraints) { // This will always report an error TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_mpwiParamTypeConstraints)); Debug.Fail("Unreachable"); return null; } if (_pInvalidSpecifiedName != null) { // Give a better message for delegate invoke. return _pGroup.OptionalObject?.Type is AggregateType agg && agg.OwningAggregate.IsDelegate() ? GetErrorContext().Error( ErrorCode.ERR_BadNamedArgumentForDelegateInvoke, agg.OwningAggregate.name, _pInvalidSpecifiedName) : GetErrorContext().Error(ErrorCode.ERR_BadNamedArgument, _pGroup.Name, _pInvalidSpecifiedName); } if (_pNameUsedInPositionalArgument != null) { return GetErrorContext().Error(ErrorCode.ERR_NamedArgumentUsedInPositional, _pNameUsedInPositionalArgument); } // The number of arguments must be wrong. if (_fCandidatesUnsupported) { return GetErrorContext().Error(ErrorCode.ERR_BindToBogus, nameErr); } if (bUseDelegateErrors) { Debug.Assert(0 == (_pGroup.Flags & EXPRFLAG.EXF_CTOR)); return GetErrorContext().Error(ErrorCode.ERR_BadDelArgCount, nameErr, _pArguments.carg); } if (0 != (_pGroup.Flags & EXPRFLAG.EXF_CTOR)) { Debug.Assert(!(_pGroup.ParentType is TypeParameterType)); return GetErrorContext().Error(ErrorCode.ERR_BadCtorArgCount, _pGroup.ParentType, _pArguments.carg); } return GetErrorContext().Error(ErrorCode.ERR_BadArgCount, nameErr, _pArguments.carg); } private RuntimeBinderException ReportErrorsForBestMatching(bool bUseDelegateErrors) { if (bUseDelegateErrors) { // Point to the Delegate, not the Invoke method return GetErrorContext().Error(ErrorCode.ERR_BadDelArgTypes, _results.BestResult.GetType()); } return GetErrorContext().Error(ErrorCode.ERR_BadArgTypes, _results.BestResult); } } } }
#region File Description //----------------------------------------------------------------------------- // SpellbookScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using RolePlayingGameData; #endregion namespace RolePlaying { /// <summary> /// Lists the spells available to the character. /// </summary> class SpellbookScreen : ListScreen<Spell> { #region Graphics Data private readonly Vector2 spellDescriptionPosition = ScaledVector2.GetScaledVector(200, 550); private readonly Vector2 warningMessagePosition = ScaledVector2.GetScaledVector(200, 580); #endregion #region Columns private string nameColumnText = "Name"; private float nameColumnInterval = 80 * ScaledVector2.ScaleFactor; private string levelColumnText = "Level"; private float levelColumnInterval = 240 * ScaledVector2.ScaleFactor; private string powerColumnText = "Power (min, max)"; private float powerColumnInterval = 110 * ScaledVector2.ScaleFactor; private string magicCostColumnText = "MP"; private float magicCostColumnInterval = 380 * ScaledVector2.ScaleFactor; #endregion #region Data Access /// <summary> /// The FightingCharacter object whose spells are displayed. /// </summary> private FightingCharacter fightingCharacter; /// <summary> /// The statistics of the character, for calculating the eligibility of spells. /// </summary> /// <remarks> /// Needed because combat statistics override character statistics. /// </remarks> private StatisticsValue statistics; /// <summary> /// Get the list that this screen displays. /// </summary> public override ReadOnlyCollection<Spell> GetDataList() { return fightingCharacter.Spells.AsReadOnly(); } #endregion #region Initialization /// <summary> /// Creates a new SpellbookScreen object for the given player and statistics. /// </summary> public SpellbookScreen(FightingCharacter fightingCharacter, StatisticsValue statistics) : base() { // check the parameter if (fightingCharacter == null) { throw new ArgumentNullException("fightingCharacter"); } this.fightingCharacter = fightingCharacter; this.statistics = statistics; // sort the player's spell this.fightingCharacter.Spells.Sort( delegate(Spell spell1, Spell spell2) { // handle null values if (spell1 == null) { return (spell2 == null ? 0 : 1); } else if (spell2 == null) { return -1; } // sort by name return spell1.Name.CompareTo(spell2.Name); }); // configure the menu text titleText = "Spell Book"; selectButtonText = "Cast"; backButtonText = "Back"; xButtonText = String.Empty; yButtonText = String.Empty; leftTriggerText = String.Empty; rightTriggerText = String.Empty; } #endregion #region Input Handling /// <summary> /// Delegate for spell-selection events. /// </summary> public delegate void SpellSelectedHandler(Spell spell); /// <summary> /// Responds when an spell is selected by this menu. /// </summary> /// <remarks> /// Typically used by the calling menu, like the combat HUD menu, /// to respond to selection. /// </remarks> public event SpellSelectedHandler SpellSelected; /// <summary> /// Respond to the triggering of the Select action (and related key). /// </summary> protected override void SelectTriggered(Spell entry) { // check the parameter if (entry == null) { return; } // make sure the spell can be selected if (!CanSelectEntry(entry)) { return; } // if the event is valid, fire it and exit this screen if (SpellSelected != null) { SpellSelected(entry); ExitScreen(); return; } } /// <summary> /// Returns true if the specified spell can be selected. /// </summary> private bool CanSelectEntry(Spell entry) { if (entry == null) { return false; } return (statistics.MagicPoints >= entry.MagicPointCost) && (!entry.IsOffensive || CombatEngine.IsActive); } #endregion #region Drawing /// <summary> /// Draw the spell at the given position in the list. /// </summary> /// <param name="contentEntry">The spell to draw.</param> /// <param name="position">The position to draw the entry at.</param> /// <param name="isSelected">If true, this item is selected.</param> protected override void DrawEntry(Spell entry, Vector2 position, bool isSelected) { // check the parameter if (entry == null) { throw new ArgumentNullException("entry"); } SpriteBatch spriteBatch = ScreenManager.SpriteBatch; Vector2 drawPosition = position; Color color = isSelected ? Fonts.HighlightColor : Fonts.DisplayColor; // draw the icon spriteBatch.Draw(entry.IconTexture, drawPosition + iconOffset, Color.White); // draw the name drawPosition.Y += listLineSpacing / 4; drawPosition.X += nameColumnInterval; spriteBatch.DrawString(Fonts.GearInfoFont, entry.Name, drawPosition, color); // draw the level drawPosition.X += levelColumnInterval; spriteBatch.DrawString(Fonts.GearInfoFont, entry.Level.ToString(), drawPosition, color); // draw the power drawPosition.X += powerColumnInterval; string powerText = entry.GetPowerText(); Vector2 powerTextSize = Fonts.GearInfoFont.MeasureString(powerText); Vector2 powerPosition = drawPosition; powerPosition.Y -= (float)Math.Ceiling((powerTextSize.Y - 30f) / 2); spriteBatch.DrawString(Fonts.GearInfoFont, powerText, powerPosition, color); // draw the quantity drawPosition.X += magicCostColumnInterval; spriteBatch.DrawString(Fonts.GearInfoFont, entry.MagicPointCost.ToString(), drawPosition, color); // draw the cast button if needed if (isSelected) { selectButtonText = (CanSelectEntry(entry) && (SpellSelected != null)) ? "Cast" : String.Empty; } } /// <summary> /// Draw the description of the selected item. /// </summary> protected override void DrawSelectedDescription(Spell entry) { // check the parameter if (entry == null) { throw new ArgumentNullException("entry"); } SpriteBatch spriteBatch = ScreenManager.SpriteBatch; Vector2 position = descriptionTextPosition; // draw the insufficient-mp warning if (CombatEngine.IsActive && (entry.MagicPointCost > statistics.MagicPoints)) { // draw the insufficient-mp warning spriteBatch.DrawString(Fonts.DescriptionFont, "Not enough MP to Cast Spell", position, Color.Red); position.X += Fonts.DescriptionFont.MeasureString("Not enough MP to Cast Spell").X + 5; } // draw the description spriteBatch.DrawString(Fonts.DescriptionFont, Fonts.BreakTextIntoLines(entry.Description, 90, 3), position, Fonts.DescriptionColor); } /// <summary> /// Draw the column headers above the list. /// </summary> protected override void DrawColumnHeaders() { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; Vector2 position = listEntryStartPosition; position.X += nameColumnInterval; if (!String.IsNullOrEmpty(nameColumnText)) { spriteBatch.DrawString(Fonts.CaptionFont, nameColumnText, position, Fonts.CaptionColor); } position.X += levelColumnInterval; if (!String.IsNullOrEmpty(levelColumnText)) { spriteBatch.DrawString(Fonts.CaptionFont, levelColumnText, position, Fonts.CaptionColor); } position.X += powerColumnInterval; if (!String.IsNullOrEmpty(powerColumnText)) { spriteBatch.DrawString(Fonts.CaptionFont, powerColumnText, position, Fonts.CaptionColor); } position.X += magicCostColumnInterval; if (!String.IsNullOrEmpty(magicCostColumnText)) { spriteBatch.DrawString(Fonts.CaptionFont, magicCostColumnText, position, Fonts.CaptionColor); } } #endregion } }
/* Project Orleans Cloud Service SDK ver. 1.0 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.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Concurrency; namespace Orleans.Streams { internal class PersistentStreamPullingAgent : SystemTarget, IPersistentStreamPullingAgent { private static readonly IBackoffProvider DefaultBackoffProvider = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1)); private const int StreamInactivityCheckFrequency = 10; private readonly string streamProviderName; private readonly IStreamProviderRuntime providerRuntime; private readonly IStreamPubSub pubSub; private readonly Dictionary<StreamId, StreamConsumerCollection> pubSubCache; private readonly SafeRandom safeRandom; private readonly PersistentStreamProviderConfig config; private readonly Logger logger; private readonly CounterStatistic numReadMessagesCounter; private readonly CounterStatistic numSentMessagesCounter; private int numMessages; private IQueueAdapter queueAdapter; private IQueueCache queueCache; private IQueueAdapterReceiver receiver; private IStreamFailureHandler streamFailureHandler; private DateTime lastTimeCleanedPubSubCache; private IDisposable timer; internal readonly QueueId QueueId; internal PersistentStreamPullingAgent( GrainId id, string strProviderName, IStreamProviderRuntime runtime, IStreamPubSub streamPubSub, QueueId queueId, PersistentStreamProviderConfig config) : base(id, runtime.ExecutingSiloAddress, true) { if (runtime == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null"); if (strProviderName == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null"); QueueId = queueId; streamProviderName = strProviderName; providerRuntime = runtime; pubSub = streamPubSub; pubSubCache = new Dictionary<StreamId, StreamConsumerCollection>(); safeRandom = new SafeRandom(); this.config = config; numMessages = 0; logger = providerRuntime.GetLogger(GrainId + "-" + streamProviderName); logger.Info((int)ErrorCode.PersistentStreamPullingAgent_01, "Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.", GetType().Name, GrainId.ToDetailedString(), streamProviderName, Silo, QueueId.ToStringWithHashCode()); string statUniquePostfix = strProviderName + "." + QueueId; numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, statUniquePostfix)); numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, statUniquePostfix)); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, statUniquePostfix), () => pubSubCache.Count); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, statUniquePostfix), () => queueCache !=null ? queueCache.Size : 0); } /// <summary> /// Take responsibility for a new queues that was assigned to me via a new range. /// We first store the new queue in our internal data structure, try to initialize it and start a pumping timer. /// ERROR HANDLING: /// The resposibility to handle initializatoion and shutdown failures is inside the INewQueueAdapterReceiver code. /// The agent will call Initialize once and log an error. It will not call initiliaze again. /// The receiver itself may attempt later to recover from this error and do initialization again. /// The agent will assume initialization has succeeded and will subsequently start calling pumping receive. /// Same applies to shutdown. /// </summary> /// <param name="qAdapter"></param> /// <param name="queueAdapterCache"></param> /// <param name="failureHandler"></param> /// <returns></returns> public async Task Initialize(Immutable<IQueueAdapter> qAdapter, Immutable<IQueueAdapterCache> queueAdapterCache, Immutable<IStreamFailureHandler> failureHandler) { if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null"); if (failureHandler.Value == null) throw new ArgumentNullException("failureHandler", "Init: streamDeliveryFailureHandler should not be null"); logger.Info((int)ErrorCode.PersistentStreamPullingAgent_02, "Init of {0} {1} on silo {2} for queue {3}.", GetType().Name, GrainId.ToDetailedString(), Silo, QueueId.ToStringWithHashCode()); // Remove cast once we cleanup queueAdapter = qAdapter.Value; streamFailureHandler = failureHandler.Value; lastTimeCleanedPubSubCache = DateTime.UtcNow; try { receiver = queueAdapter.CreateReceiver(QueueId); } catch (Exception exc) { logger.Error((int)ErrorCode.PersistentStreamPullingAgent_02, "Exception while calling IQueueAdapter.CreateNewReceiver.", exc); return; } try { if (queueAdapterCache.Value != null) { queueCache = queueAdapterCache.Value.CreateQueueCache(QueueId); } } catch (Exception exc) { logger.Error((int)ErrorCode.PersistentStreamPullingAgent_23, "Exception while calling IQueueAdapterCache.CreateQueueCache.", exc); return; } try { var task = OrleansTaskExtentions.SafeExecute(() => receiver.Initialize(config.InitQueueTimeout)); task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_03, String.Format("QueueAdapterReceiver {0} failed to Initialize.", QueueId.ToStringWithHashCode())); await task; } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Initialize. No need to log again. } // Setup a reader for a new receiver. // Even if the receiver failed to initialise, treat it as OK and start pumping it. It's receiver responsibility to retry initialization. var randomTimerOffset = safeRandom.NextTimeSpan(config.GetQueueMsgsTimerPeriod); timer = base.RegisterTimer(AsyncTimerCallback, QueueId, randomTimerOffset, config.GetQueueMsgsTimerPeriod); logger.Info((int) ErrorCode.PersistentStreamPullingAgent_04, "Taking queue {0} under my responsibility.", QueueId.ToStringWithHashCode()); } public async Task Shutdown() { // Stop pulling from queues that are not in my range anymore. logger.Info((int)ErrorCode.PersistentStreamPullingAgent_05, "Shutdown of {0} responsible for queue: {1}", GetType().Name, QueueId.ToStringWithHashCode()); if (timer != null) { var tmp = timer; timer = null; Utils.SafeExecute(tmp.Dispose); } var unregisterTasks = new List<Task>(); var meAsStreamProducer = this.AsReference<IStreamProducerExtension>(); foreach (var streamId in pubSubCache.Keys) { logger.Info((int)ErrorCode.PersistentStreamPullingAgent_06, "Unregister PersistentStreamPullingAgent Producer for stream {0}.", streamId); unregisterTasks.Add(pubSub.UnregisterProducer(streamId, streamProviderName, meAsStreamProducer)); } try { var task = OrleansTaskExtentions.SafeExecute(() => receiver.Shutdown(config.InitQueueTimeout)); task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_07, String.Format("QueueAdapterReceiver {0} failed to Shutdown.", QueueId)); await task; } catch { // Just ignore this exception and proceed as if Shutdown has succeeded. // We already logged individual exceptions for individual calls to Shutdown. No need to log again. } try { await Task.WhenAll(unregisterTasks); } catch (Exception exc) { logger.Warn((int)ErrorCode.PersistentStreamPullingAgent_08, "Failed to unregister myself as stream producer to some streams taht used to be in my responsibility.", exc); } } public Task AddSubscriber( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { if (logger.IsVerbose) logger.Verbose((int)ErrorCode.PersistentStreamPullingAgent_09, "AddSubscriber: Stream={0} Subscriber={1}.", streamId, streamConsumer); // cannot await here because explicit consumers trigger this call, so it could cause a deadlock. AddSubscriber_Impl(subscriptionId, streamId, streamConsumer, null, filter) .LogException(logger, ErrorCode.PersistentStreamPullingAgent_26, String.Format("Failed to add subscription for stream {0}." , streamId)) .Ignore(); return TaskDone.Done; } // Called by rendezvous when new remote subscriber subscribes to this stream. private async Task AddSubscriber_Impl( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, StreamSequenceToken cacheToken, IStreamFilterPredicateWrapper filter) { StreamConsumerCollection streamDataCollection; if (!pubSubCache.TryGetValue(streamId, out streamDataCollection)) { streamDataCollection = new StreamConsumerCollection(DateTime.UtcNow); pubSubCache.Add(streamId, streamDataCollection); } StreamConsumerData data; if (!streamDataCollection.TryGetConsumer(subscriptionId, out data)) data = streamDataCollection.AddConsumer(subscriptionId, streamId, streamConsumer, filter); if (await DoHandshakeWithConsumer(data, cacheToken)) { if (data.State == StreamConsumerDataState.Inactive) RunConsumerCursor(data, filter).Ignore(); // Start delivering events if not actively doing so } } private async Task<bool> DoHandshakeWithConsumer( StreamConsumerData consumerData, StreamSequenceToken cacheToken) { StreamSequenceToken requestedToken = null; // if not cache, then we can't get cursor and there is no reason to ask consumer for token. if (queueCache != null) { Exception exceptionOccured = null; try { requestedToken = await AsyncExecutorWithRetries.ExecuteWithRetries( i => consumerData.StreamConsumer.GetSequenceToken(consumerData.SubscriptionId), AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => true, config.MaxEventDeliveryTime, DefaultBackoffProvider); if (requestedToken != null) { if (consumerData.Cursor != null) consumerData.Cursor.Dispose(); consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId.Guid, consumerData.StreamId.Namespace, requestedToken); } else { if (consumerData.Cursor == null) // if the consumer did not ask for a specific token and we already have a cursor, jsut keep using it. consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId.Guid, consumerData.StreamId.Namespace, cacheToken); } } catch (Exception exception) { exceptionOccured = exception; } if (exceptionOccured != null) { bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, false, null, requestedToken); if (faultedSubscription) return false; } } consumerData.LastToken = requestedToken; // use what ever the consumer asked for as LastToken for next handshake (even if he asked for null). // if we don't yet have a cursor (had errors in the handshake or data not available exc), get a cursor at the event that triggered that consumer subscription. if (consumerData.Cursor == null && queueCache != null) { try { consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId.Guid, consumerData.StreamId.Namespace, cacheToken); } catch (Exception) { consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId.Guid, consumerData.StreamId.Namespace, null); // just in case last GetCacheCursor failed. } } return true; } public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId) { RemoveSubscriber_Impl(subscriptionId, streamId); return TaskDone.Done; } public void RemoveSubscriber_Impl(GuidId subscriptionId, StreamId streamId) { StreamConsumerCollection streamData; if (!pubSubCache.TryGetValue(streamId, out streamData)) return; // remove consumer bool removed = streamData.RemoveConsumer(subscriptionId); if (removed && logger.IsVerbose) logger.Verbose((int)ErrorCode.PersistentStreamPullingAgent_10, "Removed Consumer: subscription={0}, for stream {1}.", subscriptionId, streamId); if (streamData.Count == 0) pubSubCache.Remove(streamId); } private async Task AsyncTimerCallback(object state) { try { var myQueueId = (QueueId)(state); if (timer == null) return; // timer was already removed, last tick IQueueAdapterReceiver rcvr = receiver; int maxCacheAddCount = queueCache != null ? queueCache.MaxAddCount : QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG; // loop through the queue until it is empty. while (timer != null) // timer will be set to null when we are asked to shudown. { var now = DateTime.UtcNow; // Try to cleanup the pubsub cache at the cadence of 10 times in the configurable StreamInactivityPeriod. if ((now - lastTimeCleanedPubSubCache) >= config.StreamInactivityPeriod.Divide(StreamInactivityCheckFrequency)) { lastTimeCleanedPubSubCache = now; CleanupPubSubCache(now); } if (queueCache != null) { IList<IBatchContainer> purgedItems; if (queueCache.TryPurgeFromCache(out purgedItems)) { await rcvr.MessagesDeliveredAsync(purgedItems); } } if (queueCache != null && queueCache.IsUnderPressure()) { // Under back pressure. Exit the loop. Will attempt again in the next timer callback. logger.Info((int)ErrorCode.PersistentStreamPullingAgent_24, "Stream cache is under pressure. Backing off."); return; } // Retrive one multiBatch from the queue. Every multiBatch has an IEnumerable of IBatchContainers, each IBatchContainer may have multiple events. IList<IBatchContainer> multiBatch = await rcvr.GetQueueMessagesAsync(maxCacheAddCount); if (multiBatch == null || multiBatch.Count == 0) return; // queue is empty. Exit the loop. Will attempt again in the next timer callback. if (queueCache != null) { queueCache.AddToCache(multiBatch); } numMessages += multiBatch.Count; numReadMessagesCounter.IncrementBy(multiBatch.Count); if (logger.IsVerbose2) logger.Verbose2((int)ErrorCode.PersistentStreamPullingAgent_11, "Got {0} messages from queue {1}. So far {2} msgs from this queue.", multiBatch.Count, myQueueId.ToStringWithHashCode(), numMessages); foreach (var group in multiBatch .Where(m => m != null) .GroupBy(container => new Tuple<Guid, string>(container.StreamGuid, container.StreamNamespace))) { var streamId = StreamId.GetStreamId(group.Key.Item1, queueAdapter.Name, group.Key.Item2); StreamConsumerCollection streamData; if (pubSubCache.TryGetValue(streamId, out streamData)) { streamData.RefreshActivity(now); StartInactiveCursors(streamData); // if this is an existing stream, start any inactive cursors } else { RegisterStream(streamId, group.First().SequenceToken, now).Ignore(); // if this is a new stream register as producer of stream in pub sub system } } } } catch (Exception exc) { logger.Error((int)ErrorCode.PersistentStreamPullingAgent_12, "Exception while PersistentStreamPullingAgentGrain.AsyncTimerCallback", exc); } } private void CleanupPubSubCache(DateTime now) { if (pubSubCache.Count == 0) return; var toRemove = pubSubCache.Where(pair => pair.Value.IsInactive(now, config.StreamInactivityPeriod)) .Select(pair => pair.Key) .ToList(); toRemove.ForEach(key => pubSubCache.Remove(key)); } private async Task RegisterStream(StreamId streamId, StreamSequenceToken firstToken, DateTime now) { var streamData = new StreamConsumerCollection(now); pubSubCache.Add(streamId, streamData); // Create a fake cursor to point into a cache. // That way we will not purge the event from the cache, until we talk to pub sub. // This will help ensure the "casual consistency" between pre-existing subscripton (of a potentially new already subscribed consumer) // and later production. var pinCursor = queueCache.GetCacheCursor(streamId.Guid, streamId.Namespace, firstToken); try { await RegisterAsStreamProducer(streamId, firstToken); }finally { // Cleanup the fake pinning cursor. pinCursor.Dispose(); } } private void StartInactiveCursors(StreamConsumerCollection streamData) { foreach (StreamConsumerData consumerData in streamData.AllConsumers()) { if (consumerData.State == StreamConsumerDataState.Inactive) { // wake up inactive consumers RunConsumerCursor(consumerData, consumerData.Filter).Ignore(); } else { if (consumerData.Cursor != null) { consumerData.Cursor.Refresh(); } } } } private async Task RunConsumerCursor(StreamConsumerData consumerData, IStreamFilterPredicateWrapper filterWrapper) { try { // double check in case of interleaving if (consumerData.State == StreamConsumerDataState.Active || consumerData.Cursor == null) return; consumerData.State = StreamConsumerDataState.Active; while (consumerData.Cursor != null && consumerData.Cursor.MoveNext()) { IBatchContainer batch = null; Exception exceptionOccured = null; try { Exception ignore; batch = consumerData.Cursor.GetCurrent(out ignore); } catch (Exception exc) { exceptionOccured = exc; if (consumerData.Cursor != null) consumerData.Cursor.Dispose(); consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId.Guid, consumerData.StreamId.Namespace, null); } // Apply filtering to this batch, if applicable if (filterWrapper != null && batch != null) { try { // Apply batch filter to this input batch, to see whether we should deliver it to this consumer. if (!batch.ShouldDeliver( consumerData.StreamId, filterWrapper.FilterData, filterWrapper.ShouldReceive)) continue; // Skip this batch -- nothing to do } catch (Exception exc) { var message = string.Format("Ignoring exception while trying to evaluate subscription filter function {0} on stream {1} in PersistentStreamPullingAgentGrain.RunConsumerCursor", filterWrapper, consumerData.StreamId); logger.Warn((int) ErrorCode.PersistentStreamPullingAgent_13, message, exc); } } try { numSentMessagesCounter.Increment(); if (batch != null) { await AsyncExecutorWithRetries.ExecuteWithRetries( i => DeliverBatchToConsumer(consumerData, batch), AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !(exception is DataNotAvailableException), config.MaxEventDeliveryTime, DefaultBackoffProvider); } } catch (Exception exc) { var message = string.Format("Exception while trying to deliver msgs to stream {0} in PersistentStreamPullingAgentGrain.RunConsumerCursor", consumerData.StreamId); logger.Error((int)ErrorCode.PersistentStreamPullingAgent_14, message, exc); exceptionOccured = new StreamEventDeliveryFailureException(consumerData.StreamId); } // if we failed to deliver a batch if (exceptionOccured != null) { bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, true, batch, batch != null ? batch.SequenceToken : null); if (faultedSubscription) return; } } consumerData.State = StreamConsumerDataState.Inactive; } catch (Exception exc) { // RunConsumerCursor is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception logger.Error((int)ErrorCode.PersistentStreamPullingAgent_15, "Ignored RunConsumerCursor Error", exc); consumerData.State = StreamConsumerDataState.Inactive; throw; } } private async Task DeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch) { StreamSequenceToken prevToken = consumerData.LastToken; Task<StreamSequenceToken> batchDeliveryTask; bool isRequestContextSet = batch.ImportRequestContext(); try { batchDeliveryTask = consumerData.StreamConsumer.DeliverBatch(consumerData.SubscriptionId, batch.AsImmutable(), prevToken); } finally { if (isRequestContextSet) { // clear RequestContext before await! RequestContext.Clear(); } } StreamSequenceToken newToken = await batchDeliveryTask; if (newToken != null) { consumerData.LastToken = newToken; consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId.Guid, consumerData.StreamId.Namespace, newToken); } else { consumerData.LastToken = batch.SequenceToken; // this is the currently delivered token } } private static async Task DeliverErrorToConsumer(StreamConsumerData consumerData, Exception exc, IBatchContainer batch) { Task errorDeliveryTask; bool isRequestContextSet = batch != null && batch.ImportRequestContext(); try { errorDeliveryTask = consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, exc); } finally { if (isRequestContextSet) { RequestContext.Clear(); // clear RequestContext before await! } } await errorDeliveryTask; } private async Task<bool> ErrorProtocol(StreamConsumerData consumerData, Exception exceptionOccured, bool isDeliveryError, IBatchContainer batch, StreamSequenceToken token) { // notify consumer about the error or that the data is not available. await OrleansTaskExtentions.ExecuteAndIgnoreException( () => DeliverErrorToConsumer( consumerData, exceptionOccured, batch)); // record that there was a delivery failure if (isDeliveryError) { await OrleansTaskExtentions.ExecuteAndIgnoreException( () => streamFailureHandler.OnDeliveryFailure( consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token)); } else { await OrleansTaskExtentions.ExecuteAndIgnoreException( () => streamFailureHandler.OnSubscriptionFailure( consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token)); } // if configured to fault on delivery failure and this is not an implicit subscription, fault and remove the subscription if (streamFailureHandler.ShouldFaultSubsriptionOnError && !SubscriptionMarker.IsImplicitSubscription(consumerData.SubscriptionId.Guid)) { try { // notify consumer of faulted subscription, if we can. await OrleansTaskExtentions.ExecuteAndIgnoreException( () => DeliverErrorToConsumer( consumerData, new FaultedSubscriptionException(consumerData.SubscriptionId, consumerData.StreamId), batch)); // mark subscription as faulted. await pubSub.FaultSubscription(consumerData.StreamId, consumerData.SubscriptionId); } finally { // remove subscription RemoveSubscriber_Impl(consumerData.SubscriptionId, consumerData.StreamId); } return true; } return false; } private async Task RegisterAsStreamProducer(StreamId streamId, StreamSequenceToken streamStartToken) { try { if (pubSub == null) throw new NullReferenceException("Found pubSub reference not set up correctly in RetreaveNewStream"); IStreamProducerExtension meAsStreamProducer = this.AsReference<IStreamProducerExtension>(); ISet<PubSubSubscriptionState> streamData = await pubSub.RegisterProducer(streamId, streamProviderName, meAsStreamProducer); if (logger.IsVerbose) logger.Verbose((int)ErrorCode.PersistentStreamPullingAgent_16, "Got back {0} Subscribers for stream {1}.", streamData.Count, streamId); var addSubscriptionTasks = new List<Task>(streamData.Count); foreach (PubSubSubscriptionState item in streamData) { addSubscriptionTasks.Add(AddSubscriber_Impl(item.SubscriptionId, item.Stream, item.Consumer, streamStartToken, item.Filter)); } await Task.WhenAll(addSubscriptionTasks); } catch (Exception exc) { // RegisterAsStreamProducer is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception logger.Error((int)ErrorCode.PersistentStreamPullingAgent_17, "Ignored RegisterAsStreamProducer Error", exc); throw; } } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Actions; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.Persistence.Querying; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Services.Implement; using Umbraco.Cms.Tests.Common.Builders; using Umbraco.Cms.Tests.Common.Testing; using Umbraco.Cms.Tests.Integration.Testing; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Services { /// <summary> /// Tests covering the UserService /// </summary> [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class UserServiceTests : UmbracoIntegrationTest { private UserService UserService => (UserService)GetRequiredService<IUserService>(); private IContentTypeService ContentTypeService => GetRequiredService<IContentTypeService>(); private IFileService FileService => GetRequiredService<IFileService>(); private IContentService ContentService => GetRequiredService<IContentService>(); [Test] public void Get_User_Permissions_For_Unassigned_Permission_Nodes() { // Arrange IUser user = CreateTestUser(out _); Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType) }; ContentService.Save(content); // Act EntityPermission[] permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); // Assert Assert.AreEqual(3, permissions.Length); Assert.AreEqual(17, permissions[0].AssignedPermissions.Length); Assert.AreEqual(17, permissions[1].AssignedPermissions.Length); Assert.AreEqual(17, permissions[2].AssignedPermissions.Length); } [Test] public void Get_User_Permissions_For_Assigned_Permission_Nodes() { // Arrange IUser user = CreateTestUser(out IUserGroup userGroup); Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType) }; ContentService.Save(content); ContentService.SetPermission(content[0], ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[0], ActionDelete.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[0], ActionMove.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[1], ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[1], ActionDelete.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[2], ActionBrowse.ActionLetter, new int[] { userGroup.Id }); // Act EntityPermission[] permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); // Assert Assert.AreEqual(3, permissions.Length); Assert.AreEqual(3, permissions[0].AssignedPermissions.Length); Assert.AreEqual(2, permissions[1].AssignedPermissions.Length); Assert.AreEqual(1, permissions[2].AssignedPermissions.Length); } [Test] public void Get_UserGroup_Assigned_Permissions() { // Arrange UserGroup userGroup = CreateTestUserGroup(); Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType) }; ContentService.Save(content); ContentService.SetPermission(content.ElementAt(0), ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content.ElementAt(0), ActionDelete.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content.ElementAt(0), ActionMove.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content.ElementAt(1), ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content.ElementAt(1), ActionDelete.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content.ElementAt(2), ActionBrowse.ActionLetter, new int[] { userGroup.Id }); // Act EntityPermission[] permissions = UserService.GetPermissions(userGroup, false, content[0].Id, content[1].Id, content[2].Id).ToArray(); // Assert Assert.AreEqual(3, permissions.Length); Assert.AreEqual(3, permissions[0].AssignedPermissions.Length); Assert.AreEqual(2, permissions[1].AssignedPermissions.Length); Assert.AreEqual(1, permissions[2].AssignedPermissions.Length); } [Test] public void Get_UserGroup_Assigned_And_Default_Permissions() { // Arrange UserGroup userGroup = CreateTestUserGroup(); Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType) }; ContentService.Save(content); ContentService.SetPermission(content[0], ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[0], ActionDelete.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[0], ActionMove.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[1], ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[1], ActionDelete.ActionLetter, new int[] { userGroup.Id }); // Act EntityPermission[] permissions = UserService.GetPermissions(userGroup, true, content[0].Id, content[1].Id, content[2].Id) .ToArray(); // Assert Assert.AreEqual(3, permissions.Length); Assert.AreEqual(3, permissions[0].AssignedPermissions.Length); Assert.AreEqual(2, permissions[1].AssignedPermissions.Length); Assert.AreEqual(17, permissions[2].AssignedPermissions.Length); } [Test] public void Get_All_User_Permissions_For_All_Nodes_With_Explicit_Permission() { // Arrange UserGroup userGroup1 = CreateTestUserGroup(); UserGroup userGroup2 = CreateTestUserGroup("test2", "Test 2"); UserGroup userGroup3 = CreateTestUserGroup("test3", "Test 3"); IUser user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); int defaultPermissionCount = userGroup3.Permissions.Count(); user.AddGroup(userGroup1); user.AddGroup(userGroup2); user.AddGroup(userGroup3); UserService.Save(user); Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType) }; ContentService.Save(content); // assign permissions - we aren't assigning anything explicit for group3 and nothing explicit for content[2] /w group2 ContentService.SetPermission(content[0], ActionBrowse.ActionLetter, new int[] { userGroup1.Id }); ContentService.SetPermission(content[0], ActionDelete.ActionLetter, new int[] { userGroup1.Id }); ContentService.SetPermission(content[0], ActionMove.ActionLetter, new int[] { userGroup2.Id }); ContentService.SetPermission(content[1], ActionBrowse.ActionLetter, new int[] { userGroup1.Id }); ContentService.SetPermission(content[1], ActionDelete.ActionLetter, new int[] { userGroup2.Id }); ContentService.SetPermission(content[2], ActionDelete.ActionLetter, new int[] { userGroup1.Id }); // Act // we don't pass in any nodes so it will return all of them EntityPermission[] result = UserService.GetPermissions(user).ToArray(); var permissions = result .GroupBy(x => x.EntityId) .ToDictionary(x => x.Key, x => x.GroupBy(a => a.UserGroupId).ToDictionary(a => a.Key, a => a.ToArray())); // Assert // there will be 3 since that is how many content items there are Assert.AreEqual(3, permissions.Count); // test permissions contains content[0] Assert.IsTrue(permissions.ContainsKey(content[0].Id)); // test that this permissions set contains permissions for all groups Assert.IsTrue(permissions[content[0].Id].ContainsKey(userGroup1.Id)); Assert.IsTrue(permissions[content[0].Id].ContainsKey(userGroup2.Id)); Assert.IsTrue(permissions[content[0].Id].ContainsKey(userGroup3.Id)); // test that the correct number of permissions are returned for each group Assert.AreEqual(2, permissions[content[0].Id][userGroup1.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(1, permissions[content[0].Id][userGroup2.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[0].Id][userGroup3.Id].SelectMany(x => x.AssignedPermissions).Count()); // test permissions contains content[1] Assert.IsTrue(permissions.ContainsKey(content[1].Id)); // test that this permissions set contains permissions for all groups Assert.IsTrue(permissions[content[1].Id].ContainsKey(userGroup1.Id)); Assert.IsTrue(permissions[content[1].Id].ContainsKey(userGroup2.Id)); Assert.IsTrue(permissions[content[1].Id].ContainsKey(userGroup3.Id)); // test that the correct number of permissions are returned for each group Assert.AreEqual(1, permissions[content[1].Id][userGroup1.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(1, permissions[content[1].Id][userGroup2.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[1].Id][userGroup3.Id].SelectMany(x => x.AssignedPermissions).Count()); // test permissions contains content[2] Assert.IsTrue(permissions.ContainsKey(content[2].Id)); // test that this permissions set contains permissions for all groups Assert.IsTrue(permissions[content[2].Id].ContainsKey(userGroup1.Id)); Assert.IsTrue(permissions[content[2].Id].ContainsKey(userGroup2.Id)); Assert.IsTrue(permissions[content[2].Id].ContainsKey(userGroup3.Id)); // test that the correct number of permissions are returned for each group Assert.AreEqual(1, permissions[content[2].Id][userGroup1.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[2].Id][userGroup2.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[2].Id][userGroup3.Id].SelectMany(x => x.AssignedPermissions).Count()); } [Test] public void Get_All_User_Group_Permissions_For_All_Nodes() { // Arrange UserGroup userGroup = CreateTestUserGroup(); Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType) }; ContentService.Save(content); ContentService.SetPermission(content[0], ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[0], ActionDelete.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[0], ActionMove.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[1], ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[1], ActionDelete.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(content[2], ActionDelete.ActionLetter, new int[] { userGroup.Id }); // Act // we don't pass in any nodes so it will return all of them var permissions = UserService.GetPermissions(userGroup, true) .GroupBy(x => x.EntityId) .ToDictionary(x => x.Key, x => x); // Assert Assert.AreEqual(3, permissions.Count); Assert.IsTrue(permissions.ContainsKey(content[0].Id)); Assert.AreEqual(3, permissions[content[0].Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.IsTrue(permissions.ContainsKey(content[1].Id)); Assert.AreEqual(2, permissions[content[1].Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.IsTrue(permissions.ContainsKey(content[2].Id)); Assert.AreEqual(1, permissions[content[2].Id].SelectMany(x => x.AssignedPermissions).Count()); } [Test] public void Calculate_Permissions_For_User_For_Path() { // see: http://issues.umbraco.org/issue/U4-10075#comment=67-40085 // for an overview of what this is testing const string path = "-1,1,2,3,4"; int[] pathIds = path.GetIdsFromPathReversed(); const int groupA = 7; const int groupB = 8; const int groupC = 9; var userGroups = new Dictionary<int, string[]> { { groupA, new[] { "S", "D", "F" } }, { groupB, new[] { "S", "D", "G", "K" } }, { groupC, new[] { "F", "G" } } }; EntityPermission[] permissions = new[] { new EntityPermission(groupA, 1, userGroups[groupA], isDefaultPermissions: true), new EntityPermission(groupA, 2, userGroups[groupA], isDefaultPermissions: true), new EntityPermission(groupA, 3, userGroups[groupA], isDefaultPermissions: true), new EntityPermission(groupA, 4, userGroups[groupA], isDefaultPermissions: true), new EntityPermission(groupB, 1, userGroups[groupB], isDefaultPermissions: true), new EntityPermission(groupB, 2, new[] { "F", "R" }, isDefaultPermissions: false), new EntityPermission(groupB, 3, userGroups[groupB], isDefaultPermissions: true), new EntityPermission(groupB, 4, userGroups[groupB], isDefaultPermissions: true), new EntityPermission(groupC, 1, userGroups[groupC], isDefaultPermissions: true), new EntityPermission(groupC, 2, userGroups[groupC], isDefaultPermissions: true), new EntityPermission(groupC, 3, new[] { "Q", "Z" }, isDefaultPermissions: false), new EntityPermission(groupC, 4, userGroups[groupC], isDefaultPermissions: true), }; // Permissions for Id 4 EntityPermissionSet result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds); Assert.AreEqual(4, result.EntityId); string[] allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(6, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "R", "Q", "Z" })); // Permissions for Id 3 result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds.Skip(1).ToArray()); Assert.AreEqual(3, result.EntityId); allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(6, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "R", "Q", "Z" })); // Permissions for Id 2 result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds.Skip(2).ToArray()); Assert.AreEqual(2, result.EntityId); allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(5, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "G", "R" })); // Permissions for Id 1 result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds.Skip(3).ToArray()); Assert.AreEqual(1, result.EntityId); allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(5, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "G", "K" })); } [Test] public void Determine_Deepest_Explicit_Permissions_For_Group_For_Path_1() { string path = "-1,1,2,3"; int[] pathIds = path.GetIdsFromPathReversed(); string[] defaults = new[] { "A", "B" }; var permissions = new List<EntityPermission> { new EntityPermission(9876, 1, defaults, isDefaultPermissions: true), new EntityPermission(9876, 2, new[] { "B", "C", "D" }, isDefaultPermissions: false), new EntityPermission(9876, 3, defaults, isDefaultPermissions: true) }; EntityPermission result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); Assert.AreEqual(3, result.AssignedPermissions.Length); Assert.IsFalse(result.IsDefaultPermissions); Assert.IsTrue(result.AssignedPermissions.ContainsAll(new[] { "B", "C", "D" })); Assert.AreEqual(2, result.EntityId); Assert.AreEqual(9876, result.UserGroupId); } [Test] public void Determine_Deepest_Explicit_Permissions_For_Group_For_Path_2() { string path = "-1,1,2,3"; int[] pathIds = path.GetIdsFromPathReversed(); string[] defaults = new[] { "A", "B", "C" }; var permissions = new List<EntityPermission> { new EntityPermission(9876, 1, defaults, isDefaultPermissions: true), new EntityPermission(9876, 2, defaults, isDefaultPermissions: true), new EntityPermission(9876, 3, defaults, isDefaultPermissions: true) }; EntityPermission result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: false); Assert.IsNull(result); } [Test] public void Determine_Deepest_Explicit_Permissions_For_Group_For_Path_3() { string path = "-1,1,2,3"; int[] pathIds = path.GetIdsFromPathReversed(); string[] defaults = new[] { "A", "B" }; var permissions = new List<EntityPermission> { new EntityPermission(9876, 1, defaults, isDefaultPermissions: true), new EntityPermission(9876, 2, defaults, isDefaultPermissions: true), new EntityPermission(9876, 3, defaults, isDefaultPermissions: true) }; EntityPermission result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); Assert.AreEqual(2, result.AssignedPermissions.Length); Assert.IsTrue(result.IsDefaultPermissions); Assert.IsTrue(result.AssignedPermissions.ContainsAll(defaults)); Assert.AreEqual(3, result.EntityId); Assert.AreEqual(9876, result.UserGroupId); } [Test] public void Get_User_Implicit_Permissions() { // Arrange UserGroup userGroup = CreateTestUserGroup(); Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); Content parent = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parent); Content child1 = ContentBuilder.CreateSimpleContent(contentType, "child1", parent.Id); ContentService.Save(child1); Content child2 = ContentBuilder.CreateSimpleContent(contentType, "child2", child1.Id); ContentService.Save(child2); ContentService.SetPermission(parent, ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(parent, ActionDelete.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(parent, ActionMove.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(parent, ActionBrowse.ActionLetter, new int[] { userGroup.Id }); ContentService.SetPermission(parent, ActionDelete.ActionLetter, new int[] { userGroup.Id }); // Act EntityPermissionSet permissions = UserService.GetPermissionsForPath(userGroup, child2.Path); // Assert string[] allPermissions = permissions.GetAllPermissions().ToArray(); Assert.AreEqual(3, allPermissions.Length); } [Test] public void Can_Delete_User() { IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); UserService.Delete(user, true); IUser deleted = UserService.GetUserById(user.Id); // Assert Assert.That(deleted, Is.Null); } [Test] public void Disables_User_Instead_Of_Deleting_If_Flag_Not_Set() { IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); UserService.Delete(user); IUser deleted = UserService.GetUserById(user.Id); // Assert Assert.That(deleted, Is.Not.Null); } [Test] public void Exists_By_Username() { IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); IUser user2 = UserService.CreateUserWithIdentity("john2@umbraco.io", "john2@umbraco.io"); Assert.IsTrue(UserService.Exists("JohnDoe")); Assert.IsFalse(UserService.Exists("notFound")); Assert.IsTrue(UserService.Exists("john2@umbraco.io")); } [Test] public void Get_By_Email() { IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetByEmail(user.Email)); Assert.IsNull(UserService.GetByEmail("do@not.find")); } [Test] public void Get_By_Username() { IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetByUsername(user.Username)); Assert.IsNull(UserService.GetByUsername("notFound")); } [Test] public void Get_By_Username_With_Backslash() { IUser user = UserService.CreateUserWithIdentity("mydomain\\JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetByUsername(user.Username)); Assert.IsNull(UserService.GetByUsername("notFound")); } [Test] public void Get_By_Object_Id() { IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetUserById(user.Id)); Assert.IsNull(UserService.GetUserById(9876)); } [Test] public void Find_By_Email_Starts_With() { IEnumerable<IUser> users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); // don't find this User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@hello.com"; UserService.Save(customUser); IEnumerable<IUser> found = UserService.FindByEmail("tes", 0, 100, out _, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } [Test] public void Find_By_Email_Ends_With() { IEnumerable<IUser> users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); // include this User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@test.com"; UserService.Save(customUser); IEnumerable<IUser> found = UserService.FindByEmail("test.com", 0, 100, out _, StringPropertyMatchType.EndsWith); Assert.AreEqual(11, found.Count()); } [Test] public void Find_By_Email_Contains() { IEnumerable<IUser> users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); // include this User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@test.com"; UserService.Save(customUser); IEnumerable<IUser> found = UserService.FindByEmail("test", 0, 100, out _, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } [Test] public void Find_By_Email_Exact() { IEnumerable<IUser> users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); // include this User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@test.com"; UserService.Save(customUser); IEnumerable<IUser> found = UserService.FindByEmail("hello@test.com", 0, 100, out _, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } [Test] public void Get_All_Paged_Users() { IEnumerable<IUser> users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); IEnumerable<IUser> found = UserService.GetAll(0, 2, out long totalRecs); Assert.AreEqual(2, found.Count()); // + 1 because of the built in admin user Assert.AreEqual(11, totalRecs); Assert.AreEqual("admin", found.First().Username); Assert.AreEqual("test0", found.Last().Username); } [Test] public void Get_All_Paged_Users_With_Filter() { IUser[] users = UserBuilder.CreateMulipleUsers(10).ToArray(); UserService.Save(users); IEnumerable<IUser> found = UserService.GetAll(0, 2, out long totalRecs, "username", Direction.Ascending, filter: "test"); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); Assert.AreEqual("test0", found.First().Username); Assert.AreEqual("test1", found.Last().Username); } [Test] public void Get_All_Paged_Users_For_Group() { UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); UserService.Save(userGroup); IUser[] users = UserBuilder.CreateMulipleUsers(10).ToArray(); for (int i = 0; i < 10;) { users[i].AddGroup(userGroup.ToReadOnlyGroup()); i = i + 2; } UserService.Save(users); long totalRecs; IEnumerable<IUser> found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, includeUserGroups: new[] { userGroup.Alias }); Assert.AreEqual(2, found.Count()); Assert.AreEqual(5, totalRecs); Assert.AreEqual("test0", found.First().Username); Assert.AreEqual("test2", found.Last().Username); } [Test] public void Get_All_Paged_Users_For_Group_With_Filter() { UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); UserService.Save(userGroup); IUser[] users = UserBuilder.CreateMulipleUsers(10).ToArray(); for (int i = 0; i < 10;) { users[i].AddGroup(userGroup.ToReadOnlyGroup()); i = i + 2; } for (int i = 0; i < 10;) { users[i].Name = "blah" + users[i].Name; i = i + 3; } UserService.Save(users); long totalRecs; IEnumerable<IUser> found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, userGroups: new[] { userGroup.Alias }, filter: "blah"); Assert.AreEqual(2, found.Count()); Assert.AreEqual(2, totalRecs); Assert.AreEqual("test0", found.First().Username); Assert.AreEqual("test6", found.Last().Username); } [Test] public void Count_All_Users() { IEnumerable<IUser> users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); User customUser = UserBuilder.CreateUser(); UserService.Save(customUser); int found = UserService.GetCount(MemberCountType.All); // + 1 because of the built in admin user Assert.AreEqual(12, found); } [Ignore("why?")] [Test] public void Count_All_Online_Users() { IEnumerable<IUser> users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.LastLoginDate = DateTime.Now.AddMinutes(i * -2)); UserService.Save(users); User customUser = UserBuilder.CreateUser(); throw new NotImplementedException(); } [Test] public void Count_All_Locked_Users() { IEnumerable<IUser> users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsLockedOut = i % 2 == 0); UserService.Save(users); User customUser = UserBuilder.CreateUser(); customUser.IsLockedOut = true; UserService.Save(customUser); int found = UserService.GetCount(MemberCountType.LockedOut); Assert.AreEqual(6, found); } [Test] public void Count_All_Approved_Users() { IEnumerable<IUser> users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsApproved = i % 2 == 0); UserService.Save(users); User customUser = UserBuilder.CreateUser(); customUser.IsApproved = false; UserService.Save(customUser); int found = UserService.GetCount(MemberCountType.Approved); // + 1 because of the built in admin user Assert.AreEqual(6, found); } [Test] public void Can_Persist_New_User() { // Act IUser membershipUser = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); // Assert Assert.That(membershipUser.HasIdentity, Is.True); Assert.That(membershipUser.Id, Is.GreaterThan(0)); IUser user = membershipUser as User; Assert.That(user, Is.Not.Null); } [Test] public void Can_Persist_New_User_With_Hashed_Password() { // Act // NOTE: Normally the hash'ing would be handled in the membership provider, so the service just saves the password string password = "123456"; var hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); var globalSettings = new GlobalSettings(); var membershipUser = new User(globalSettings, "JohnDoe", "john@umbraco.io", encodedPassword, encodedPassword); UserService.Save(membershipUser); // Assert Assert.That(membershipUser.HasIdentity, Is.True); Assert.That(membershipUser.RawPasswordValue, Is.Not.EqualTo(password)); Assert.That(membershipUser.RawPasswordValue, Is.EqualTo(encodedPassword)); IUser user = membershipUser as User; Assert.That(user, Is.Not.Null); } [Test] public void Can_Add_And_Remove_Sections_From_UserGroup() { var userGroup = new UserGroup(ShortStringHelper) { Alias = "Group1", Name = "Group 1" }; userGroup.AddAllowedSection("content"); userGroup.AddAllowedSection("mediat"); UserService.Save(userGroup); IUserGroup result1 = UserService.GetUserGroupById(userGroup.Id); Assert.AreEqual(2, result1.AllowedSections.Count()); // adds some allowed sections userGroup.AddAllowedSection("test1"); userGroup.AddAllowedSection("test2"); userGroup.AddAllowedSection("test3"); userGroup.AddAllowedSection("test4"); UserService.Save(userGroup); result1 = UserService.GetUserGroupById(userGroup.Id); Assert.AreEqual(6, result1.AllowedSections.Count()); // simulate clearing the sections foreach (string s in userGroup.AllowedSections) { result1.RemoveAllowedSection(s); } // now just re-add a couple result1.AddAllowedSection("test3"); result1.AddAllowedSection("test4"); UserService.Save(result1); // Assert // re-get result1 = UserService.GetUserGroupById(userGroup.Id); Assert.AreEqual(2, result1.AllowedSections.Count()); } [Test] public void Can_Remove_Section_From_All_Assigned_UserGroups() { var userGroup1 = new UserGroup(ShortStringHelper) { Alias = "Group1", Name = "Group 1" }; var userGroup2 = new UserGroup(ShortStringHelper) { Alias = "Group2", Name = "Group 2" }; UserService.Save(userGroup1); UserService.Save(userGroup2); // adds some allowed sections userGroup1.AddAllowedSection("test"); userGroup2.AddAllowedSection("test"); UserService.Save(userGroup1); UserService.Save(userGroup2); // now clear the section from all users UserService.DeleteSectionFromAllUserGroups("test"); // Assert IUserGroup result1 = UserService.GetUserGroupById(userGroup1.Id); IUserGroup result2 = UserService.GetUserGroupById(userGroup2.Id); Assert.IsFalse(result1.AllowedSections.Contains("test")); Assert.IsFalse(result2.AllowedSections.Contains("test")); } [Test] public void Can_Add_Section_To_All_UserGroups() { var userGroup1 = new UserGroup(ShortStringHelper) { Alias = "Group1", Name = "Group 1" }; userGroup1.AddAllowedSection("test"); var userGroup2 = new UserGroup(ShortStringHelper) { Alias = "Group2", Name = "Group 2" }; userGroup2.AddAllowedSection("test"); var userGroup3 = new UserGroup(ShortStringHelper) { Alias = "Group3", Name = "Group 3" }; UserService.Save(userGroup1); UserService.Save(userGroup2); UserService.Save(userGroup3); // Assert IUserGroup result1 = UserService.GetUserGroupById(userGroup1.Id); IUserGroup result2 = UserService.GetUserGroupById(userGroup2.Id); IUserGroup result3 = UserService.GetUserGroupById(userGroup3.Id); Assert.IsTrue(result1.AllowedSections.Contains("test")); Assert.IsTrue(result2.AllowedSections.Contains("test")); Assert.IsFalse(result3.AllowedSections.Contains("test")); // now add the section to all groups foreach (UserGroup userGroup in new[] { userGroup1, userGroup2, userGroup3 }) { userGroup.AddAllowedSection("test"); UserService.Save(userGroup); } // Assert result1 = UserService.GetUserGroupById(userGroup1.Id); result2 = UserService.GetUserGroupById(userGroup2.Id); result3 = UserService.GetUserGroupById(userGroup3.Id); Assert.IsTrue(result1.AllowedSections.Contains("test")); Assert.IsTrue(result2.AllowedSections.Contains("test")); Assert.IsTrue(result3.AllowedSections.Contains("test")); } [Test] public void Cannot_Create_User_With_Empty_Username() { // Act & Assert Assert.Throws<ArgumentException>(() => UserService.CreateUserWithIdentity(string.Empty, "john@umbraco.io")); } [Test] public void Cannot_Save_User_With_Empty_Username() { // Arrange IUser user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); user.Username = string.Empty; // Act & Assert Assert.Throws<ArgumentException>(() => UserService.Save(user)); } [Test] public void Cannot_Save_User_With_Empty_Name() { // Arrange IUser user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); user.Name = string.Empty; // Act & Assert Assert.Throws<ArgumentException>(() => UserService.Save(user)); } [Test] public void Get_By_Profile_Username() { // Arrange IUser user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); // Act IProfile profile = UserService.GetProfileByUserName(user.Username); // Assert Assert.IsNotNull(profile); Assert.AreEqual(user.Username, profile.Name); Assert.AreEqual(user.Id, profile.Id); } [Test] public void Get_By_Profile_Id() { // Arrange IUser user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); // Act IProfile profile = UserService.GetProfileById((int)user.Id); // Assert Assert.IsNotNull(profile); Assert.AreEqual(user.Username, profile.Name); Assert.AreEqual(user.Id, profile.Id); } [Test] public void Get_By_Profile_Id_Must_Return_Null_If_User_Does_Not_Exist() { IProfile profile = UserService.GetProfileById(42); // Assert Assert.IsNull(profile); } [Test] public void GetProfilesById_Must_Return_Empty_If_User_Does_Not_Exist() { IEnumerable<IProfile> profiles = UserService.GetProfilesById(42); // Assert CollectionAssert.IsEmpty(profiles); } [Test] public void Get_User_By_Username() { // Arrange IUser originalUser = CreateTestUser(out _); // Act var updatedItem = (User)UserService.GetByUsername(originalUser.Username); // Assert Assert.IsNotNull(updatedItem); Assert.That(updatedItem.Id, Is.EqualTo(originalUser.Id)); Assert.That(updatedItem.Name, Is.EqualTo(originalUser.Name)); Assert.That(updatedItem.Language, Is.EqualTo(originalUser.Language)); Assert.That(updatedItem.IsApproved, Is.EqualTo(originalUser.IsApproved)); Assert.That(updatedItem.RawPasswordValue, Is.EqualTo(originalUser.RawPasswordValue)); Assert.That(updatedItem.IsLockedOut, Is.EqualTo(originalUser.IsLockedOut)); Assert.IsTrue(updatedItem.StartContentIds.UnsortedSequenceEqual(originalUser.StartContentIds)); Assert.IsTrue(updatedItem.StartMediaIds.UnsortedSequenceEqual(originalUser.StartMediaIds)); Assert.That(updatedItem.Email, Is.EqualTo(originalUser.Email)); Assert.That(updatedItem.Username, Is.EqualTo(originalUser.Username)); Assert.That(updatedItem.AllowedSections.Count(), Is.EqualTo(originalUser.AllowedSections.Count())); } [Test] public void Can_Get_Assigned_StartNodes_For_User() { Content[] startContentItems = BuildContentItems(3); UserGroup testUserGroup = CreateTestUserGroup(); int userGroupId = testUserGroup.Id; CreateTestUsers(startContentItems.Select(x => x.Id).ToArray(), testUserGroup, 3); IEnumerable<IUser> usersInGroup = UserService.GetAllInGroup(userGroupId); foreach (IUser user in usersInGroup) { Assert.AreEqual(user.StartContentIds.Length, startContentItems.Length); } } private Content[] BuildContentItems(int numberToCreate) { Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); var startContentItems = new List<Content>(); for (int i = 0; i < numberToCreate; i++) { startContentItems.Add(ContentBuilder.CreateSimpleContent(contentType)); } ContentService.Save(startContentItems); return startContentItems.ToArray(); } private IUser CreateTestUser(out IUserGroup userGroup) { userGroup = CreateTestUserGroup(); IUser user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); user.AddGroup(userGroup.ToReadOnlyGroup()); UserService.Save(user); return user; } private List<IUser> CreateTestUsers(int[] startContentIds, IUserGroup userGroup, int numberToCreate) { var users = new List<IUser>(); for (int i = 0; i < numberToCreate; i++) { IUser user = UserService.CreateUserWithIdentity($"test{i}", $"test{i}@test.com"); user.AddGroup(userGroup.ToReadOnlyGroup()); var updateable = (User)user; updateable.StartContentIds = startContentIds; UserService.Save(user); users.Add(user); } return users; } private UserGroup CreateTestUserGroup(string alias = "testGroup", string name = "Test Group") { string[] permissions = "ABCDEFGHIJ1234567".ToCharArray().Select(x => x.ToString()).ToArray(); UserGroup userGroup = UserGroupBuilder.CreateUserGroup(alias, name, permissions: permissions); UserService.Save(userGroup); return userGroup; } } }
using System; using System.IO; using System.Collections.Generic; using System.Text; using LumiSoft.Net.IO; using LumiSoft.Net.MIME; namespace LumiSoft.Net.MIME { /// <summary> /// Represents a MIME entity. Defined in RFC 2045 2.4. /// </summary> public class MIME_Entity : IDisposable { private bool m_IsDisposed = false; private MIME_Entity m_pParent = null; private MIME_h_Collection m_pHeader = null; private MIME_b m_pBody = null; private MIME_b_Provider m_pBodyProvider = null; /// <summary> /// Default constructor. /// </summary> public MIME_Entity() { m_pHeader = new MIME_h_Collection(new MIME_h_Provider()); m_pBodyProvider = new MIME_b_Provider(); } #region method Dispose /// <summary> /// Cleans up any resources being used. This method is thread-safe. /// </summary> public void Dispose() { lock(this){ if(m_IsDisposed){ return; } m_IsDisposed = true; m_pHeader = null; m_pParent = null; } } #endregion #region method ToFile /// <summary> /// Stores MIME entity to the specified file. /// </summary> /// <param name="file">File name with path where to store MIME entity.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>file</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void ToFile(string file,MIME_Encoding_EncodedWord headerWordEncoder,Encoding headerParmetersCharset) { if(file == null){ throw new ArgumentNullException("file"); } if(file == ""){ throw new ArgumentException("Argument 'file' value must be specified."); } using(FileStream fs = File.Create(file)){ ToStream(fs,headerWordEncoder,headerParmetersCharset); } } #endregion #region method ToStream /// <summary> /// Store MIME enity to the specified stream. /// </summary> /// <param name="stream">Stream where to store MIME entity. Storing starts form stream current position.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> public void ToStream(Stream stream,MIME_Encoding_EncodedWord headerWordEncoder,Encoding headerParmetersCharset) { if(stream == null){ throw new ArgumentNullException("stream"); } m_pHeader.ToStream(stream,headerWordEncoder,headerParmetersCharset); stream.Write(new byte[]{(int)'\r',(int)'\n'},0,2); m_pBody.ToStream(stream,headerWordEncoder,headerParmetersCharset); } #endregion #region override method ToString /// <summary> /// Returns MIME entity as string. /// </summary> /// <returns>Returns MIME entity as string.</returns> public override string ToString() { using(MemoryStream ms = new MemoryStream()){ ToStream(ms,null,null); return Encoding.UTF8.GetString(ms.ToArray()); } } #endregion #region method Parse /// <summary> /// Parses MIME entiry from the specified stream. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="defaultContentType">Default content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>defaultContentType</b> is null reference.</exception> internal void Parse(SmartStream stream,MIME_h_ContentType defaultContentType) { if(stream == null){ throw new ArgumentNullException("stream"); } if(defaultContentType == null){ throw new ArgumentNullException("defaultContentType"); } m_pHeader.Parse(stream); this.Body = m_pBodyProvider.Parse(this,stream,defaultContentType); } #endregion #region method SetParent /// <summary> /// Sets MIME entity parent entity. /// </summary> /// <param name="parent">Parent entity.</param> internal void SetParent(MIME_Entity parent) { m_pParent = parent; } #endregion #region Properties Implementation // Permanent headerds list: http://www.rfc-editor.org/rfc/rfc4021.txt /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get{ return m_IsDisposed; } } /// <summary> /// Gets if this entity is modified since it has loaded. /// </summary> /// <exception cref="ObjectDisposedException">Is riased when this class is disposed and this property is accessed.</exception> public bool IsModified { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } return m_pHeader.IsModified || m_pBody.IsModified; } } /// <summary> /// Gets the parent entity of this entity, returns null if this is the root entity. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public MIME_Entity Parent { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } return m_pParent; } } /// <summary> /// Gets MIME entity header field collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public MIME_h_Collection Header { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } return m_pHeader; } } /// <summary> /// Gets or sets MIME version number. Value null means that header field does not exist. Normally this value is 1.0. Defined in RFC 2045 section 4. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>An indicator that this message is formatted according to the MIME /// standard, and an indication of which version of MIME is used.</remarks> public string MimeVersion { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("MIME-Version"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("MIME-Version"); } else{ MIME_h h = m_pHeader.GetFirst("MIME-Version"); if(h == null){ h = new MIME_h_Unstructured("MIME-Version",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets content body part ID. Value null means that header field does not exist. Defined in RFC 2045 7. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>Specifies a Unique ID for one MIME body part of the content of a message.</remarks> public string ContentID { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-ID"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-ID"); } else{ MIME_h h = m_pHeader.GetFirst("Content-ID"); if(h == null){ h = new MIME_h_Unstructured("Content-ID",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets description of message body part. Value null means that header field does not exist. Defined in RFC 2045 8. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>Description of a particular body part of a message; for example, a caption for an image body part.</remarks> public string ContentDescription { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-Description"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-Description"); } else{ MIME_h h = m_pHeader.GetFirst("Content-Description"); if(h == null){ h = new MIME_h_Unstructured("Content-Description",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets content transfer encoding. Value null means that header field does not exist. /// RFC defined values are in <see cref="MIME_TransferEncodings">MIME_TransferEncodings</see>. Defined in RFC 2045 6. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>Coding method used in a MIME message body part.</remarks> public string ContentTransferEncoding { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h_Unstructured h = (MIME_h_Unstructured)m_pHeader.GetFirst("Content-Transfer-Encoding"); if(h != null){ return h.Value; } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-Transfer-Encoding"); } else{ MIME_h h = m_pHeader.GetFirst("Content-Transfer-Encoding"); if(h == null){ h = new MIME_h_Unstructured("Content-Transfer-Encoding",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets MIME content type. Value null means that header field does not exist. Defined in RFC 2045 5. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public MIME_h_ContentType ContentType { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-Type"); if(h != null){ if(!(h is MIME_h_ContentType)){ throw new ParseException("Header field 'ContentType' parsing failed."); } return (MIME_h_ContentType)h; } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-Type"); } else{ MIME_h h = m_pHeader.GetFirst("Content-Type"); if(h == null){ m_pHeader.Add(value); } else{ m_pHeader.ReplaceFirst(value); } } } } /// <summary> /// Gets or sets base to be used for resolving relative URIs within this content part. Value null means that header field does not exist. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>Base to be used for resolving relative URIs within this content part. See also Content-Location.</remarks> public string ContentBase { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-Base"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-Base"); } else{ MIME_h h = m_pHeader.GetFirst("Content-Base"); if(h == null){ h = new MIME_h_Unstructured("Content-Base",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets URI for retrieving a body part. Value null means that header field does not exist. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>URI using which the content of this body-part part was retrieved, /// might be retrievable, or which otherwise gives a globally unique identification of the content.</remarks> public string ContentLocation { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-Location"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-Location"); } else{ MIME_h h = m_pHeader.GetFirst("Content-Location"); if(h == null){ h = new MIME_h_Unstructured("Content-Location",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets content features of a MIME body part. Value null means that header field does not exist. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>The 'Content-features:' header can be used to annotate a MIME body part with a media feature expression, /// to indicate features of the body part content. See also RFC 2533, RFC 2506, and RFC 2045.</remarks> public string Contentfeatures { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-features"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-features"); } else{ MIME_h h = m_pHeader.GetFirst("Content-features"); if(h == null){ h = new MIME_h_Unstructured("Content-features",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets content disposition. Value null means that header field does not exist. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>Indicates whether a MIME body part is to be shown inline or is an attachment; can also indicate a /// suggested filename for use when saving an attachment to a file.</remarks> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public MIME_h_ContentDisposition ContentDisposition { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-Dispostition"); if(h != null){ if(!(h is MIME_h_ContentType)){ throw new ParseException("Header field 'ContentDisposition' parsing failed."); } return (MIME_h_ContentDisposition)h; } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-Dispostition"); } else{ MIME_h h = m_pHeader.GetFirst("Content-Dispostition"); if(h == null){ m_pHeader.Add(value); } else{ m_pHeader.ReplaceFirst(value); } } } } /// <summary> /// Gets or sets language of message content. Value null means that header field does not exist. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>Can include a code for the natural language used in a message; e.g., 'en' for English. /// Can also contain a list of languages for a message containing more than one language.</remarks> public string ContentLanguage { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-Language"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-Language"); } else{ MIME_h h = m_pHeader.GetFirst("Content-Language"); if(h == null){ h = new MIME_h_Unstructured("Content-Language",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets message alternative content. Value null means that header field does not exist. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>Information about the media features of alternative content formats available for the current message.</remarks> public string ContentAlternative { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-Alternative"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-Alternative"); } else{ MIME_h h = m_pHeader.GetFirst("Content-Alternative"); if(h == null){ h = new MIME_h_Unstructured("Content-Alternative",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets content MD5 checksum. Value null means that header field does not exist. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>Checksum of content to ensure that it has not been modified.</remarks> public string ContentMD5 { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-MD5"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-MD5"); } else{ MIME_h h = m_pHeader.GetFirst("Content-MD5"); if(h == null){ h = new MIME_h_Unstructured("Content-MD5",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets time duration of content. Value null means that header field does not exist. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <remarks>Time duration of body part content, in seconds (e.g., for audio message).</remarks> public string ContentDuration { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } MIME_h h = m_pHeader.GetFirst("Content-Duration"); if(h != null){ return h.ToString(); } else{ return null; } } set{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(value == null){ m_pHeader.RemoveAll("Content-Duration"); } else{ MIME_h h = m_pHeader.GetFirst("Content-Duration"); if(h == null){ h = new MIME_h_Unstructured("Content-Duration",value); m_pHeader.Add(h); } else{ ((MIME_h_Unstructured)h).Value = value; } } } } /// <summary> /// Gets or sets MIME entity body. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null reference passed.</exception> public MIME_b Body { get{ return m_pBody; } set{ if(value == null){ throw new ArgumentNullException("Body"); } m_pBody = value; m_pBody.SetParent(this); this.ContentType = m_pBody.ContentType; } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Feedback.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Packaging; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using NuGet.VisualStudio; using Roslyn.Utilities; using Roslyn.VisualStudio.ProjectSystem; using VSLangProj; using VSLangProj140; using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// The Workspace for running inside Visual Studio. /// </summary> internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace { private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1); private const string AppCodeFolderName = "App_Code"; protected readonly IServiceProvider ServiceProvider; private readonly IVsUIShellOpenDocument _shellOpenDocument; private readonly IVsTextManager _textManager; // Not readonly because it needs to be set in the derived class' constructor. private VisualStudioProjectTracker _projectTracker; // document worker coordinator private ISolutionCrawlerRegistrationService _registrationService; private readonly ForegroundThreadAffinitizedObject _foregroundObject = new ForegroundThreadAffinitizedObject(); public VisualStudioWorkspaceImpl( SVsServiceProvider serviceProvider, WorkspaceBackgroundWork backgroundWork) : base( CreateHostServices(serviceProvider), backgroundWork) { this.ServiceProvider = serviceProvider; _textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager; _shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); var session = serviceProvider.GetService(typeof(SVsLog)) as IVsSqmMulti; var profileService = serviceProvider.GetService(typeof(SVsFeedbackProfile)) as IVsFeedbackProfile; // We have Watson hits where this came back null, so guard against it if (profileService != null) { Sqm.LogSession(session, profileService.IsMicrosoftInternal); } } internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider) { var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); return MefV1HostServices.Create(composition.DefaultExportProvider); } protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService) { var projectTracker = new VisualStudioProjectTracker(serviceProvider); // Ensure the document tracking service is initialized on the UI thread var documentTrackingService = this.Services.GetService<IDocumentTrackingService>(); var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService); projectTracker.DocumentProvider = documentProvider; projectTracker.MetadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>(); projectTracker.RuleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>(); this.SetProjectTracker(projectTracker); var workspaceHost = new VisualStudioWorkspaceHost(this); projectTracker.RegisterWorkspaceHost(workspaceHost); projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost); saveEventsService.StartSendingSaveEvents(); // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); } /// <summary>NOTE: Call only from derived class constructor</summary> protected void SetProjectTracker(VisualStudioProjectTracker projectTracker) { _projectTracker = projectTracker; } internal VisualStudioProjectTracker ProjectTracker { get { return _projectTracker; } } internal void ClearReferenceCache() { _projectTracker.MetadataReferenceProvider.ClearCache(); } internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId) { var project = GetHostProject(documentId.ProjectId); if (project != null) { return project.GetDocumentOrAdditionalDocument(documentId); } return null; } internal IVisualStudioHostProject GetHostProject(ProjectId projectId) { return this.ProjectTracker.GetProject(projectId); } private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project) { project = GetHostProject(projectId); return project != null; } internal override bool TryApplyChanges( Microsoft.CodeAnalysis.Solution newSolution, IProgressTracker progressTracker) { // first make sure we can edit the document we will be updating (check them out from source control, etc) var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList(); if (changedDocs.Count > 0) { this.EnsureEditableDocuments(changedDocs); } return base.TryApplyChanges(newSolution, progressTracker); } public override bool CanOpenDocuments { get { return true; } } internal override bool CanChangeActiveContextDocument { get { return true; } } public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: case ApplyChangesKind.ChangeAdditionalDocument: return true; default: return false; } } private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { hierarchy = null; project = null; return this.TryGetHostProject(projectId, out hostProject) && this.TryGetHierarchy(projectId, out hierarchy) && hierarchy.TryGetProject(out project); } internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project)) { throw new ArgumentException(string.Format(ServicesVSResources.CouldNotFindProject, projectId)); } } internal EnvDTE.Project TryGetDTEProject(ProjectId projectId) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; return TryGetProjectData(projectId, out hostProject, out hierarchy, out project) ? project : null; } internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; try { GetProjectData(projectId, out hostProject, out hierarchy, out project); } catch (ArgumentException) { return false; } var vsProject = (VSProject)project.Object; try { vsProject.References.Add(assemblyName); } catch (Exception) { return false; } return true; } private string GetAnalyzerPath(AnalyzerReference analyzerReference) { return analyzerReference.FullPath; } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Add(filePath); } } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Remove(filePath); } } private string GetMetadataPath(MetadataReference metadataReference) { var fileMetadata = metadataReference as PortableExecutableReference; if (fileMetadata != null) { return fileMetadata.FilePath; } return null; } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; vsProject.References.Add(filePath); } } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; Reference reference = vsProject.References.Find(filePath); if (reference != null) { reference.Remove(); } } } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); var vsProject = (VSProject)project.Object; vsProject.References.AddProject(refProject); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); var vsProject = (VSProject)project.Object; foreach (Reference reference in vsProject.References) { if (reference.SourceProject == refProject) { reference.Remove(); } } } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: false); } protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: true); } protected override void UpdateGeneratedDocuments(ProjectId projectId, ImmutableArray<DocumentInfo> documentsRemoved, ImmutableArray<DocumentInfo> documentsAdded) { Debug.Assert(documentsRemoved.All(d => d.Id.ProjectId == projectId)); Debug.Assert(documentsAdded.All(d => d.Id.ProjectId == projectId)); var project = GetHostProject(projectId); project.UpdateGeneratedDocuments(documentsRemoved, documentsAdded); } private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. var folders = info.Folders.AsEnumerable(); if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } folders = FilterFolderForProjectType(project, folders); if (IsWebsite(project)) { AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else if (folders.Any()) { AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else { AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } } private bool IsWebsite(EnvDTE.Project project) { return project.Kind == VsWebSite.PrjKind.prjKindVenusProject; } private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders) { foreach (var folder in folders) { var items = GetAllItems(project.ProjectItems); var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0); if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile) { yield return folder; } } } private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return SpecializedCollections.EmptyEnumerable<ProjectItem>(); } var items = projectItems.OfType<ProjectItem>(); return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems))); } #if false protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } var name = Path.GetFileName(filePath); if (folders.Any()) { AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } else { AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } } #endif private ProjectItem AddDocumentToProject( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { string folderPath; if (!project.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToFolder( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, IEnumerable<string> folders, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { var folder = project.FindOrCreateFolder(folders); string folderPath; if (!folder.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToProjectItems( IVisualStudioHostProject hostProject, ProjectItems projectItems, DocumentId documentId, string folderPath, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText, string filePath, bool isAdditionalDocument) { if (filePath == null) { var baseName = Path.GetFileNameWithoutExtension(documentName); var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind); var uniqueName = projectItems.GetUniqueName(baseName, extension); filePath = Path.Combine(folderPath, uniqueName); } if (initialText != null) { using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8)) { initialText.Write(writer); } } using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId)) { return projectItems.AddFromFile(filePath); } } protected void RemoveDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var document = this.GetHostDocument(documentId); if (document != null) { var project = document.Project.Hierarchy as IVsProject3; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } int result; project.RemoveItem(0, itemId, out result); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } public override void OpenDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void CloseDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public override void CloseAdditionalDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public bool TryGetInfoBarData(out IVsWindowFrame frame, out IVsInfoBarUIFactory factory) { frame = null; factory = null; var monitorSelectionService = ServiceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; object value = null; // We want to get whichever window is currently in focus (including toolbars) as we could have had an exception thrown from the error list or interactive window if (monitorSelectionService != null && ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_WindowFrame, out value))) { frame = value as IVsWindowFrame; } else { return false; } factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory; return frame != null && factory != null; } public void OpenDocumentCore(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!_foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.ThisWorkspaceOnlySupportsOpeningDocumentsOnTheUIThread); } var document = this.GetHostDocument(documentId); if (document != null && document.Project != null) { IVsWindowFrame frame; if (TryGetFrame(document, out frame)) { if (activate) { frame.Show(); } else { frame.ShowNoActivate(); } } } } private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame) { frame = null; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // If the ItemId is Nil, then IVsProject would not be able to open the // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only // depends on the file path. uint itemid; IVsUIHierarchy uiHierarchy; OLEServiceProvider oleServiceProvider; return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject( document.FilePath, VSConstants.LOGVIEWID.TextView_guid, out oleServiceProvider, out uiHierarchy, out itemid, out frame)); } else { // If the ItemId is not Nil, then we should not call IVsUIShellDocument // .OpenDocumentViaProject here because that simply takes a file path and opens the // file within the context of the first project it finds. That would cause problems // if the document we're trying to open is actually a linked file in another // project. So, we get the project's hierarchy and open the document using its item // ID. // It's conceivable that IVsHierarchy might not implement IVsProject. However, // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to // use here. var vsProject = document.Project.Hierarchy as IVsProject; return vsProject != null && ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame)); } } public void CloseDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (this.IsDocumentOpen(documentId)) { var document = this.GetHostDocument(documentId); if (document != null) { IVsUIHierarchy uiHierarchy; IVsWindowFrame frame; int isOpen; if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen))) { // TODO: do we need save argument for CloseDocument? frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } } } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind) { // No extension was provided. Pick a good one based on the type of host project. switch (hostProject.Language) { case LanguageNames.CSharp: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx"; return ".cs"; case LanguageNames.VisualBasic: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx"; return ".vb"; default: throw new InvalidOperationException(); } } public override IVsHierarchy GetHierarchy(ProjectId projectId) { var project = this.GetHostProject(projectId); if (project == null) { return null; } return project.Hierarchy; } internal override void SetDocumentContext(DocumentId documentId) { var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var hierarchy = hostDocument.Project.Hierarchy; var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { if (sharedHierarchy.SetProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK) { // The ASP.NET 5 intellisense project is now updated. return; } else { // Universal Project shared files // Change the SharedItemContextHierarchy of the project's parent hierarchy, then // hierarchy events will trigger the workspace to update. var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy); } } else { // Regular linked files // Transfer the item (open buffer) to the new hierarchy, and then hierarchy events // will trigger the workspace to update. var vsproj = hierarchy as IVsProject3; var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null); } } internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId) { // TODO: This is a very roundabout way to update the context // The sharedHierarchy passed in has a new context, but we don't know what it is. // The documentId passed in is associated with this sharedHierarchy, and this method // will be called once for each such documentId. During this process, one of these // documentIds will actually belong to the new SharedItemContextHierarchy. Once we // find that one, we can map back to the open buffer and set its active context to // the appropriate project. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); if (hostProject.Hierarchy == sharedHierarchy) { // How? return; } if (hostProject.Id != documentId.ProjectId) { // While this documentId is associated with one of the head projects for this // sharedHierarchy, it is not associated with the new context hierarchy. Another // documentId will be passed to this method and update the context. return; } // This documentId belongs to the new SharedItemContextHierarchy. Update the associated // buffer. OnDocumentContextUpdated(documentId); } /// <summary> /// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that /// is in the current context. For regular files (non-shared and non-linked) and closed /// linked files, this is always the provided <see cref="DocumentId"/>. For open linked /// files and open shared files, the active context is already tracked by the /// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the /// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/> /// is preferred. /// </summary> internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId) { // If the document is open, then the Workspace knows the current context for both // linked and shared files if (IsDocumentOpen(documentId)) { return base.GetDocumentIdInCurrentContext(documentId); } var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // An itemid is required to determine whether the file belongs to a Shared Project return base.GetDocumentIdInCurrentContext(documentId); } // If this is a regular document or a closed linked (non-shared) document, then use the // default logic for determining current context. var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy == null) { return base.GetDocumentIdInCurrentContext(documentId); } // This is a closed shared document, so we must determine the correct context. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); var matchingProject = CurrentSolution.GetProject(hostProject.Id); if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy) { return base.GetDocumentIdInCurrentContext(documentId); } if (matchingProject.ContainsDocument(documentId)) { // The provided documentId is in the current context project return documentId; } // The current context document is from another project. var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds(); var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id); return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId); } internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy) { hierarchy = this.GetHierarchy(projectId); return hierarchy != null; } public override string GetFilePath(DocumentId documentId) { var document = this.GetHostDocument(documentId); if (document == null) { return null; } else { return document.FilePath; } } internal void StartSolutionCrawler() { if (_registrationService == null) { lock (this) { if (_registrationService == null) { _registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } } } } internal void StopSolutionCrawler() { if (_registrationService != null) { lock (this) { if (_registrationService != null) { _registrationService.Unregister(this, blockingShutdown: true); _registrationService = null; } } } } protected override void Dispose(bool finalize) { // workspace is going away. unregister this workspace from work coordinator StopSolutionCrawler(); base.Dispose(finalize); } public void EnsureEditableDocuments(IEnumerable<DocumentId> documents) { var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave)); var fileNames = documents.Select(GetFilePath).ToArray(); uint editVerdict; uint editResultFlags; // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn int result = queryEdit.QueryEditFiles( rgfQueryEdit: 0, cFiles: fileNames.Length, rgpszMkDocuments: fileNames, rgrgf: new uint[fileNames.Length], rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length], pfEditVerdict: out editVerdict, prgfMoreInfo: out editResultFlags); if (ErrorHandler.Failed(result) || editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new Exception("Unable to check out the files from source control."); } if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0) { throw new Exception("A file was reloaded during the source control checkout."); } } public void EnsureEditableDocuments(params DocumentId[] documents) { this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents); } internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader); } internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader); } public TInterface GetVsService<TService, TInterface>() where TService : class where TInterface : class { return this.ServiceProvider.GetService(typeof(TService)) as TInterface; } public object GetVsService(Type serviceType) { return ServiceProvider.GetService(serviceType); } public DTE GetVsDte() { return GetVsService<SDTE, DTE>(); } internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { _foregroundObject.AssertIsForeground(); IVsHierarchy referencingHierarchy; IVsHierarchy referencedHierarchy; if (!TryGetHierarchy(referencingProject, out referencingHierarchy) || !TryGetHierarchy(referencedProject, out referencedHierarchy)) { // Couldn't even get a hierarchy for this project. So we have to assume // that adding a reference is disallowed. return false; } // First we have to see if either project disallows the reference being added. const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference; uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3; if (referencingProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3; if (referencedProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } // Neither project denied the reference being added. At this point, if either project // allows the reference to be added, and the other doesn't block it, then we can add // the reference. if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW || canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW) { return true; } // In both directions things are still unknown. Fallback to the reference manager // to make the determination here. var referenceManager = GetVsService<SVsReferenceManager, IVsReferenceManager>(); if (referenceManager == null) { // Couldn't get the reference manager. Have to assume it's not allowed. return false; } // As long as the reference manager does not deny things, then we allow the // reference to be added. var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy); return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY; } /// <summary> /// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just /// forwards the calls down to the underlying Workspace. /// </summary> protected sealed class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkspaceHost2, IVisualStudioWorkingFolder { private readonly VisualStudioWorkspaceImpl _workspace; private readonly Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>(); public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace) { _workspace = workspace; } void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions) { _workspace.OnCompilationOptionsChanged(projectId, compilationOptions); _workspace.OnParseOptionsChanged(projectId, parseOptions); } void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo) { _workspace.OnDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext) { // TODO: Move this out to DocumentProvider. As is, this depends on being able to // access the host document which will already be deleted in some cases, causing // a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a // Mercury shared document is closed. // UnsubscribeFromSharedHierarchyEvents(documentId); using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed")) { _workspace.OnDocumentClosed(documentId, loader, updateActiveContext); } } void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext) { SubscribeToSharedHierarchyEvents(documentId); _workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext); } private void SubscribeToSharedHierarchyEvents(DocumentId documentId) { // Todo: maybe avoid double alerts. var hostDocument = _workspace.GetHostDocument(documentId); if (hostDocument == null) { return; } var hierarchy = hostDocument.Project.Hierarchy; var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId); var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie); if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId)) { _documentIdToHierarchyEventsCookieMap.Add(documentId, cookie); } } } private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId) { var hostDocument = _workspace.GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie)) { var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie); _documentIdToHierarchyEventsCookieMap.Remove(documentId); } } } private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.RegisterPrimarySolution(solutionId); } private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.UnregisterPrimarySolution(solutionId, synchronousShutdown); } void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId) { _workspace.OnDocumentRemoved(documentId); } void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceAdded(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceRemoved(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project")) { _workspace.OnProjectAdded(projectInfo); } } void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceAdded(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceRemoved(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project")) { _workspace.OnProjectRemoved(projectId); } } void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo) { RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id); _workspace.OnSolutionAdded(solutionInfo); } void IVisualStudioWorkspaceHost.OnSolutionRemoved() { var solutionId = _workspace.CurrentSolution.Id; _workspace.OnSolutionRemoved(); _workspace.ClearReferenceCache(); UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false); } void IVisualStudioWorkspaceHost.ClearSolution() { _workspace.ClearSolution(); _workspace.ClearReferenceCache(); } void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName) { _workspace.OnAssemblyNameChanged(id, assemblyName); } void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath) { _workspace.OnOutputFilePathChanged(id, outputFilePath); } void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath) { _workspace.OnProjectNameChanged(projectId, name, filePath); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo documentInfo) { _workspace.OnAdditionalDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId documentInfo) { _workspace.OnAdditionalDocumentRemoved(documentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext) { _workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader) { _workspace.OnAdditionalDocumentClosed(documentId, loader); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnAdditionalDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost2.OnHasAllInformation(ProjectId projectId, bool hasAllInformation) { _workspace.OnHasAllInformationChanged(projectId, hasAllInformation); } void IVisualStudioWorkspaceHost2.UpdateGeneratedDocumentsIfNecessary(ProjectId projectId) { _workspace.UpdateGeneratedDocumentsIfNecessary(projectId); } void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange() { UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true); } void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange() { var solutionId = _workspace.CurrentSolution.Id; _workspace.ProjectTracker.UpdateSolutionProperties(solutionId); RegisterPrimarySolutionForPersistentStorage(solutionId); } } } }
// ReSharper disable RedundantUsingDirective // ReSharper disable DoNotCallOverridableMethodsInConstructor // ReSharper disable InconsistentNaming // ReSharper disable PartialTypeWithSinglePart // ReSharper disable PartialMethodWithSinglePart // ReSharper disable RedundantNameQualifier // TargetFrameworkVersion = 4.52 #pragma warning disable 1591 // Ignore "Missing XML Comment" warning using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Data; using System.Data.SqlClient; using System.Data.Entity.ModelConfiguration; using System.Threading; using System.Threading.Tasks; //using DatabaseGeneratedOption = System.ComponentModel.DataAnnotations.DatabaseGeneratedOption; namespace DataModels { public class NorthwindDbContext : DbContext, INorthwindDbContext { public IDbSet<AlphabeticalListOfProduct> AlphabeticalListOfProducts { get; set; } // Alphabetical list of products public IDbSet<Category> Categories { get; set; } // Categories public IDbSet<CategorySalesFor1997> CategorySalesFor1997 { get; set; } // Category Sales for 1997 public IDbSet<CurrentProductList> CurrentProductLists { get; set; } // Current Product List public IDbSet<Customer> Customers { get; set; } // Customers public IDbSet<CustomerAndSuppliersByCity> CustomerAndSuppliersByCities { get; set; } // Customer and Suppliers by City public IDbSet<CustomerDemographic> CustomerDemographics { get; set; } // CustomerDemographics public IDbSet<Employee> Employees { get; set; } // Employees public IDbSet<Invoice> Invoices { get; set; } // Invoices public IDbSet<Order> Orders { get; set; } // Orders public IDbSet<OrderDetail> OrderDetails { get; set; } // Order Details public IDbSet<OrderDetailsExtended> OrderDetailsExtendeds { get; set; } // Order Details Extended public IDbSet<OrdersQry> OrdersQries { get; set; } // Orders Qry public IDbSet<OrderSubtotal> OrderSubtotals { get; set; } // Order Subtotals public IDbSet<Product> Products { get; set; } // Products public IDbSet<ProductsAboveAveragePrice> ProductsAboveAveragePrices { get; set; } // Products Above Average Price public IDbSet<ProductSalesFor1997> ProductSalesFor1997 { get; set; } // Product Sales for 1997 public IDbSet<ProductsByCategory> ProductsByCategories { get; set; } // Products by Category public IDbSet<Region> Regions { get; set; } // Region public IDbSet<SalesByCategory> SalesByCategories { get; set; } // Sales by Category public IDbSet<SalesTotalsByAmount> SalesTotalsByAmounts { get; set; } // Sales Totals by Amount public IDbSet<Shipper> Shippers { get; set; } // Shippers public IDbSet<SummaryOfSalesByQuarter> SummaryOfSalesByQuarters { get; set; } // Summary of Sales by Quarter public IDbSet<SummaryOfSalesByYear> SummaryOfSalesByYears { get; set; } // Summary of Sales by Year public IDbSet<Supplier> Suppliers { get; set; } // Suppliers public IDbSet<Sysdiagram> Sysdiagrams { get; set; } // sysdiagrams public IDbSet<Territory> Territories { get; set; } // Territories static NorthwindDbContext() { Database.SetInitializer<NorthwindDbContext>(null); } public NorthwindDbContext() : base("Name=NorthwindDb") { } public NorthwindDbContext(string connectionString) : base(connectionString) { } public NorthwindDbContext(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) { } protected override void Dispose(bool disposing) { base.Dispose(disposing); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Configurations.Add(new AlphabeticalListOfProductConfiguration()); modelBuilder.Configurations.Add(new CategoryConfiguration()); modelBuilder.Configurations.Add(new CategorySalesFor1997Configuration()); modelBuilder.Configurations.Add(new CurrentProductListConfiguration()); modelBuilder.Configurations.Add(new CustomerConfiguration()); modelBuilder.Configurations.Add(new CustomerAndSuppliersByCityConfiguration()); modelBuilder.Configurations.Add(new CustomerDemographicConfiguration()); modelBuilder.Configurations.Add(new EmployeeConfiguration()); modelBuilder.Configurations.Add(new InvoiceConfiguration()); modelBuilder.Configurations.Add(new OrderConfiguration()); modelBuilder.Configurations.Add(new OrderDetailConfiguration()); modelBuilder.Configurations.Add(new OrderDetailsExtendedConfiguration()); modelBuilder.Configurations.Add(new OrdersQryConfiguration()); modelBuilder.Configurations.Add(new OrderSubtotalConfiguration()); modelBuilder.Configurations.Add(new ProductConfiguration()); modelBuilder.Configurations.Add(new ProductsAboveAveragePriceConfiguration()); modelBuilder.Configurations.Add(new ProductSalesFor1997Configuration()); modelBuilder.Configurations.Add(new ProductsByCategoryConfiguration()); modelBuilder.Configurations.Add(new RegionConfiguration()); modelBuilder.Configurations.Add(new SalesByCategoryConfiguration()); modelBuilder.Configurations.Add(new SalesTotalsByAmountConfiguration()); modelBuilder.Configurations.Add(new ShipperConfiguration()); modelBuilder.Configurations.Add(new SummaryOfSalesByQuarterConfiguration()); modelBuilder.Configurations.Add(new SummaryOfSalesByYearConfiguration()); modelBuilder.Configurations.Add(new SupplierConfiguration()); modelBuilder.Configurations.Add(new SysdiagramConfiguration()); modelBuilder.Configurations.Add(new TerritoryConfiguration()); } public static DbModelBuilder CreateModel(DbModelBuilder modelBuilder, string schema) { modelBuilder.Configurations.Add(new AlphabeticalListOfProductConfiguration(schema)); modelBuilder.Configurations.Add(new CategoryConfiguration(schema)); modelBuilder.Configurations.Add(new CategorySalesFor1997Configuration(schema)); modelBuilder.Configurations.Add(new CurrentProductListConfiguration(schema)); modelBuilder.Configurations.Add(new CustomerConfiguration(schema)); modelBuilder.Configurations.Add(new CustomerAndSuppliersByCityConfiguration(schema)); modelBuilder.Configurations.Add(new CustomerDemographicConfiguration(schema)); modelBuilder.Configurations.Add(new EmployeeConfiguration(schema)); modelBuilder.Configurations.Add(new InvoiceConfiguration(schema)); modelBuilder.Configurations.Add(new OrderConfiguration(schema)); modelBuilder.Configurations.Add(new OrderDetailConfiguration(schema)); modelBuilder.Configurations.Add(new OrderDetailsExtendedConfiguration(schema)); modelBuilder.Configurations.Add(new OrdersQryConfiguration(schema)); modelBuilder.Configurations.Add(new OrderSubtotalConfiguration(schema)); modelBuilder.Configurations.Add(new ProductConfiguration(schema)); modelBuilder.Configurations.Add(new ProductsAboveAveragePriceConfiguration(schema)); modelBuilder.Configurations.Add(new ProductSalesFor1997Configuration(schema)); modelBuilder.Configurations.Add(new ProductsByCategoryConfiguration(schema)); modelBuilder.Configurations.Add(new RegionConfiguration(schema)); modelBuilder.Configurations.Add(new SalesByCategoryConfiguration(schema)); modelBuilder.Configurations.Add(new SalesTotalsByAmountConfiguration(schema)); modelBuilder.Configurations.Add(new ShipperConfiguration(schema)); modelBuilder.Configurations.Add(new SummaryOfSalesByQuarterConfiguration(schema)); modelBuilder.Configurations.Add(new SummaryOfSalesByYearConfiguration(schema)); modelBuilder.Configurations.Add(new SupplierConfiguration(schema)); modelBuilder.Configurations.Add(new SysdiagramConfiguration(schema)); modelBuilder.Configurations.Add(new TerritoryConfiguration(schema)); return modelBuilder; } // Stored Procedures public List<CustOrderHistReturnModel> CustOrderHist(string customerId, out int procResult) { var customerIdParam = new SqlParameter { ParameterName = "@CustomerID", SqlDbType = SqlDbType.NChar, Direction = ParameterDirection.Input, Value = customerId, Size = 5 }; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<CustOrderHistReturnModel>("EXEC @procResult = [dbo].[CustOrderHist] @CustomerID", customerIdParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<CustOrdersDetailReturnModel> CustOrdersDetail(int? orderId, out int procResult) { var orderIdParam = new SqlParameter { ParameterName = "@OrderID", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input, Value = orderId.GetValueOrDefault() }; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<CustOrdersDetailReturnModel>("EXEC @procResult = [dbo].[CustOrdersDetail] @OrderID", orderIdParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<CustOrdersOrdersReturnModel> CustOrdersOrders(string customerId, out int procResult) { var customerIdParam = new SqlParameter { ParameterName = "@CustomerID", SqlDbType = SqlDbType.NChar, Direction = ParameterDirection.Input, Value = customerId, Size = 5 }; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<CustOrdersOrdersReturnModel>("EXEC @procResult = [dbo].[CustOrdersOrders] @CustomerID", customerIdParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<EmployeeSalesByCountryReturnModel> EmployeeSalesByCountry(DateTime? beginningDate, DateTime? endingDate, out int procResult) { var beginningDateParam = new SqlParameter { ParameterName = "@Beginning_Date", SqlDbType = SqlDbType.DateTime, Direction = ParameterDirection.Input, Value = beginningDate.GetValueOrDefault() }; var endingDateParam = new SqlParameter { ParameterName = "@Ending_Date", SqlDbType = SqlDbType.DateTime, Direction = ParameterDirection.Input, Value = endingDate.GetValueOrDefault() }; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<EmployeeSalesByCountryReturnModel>("EXEC @procResult = [dbo].[Employee Sales by Country] @Beginning_Date, @Ending_Date", beginningDateParam, endingDateParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<SalesByYearReturnModel> SalesByYear(DateTime? beginningDate, DateTime? endingDate, out int procResult) { var beginningDateParam = new SqlParameter { ParameterName = "@Beginning_Date", SqlDbType = SqlDbType.DateTime, Direction = ParameterDirection.Input, Value = beginningDate.GetValueOrDefault() }; var endingDateParam = new SqlParameter { ParameterName = "@Ending_Date", SqlDbType = SqlDbType.DateTime, Direction = ParameterDirection.Input, Value = endingDate.GetValueOrDefault() }; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<SalesByYearReturnModel>("EXEC @procResult = [dbo].[Sales by Year] @Beginning_Date, @Ending_Date", beginningDateParam, endingDateParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<SalesByCategoryReturnModel> SalesByCategory(string categoryName, string ordYear, out int procResult) { var categoryNameParam = new SqlParameter { ParameterName = "@CategoryName", SqlDbType = SqlDbType.NVarChar, Direction = ParameterDirection.Input, Value = categoryName, Size = 15 }; var ordYearParam = new SqlParameter { ParameterName = "@OrdYear", SqlDbType = SqlDbType.NVarChar, Direction = ParameterDirection.Input, Value = ordYear, Size = 4 }; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<SalesByCategoryReturnModel>("EXEC @procResult = [dbo].[SalesByCategory] @CategoryName, @OrdYear", categoryNameParam, ordYearParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<TenMostExpensiveProductsReturnModel> TenMostExpensiveProducts( out int procResult) { var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<TenMostExpensiveProductsReturnModel>("EXEC @procResult = [dbo].[Ten Most Expensive Products] ", procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } } }
using System; using System.Data.SqlTypes; using System.Reflection; using System.ComponentModel; using BLToolkit.ComponentModel; namespace BLToolkit.Reflection { public abstract class MemberAccessor { protected MemberAccessor(TypeAccessor typeAccessor, MemberInfo memberInfo) { _typeAccessor = typeAccessor; _memberInfo = memberInfo; } #region Public Properties private readonly MemberInfo _memberInfo; public MemberInfo MemberInfo { get { return _memberInfo; } } private readonly TypeAccessor _typeAccessor; public TypeAccessor TypeAccessor { get { return _typeAccessor; } } private PropertyDescriptor _propertyDescriptor; public PropertyDescriptor PropertyDescriptor { get { if (_propertyDescriptor == null) _propertyDescriptor = new MemberPropertyDescriptor(_typeAccessor.OriginalType, Name); return _propertyDescriptor; } } public virtual bool HasGetter { get { return false; } } public virtual bool HasSetter { get { return false; } } public Type Type { get { return _memberInfo is PropertyInfo? ((PropertyInfo)_memberInfo).PropertyType: ((FieldInfo) _memberInfo).FieldType; } } public string Name { get { return _memberInfo.Name; } } private Type _underlyingType; public Type UnderlyingType { get { if (_underlyingType == null) _underlyingType = TypeHelper.GetUnderlyingType(Type); return _underlyingType; } } #endregion #region Public Methods public bool IsDefined<T>() where T : Attribute { return _memberInfo.IsDefined(typeof(T), true); } [Obsolete("Use generic version instead")] public Attribute GetAttribute(Type attributeType) { object[] attrs = _memberInfo.GetCustomAttributes(attributeType, true); return attrs.Length > 0? (Attribute)attrs[0]: null; } public T GetAttribute<T>() where T : Attribute { object[] attrs = _memberInfo.GetCustomAttributes(typeof(T), true); return attrs.Length > 0? (T)attrs[0]: null; } [Obsolete("Use generic version instead")] public object[] GetAttributes(Type attributeType) { object[] attrs = _memberInfo.GetCustomAttributes(attributeType, true); return attrs.Length > 0? attrs: null; } public T[] GetAttributes<T>() where T : Attribute { Array attrs = _memberInfo.GetCustomAttributes(typeof(T), true); return attrs.Length > 0? (T[])attrs: null; } public object[] GetAttributes() { object[] attrs = _memberInfo.GetCustomAttributes(true); return attrs.Length > 0? attrs: null; } public object[] GetTypeAttributes(Type attributeType) { return TypeHelper.GetAttributes(_typeAccessor.OriginalType, attributeType); } #endregion #region Set/Get Value public virtual Boolean IsNull(object o) { return true; } public virtual object GetValue(object o) { return null; } public virtual void SetValue(object o, object value) { } public virtual void CloneValue(object source, object dest) { object value = GetValue(source); SetValue(dest, value is ICloneable? ((ICloneable)value).Clone(): value); } // Simple types getters. // [CLSCompliant(false)] public virtual SByte GetSByte (object o) { return (SByte) GetValue(o); } public virtual Int16 GetInt16 (object o) { return (Int16) GetValue(o); } public virtual Int32 GetInt32 (object o) { return (Int32) GetValue(o); } public virtual Int64 GetInt64 (object o) { return (Int64) GetValue(o); } public virtual Byte GetByte (object o) { return (Byte) GetValue(o); } [CLSCompliant(false)] public virtual UInt16 GetUInt16 (object o) { return (UInt16) GetValue(o); } [CLSCompliant(false)] public virtual UInt32 GetUInt32 (object o) { return (UInt32) GetValue(o); } [CLSCompliant(false)] public virtual UInt64 GetUInt64 (object o) { return (UInt64) GetValue(o); } public virtual Boolean GetBoolean (object o) { return (Boolean) GetValue(o); } public virtual Char GetChar (object o) { return (Char) GetValue(o); } public virtual Single GetSingle (object o) { return (Single) GetValue(o); } public virtual Double GetDouble (object o) { return (Double) GetValue(o); } public virtual Decimal GetDecimal (object o) { return (Decimal) GetValue(o); } public virtual Guid GetGuid (object o) { return (Guid) GetValue(o); } public virtual DateTime GetDateTime(object o) { return (DateTime)GetValue(o); } public virtual TimeSpan GetTimeSpan(object o) { return (TimeSpan)GetValue(o); } #if FW3 public virtual DateTimeOffset GetDateTimeOffset(object o) { return (DateTimeOffset)GetValue(o); } #endif // Nullable types getters. // [CLSCompliant(false)] public virtual SByte? GetNullableSByte (object o) { return (SByte?) GetValue(o); } public virtual Int16? GetNullableInt16 (object o) { return (Int16?) GetValue(o); } public virtual Int32? GetNullableInt32 (object o) { return (Int32?) GetValue(o); } public virtual Int64? GetNullableInt64 (object o) { return (Int64?) GetValue(o); } public virtual Byte? GetNullableByte (object o) { return (Byte?) GetValue(o); } [CLSCompliant(false)] public virtual UInt16? GetNullableUInt16 (object o) { return (UInt16?) GetValue(o); } [CLSCompliant(false)] public virtual UInt32? GetNullableUInt32 (object o) { return (UInt32?) GetValue(o); } [CLSCompliant(false)] public virtual UInt64? GetNullableUInt64 (object o) { return (UInt64?) GetValue(o); } public virtual Boolean? GetNullableBoolean (object o) { return (Boolean?) GetValue(o); } public virtual Char? GetNullableChar (object o) { return (Char?) GetValue(o); } public virtual Single? GetNullableSingle (object o) { return (Single?) GetValue(o); } public virtual Double? GetNullableDouble (object o) { return (Double?) GetValue(o); } public virtual Decimal? GetNullableDecimal (object o) { return (Decimal?) GetValue(o); } public virtual Guid? GetNullableGuid (object o) { return (Guid?) GetValue(o); } public virtual DateTime? GetNullableDateTime(object o) { return (DateTime?)GetValue(o); } public virtual TimeSpan? GetNullableTimeSpan(object o) { return (TimeSpan?)GetValue(o); } #if FW3 public virtual DateTimeOffset? GetNullableDateTimeOffset(object o) { return (DateTimeOffset?)GetValue(o); } #endif // SQL type getters. // public virtual SqlByte GetSqlByte (object o) { return (SqlByte) GetValue(o); } public virtual SqlInt16 GetSqlInt16 (object o) { return (SqlInt16) GetValue(o); } public virtual SqlInt32 GetSqlInt32 (object o) { return (SqlInt32) GetValue(o); } public virtual SqlInt64 GetSqlInt64 (object o) { return (SqlInt64) GetValue(o); } public virtual SqlSingle GetSqlSingle (object o) { return (SqlSingle) GetValue(o); } public virtual SqlBoolean GetSqlBoolean (object o) { return (SqlBoolean) GetValue(o); } public virtual SqlDouble GetSqlDouble (object o) { return (SqlDouble) GetValue(o); } public virtual SqlDateTime GetSqlDateTime(object o) { return (SqlDateTime)GetValue(o); } public virtual SqlDecimal GetSqlDecimal (object o) { return (SqlDecimal) GetValue(o); } public virtual SqlMoney GetSqlMoney (object o) { return (SqlMoney) GetValue(o); } public virtual SqlGuid GetSqlGuid (object o) { return (SqlGuid) GetValue(o); } public virtual SqlString GetSqlString (object o) { return (SqlString) GetValue(o); } // Simple type setters. // [CLSCompliant(false)] public virtual void SetSByte (object o, SByte value) { SetValue(o, value); } public virtual void SetInt16 (object o, Int16 value) { SetValue(o, value); } public virtual void SetInt32 (object o, Int32 value) { SetValue(o, value); } public virtual void SetInt64 (object o, Int64 value) { SetValue(o, value); } public virtual void SetByte (object o, Byte value) { SetValue(o, value); } [CLSCompliant(false)] public virtual void SetUInt16 (object o, UInt16 value) { SetValue(o, value); } [CLSCompliant(false)] public virtual void SetUInt32 (object o, UInt32 value) { SetValue(o, value); } [CLSCompliant(false)] public virtual void SetUInt64 (object o, UInt64 value) { SetValue(o, value); } public virtual void SetBoolean (object o, Boolean value) { SetValue(o, value); } public virtual void SetChar (object o, Char value) { SetValue(o, value); } public virtual void SetSingle (object o, Single value) { SetValue(o, value); } public virtual void SetDouble (object o, Double value) { SetValue(o, value); } public virtual void SetDecimal (object o, Decimal value) { SetValue(o, value); } public virtual void SetGuid (object o, Guid value) { SetValue(o, value); } public virtual void SetDateTime(object o, DateTime value) { SetValue(o, value); } public virtual void SetTimeSpan(object o, TimeSpan value) { SetValue(o, value); } #if FW3 public virtual void SetDateTimeOffset(object o, DateTimeOffset value) { SetValue(o, value); } #endif // Simple type setters. // [CLSCompliant(false)] public virtual void SetNullableSByte (object o, SByte? value) { SetValue(o, value); } public virtual void SetNullableInt16 (object o, Int16? value) { SetValue(o, value); } public virtual void SetNullableInt32 (object o, Int32? value) { SetValue(o, value); } public virtual void SetNullableInt64 (object o, Int64? value) { SetValue(o, value); } public virtual void SetNullableByte (object o, Byte? value) { SetValue(o, value); } [CLSCompliant(false)] public virtual void SetNullableUInt16 (object o, UInt16? value) { SetValue(o, value); } [CLSCompliant(false)] public virtual void SetNullableUInt32 (object o, UInt32? value) { SetValue(o, value); } [CLSCompliant(false)] public virtual void SetNullableUInt64 (object o, UInt64? value) { SetValue(o, value); } public virtual void SetNullableBoolean (object o, Boolean? value) { SetValue(o, value); } public virtual void SetNullableChar (object o, Char? value) { SetValue(o, value); } public virtual void SetNullableSingle (object o, Single? value) { SetValue(o, value); } public virtual void SetNullableDouble (object o, Double? value) { SetValue(o, value); } public virtual void SetNullableDecimal (object o, Decimal? value) { SetValue(o, value); } public virtual void SetNullableGuid (object o, Guid? value) { SetValue(o, value); } public virtual void SetNullableDateTime(object o, DateTime? value) { SetValue(o, value); } public virtual void SetNullableTimeSpan(object o, TimeSpan? value) { SetValue(o, value); } #if FW3 public virtual void SetNullableDateTimeOffset(object o, DateTimeOffset? value) { SetValue(o, value); } #endif // SQL type setters. // public virtual void SetSqlByte (object o, SqlByte value) { SetValue(o, value); } public virtual void SetSqlInt16 (object o, SqlInt16 value) { SetValue(o, value); } public virtual void SetSqlInt32 (object o, SqlInt32 value) { SetValue(o, value); } public virtual void SetSqlInt64 (object o, SqlInt64 value) { SetValue(o, value); } public virtual void SetSqlSingle (object o, SqlSingle value) { SetValue(o, value); } public virtual void SetSqlBoolean (object o, SqlBoolean value) { SetValue(o, value); } public virtual void SetSqlDouble (object o, SqlDouble value) { SetValue(o, value); } public virtual void SetSqlDateTime(object o, SqlDateTime value) { SetValue(o, value); } public virtual void SetSqlDecimal (object o, SqlDecimal value) { SetValue(o, value); } public virtual void SetSqlMoney (object o, SqlMoney value) { SetValue(o, value); } public virtual void SetSqlGuid (object o, SqlGuid value) { SetValue(o, value); } public virtual void SetSqlString (object o, SqlString value) { SetValue(o, value); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using Eflat.Util; namespace Eflat { /// <summary> /// An interface that could be any one of the types in the /// 'Types' static class. /// </summary> public abstract class Type { public virtual bool IsSameAs(Type other) { return GetType() == other.GetType(); } } /// <summary> /// A class that holds the declarations of each of the different types. /// </summary> public static class Types { public sealed class Unknown : Type { public override string ToString() { return "Unknown Type"; } } public sealed class Void : Type { } public sealed class Boolean : Type { public override string ToString() { return Symbols.Types.BOOLEAN; } } public sealed class Integer : Type { public enum IntegerSize { UnspecifiedSize, I8, I16, I32, I64 } public IntegerSize Size { get; set; } public Integer(IntegerSize size = IntegerSize.UnspecifiedSize) { Size = size; } public override bool IsSameAs(Type other) { if (other is Integer iOther) { return Size == iOther.Size; } return false; } public override string ToString() => $"Integer ({Size})"; } public sealed class Float : Type { public enum FloatSize { UnspecifiedSize, F32, F64, } public FloatSize Size { get; set; } public Float(FloatSize size = FloatSize.UnspecifiedSize) { Size = size; } public override bool IsSameAs(Type other) { if (other is Float fOther) { return Size == fOther.Size; } return false; } public override string ToString() => $"Float ({Size})"; } public sealed class Struct : Type { /// <summary> /// The name of the struct referenced. /// </summary> /// <returns>The name of the struct.</returns> public Token Name { get; private set; } /// <summary> /// A reference to the struct declaration we are talking to. May be set to None. /// </summary> public Option<StructDecl> Decl { get; set; } public Struct(Token name, StructDecl decl = null) { Name = name; Decl = Option<StructDecl>.Maybe(decl); } public override bool IsSameAs(Type other) { if (other is Struct sOther) { throw new NotImplementedException(); } return false; } } /// <summary> /// A type to represent a function type. /// </summary> public sealed class Function : Type { /// <summary> /// The Parameters we have /// </summary> public List<Type> Parameters { get; private set; } /// <summary> /// The return type of this function. /// </summary> public Type ReturnType { get; private set; } public Function(List<Type> paramaters, Type returnType) { Parameters = paramaters; ReturnType = returnType; } /// <summary> /// Check to see if this function is the same as the other type. /// </summary> /// <param name="other"></param> /// <returns></returns> public override bool IsSameAs(Type other) { if (other is Function fn) { return CheckReturnType(fn) && CheckParameters(fn); } return false; } /// <summary> /// Check that this function has the same parameters as the other one. /// </summary> /// <param name="fn"></param> /// <returns></returns> private bool CheckParameters(Function fn) { // Check parameter count is same. if (fn.Parameters.Count != Parameters.Count) { return false; } /// Check that each parameter type is the same. for (int i = 0; i < Parameters.Count; i++) { Type ours = Parameters[i]; Type theirs = fn.Parameters[i]; if (!ours.IsSameAs(theirs)) { return false; } } // If we've got here, it is the same. return true; } /// <summary> /// Check that this function has the same return type as the other one. /// </summary> /// <param name="fn"></param> /// <returns></returns> private bool CheckReturnType(Function fn) => ReturnType.IsSameAs(fn.ReturnType); public override string ToString() { StringBuilder b = new StringBuilder(); b.Append("|"); for (int i = 0; i < Parameters.Count; i++) { b.Append(Parameters[i]); if (i == Parameters.Count - 1) { b.Append(", "); } } b.Append($"| -> {ReturnType}"); return b.ToString(); } } public sealed class StructDecl : Type { } } public abstract class TypedNode { public Type Type { get; set; } public TypedNode(Type type) => Type = type; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // using System; using System.Runtime.InteropServices; using System.Text; #pragma warning disable 436 // Redefining types from Windows.Foundation namespace Windows.UI.Xaml.Media.Animation { // // RepeatBehavior is the managed projection of Windows.UI.Xaml.Media.Animation.RepeatBehavior. // Any changes to the layout of this type must be exactly mirrored on the native WinRT side as well. // // RepeatBehaviorType is the managed projection of Windows.UI.Xaml.Media.Animation.RepeatBehaviorType. // Any changes to this enumeration must be exactly mirrored on the native WinRT side as well. // // Note that these types are owned by the Jupiter team. Please contact them before making any // changes here. // public enum RepeatBehaviorType { Count, Duration, Forever } [StructLayout(LayoutKind.Sequential)] public struct RepeatBehavior : IFormattable { private double _Count; private TimeSpan _Duration; private RepeatBehaviorType _Type; public RepeatBehavior(double count) { if (!double.IsFinite(count) || count < 0.0) { throw new ArgumentOutOfRangeException(nameof(count)); } _Duration = new TimeSpan(0); _Count = count; _Type = RepeatBehaviorType.Count; } public RepeatBehavior(TimeSpan duration) { if (duration < new TimeSpan(0)) { throw new ArgumentOutOfRangeException(nameof(duration)); } _Duration = duration; _Count = 0.0; _Type = RepeatBehaviorType.Duration; } public static RepeatBehavior Forever { get { RepeatBehavior forever = new RepeatBehavior(); forever.Type = RepeatBehaviorType.Forever; return forever; } } public bool HasCount { get { return Type == RepeatBehaviorType.Count; } } public bool HasDuration { get { return Type == RepeatBehaviorType.Duration; } } public double Count { get { return _Count; } set { _Count = value; } } public TimeSpan Duration { get { return _Duration; } set { _Duration = value; } } public RepeatBehaviorType Type { get { return _Type; } set { _Type = value; } } public override string ToString() { return InternalToString(null, null); } public string ToString(IFormatProvider formatProvider) { return InternalToString(null, formatProvider); } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return InternalToString(format, formatProvider); } internal string InternalToString(string format, IFormatProvider formatProvider) { switch (_Type) { case RepeatBehaviorType.Forever: return "Forever"; case RepeatBehaviorType.Count: StringBuilder sb = new StringBuilder(); sb.AppendFormat( formatProvider, "{0:" + format + "}x", _Count); return sb.ToString(); case RepeatBehaviorType.Duration: return _Duration.ToString(); default: return null; } } public override bool Equals(object value) { if (value is RepeatBehavior) { return this.Equals((RepeatBehavior)value); } else { return false; } } public bool Equals(RepeatBehavior repeatBehavior) { if (_Type == repeatBehavior._Type) { return _Type switch { RepeatBehaviorType.Forever => true, RepeatBehaviorType.Count => _Count == repeatBehavior._Count, RepeatBehaviorType.Duration => _Duration == repeatBehavior._Duration, _ => false, }; } else { return false; } } public static bool Equals(RepeatBehavior repeatBehavior1, RepeatBehavior repeatBehavior2) { return repeatBehavior1.Equals(repeatBehavior2); } public override int GetHashCode() { return _Type switch { RepeatBehaviorType.Count => _Count.GetHashCode(), RepeatBehaviorType.Duration => _Duration.GetHashCode(), // We try to choose an unlikely hash code value for Forever. // All Forevers need to return the same hash code value. RepeatBehaviorType.Forever => int.MaxValue - 42, _ => base.GetHashCode(), }; } public static bool operator ==(RepeatBehavior repeatBehavior1, RepeatBehavior repeatBehavior2) { return repeatBehavior1.Equals(repeatBehavior2); } public static bool operator !=(RepeatBehavior repeatBehavior1, RepeatBehavior repeatBehavior2) { return !repeatBehavior1.Equals(repeatBehavior2); } } } #pragma warning restore 436
//--------------------------------------------------------------------- // <copyright file="FeatureInfo.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller { using System; using System.Collections; using System.Collections.Generic; using System.Text; /// <summary> /// Accessor for information about features within the context of an installation session. /// </summary> internal sealed class FeatureInfoCollection : ICollection<FeatureInfo> { private Session session; internal FeatureInfoCollection(Session session) { this.session = session; } /// <summary> /// Gets information about a feature within the context of an installation session. /// </summary> /// <param name="feature">name of the feature</param> /// <returns>feature object</returns> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public FeatureInfo this[string feature] { get { return new FeatureInfo(this.session, feature); } } void ICollection<FeatureInfo>.Add(FeatureInfo item) { throw new InvalidOperationException(); } void ICollection<FeatureInfo>.Clear() { throw new InvalidOperationException(); } /// <summary> /// Checks if the collection contains a feature. /// </summary> /// <param name="feature">name of the feature</param> /// <returns>true if the feature is in the collection, else false</returns> public bool Contains(string feature) { return this.session.Database.CountRows( "Feature", "`Feature` = '" + feature + "'") == 1; } bool ICollection<FeatureInfo>.Contains(FeatureInfo item) { return item != null && this.Contains(item.Name); } /// <summary> /// Copies the features into an array. /// </summary> /// <param name="array">array that receives the features</param> /// <param name="arrayIndex">offset into the array</param> public void CopyTo(FeatureInfo[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException("array"); } foreach (FeatureInfo feature in this) { array[arrayIndex++] = feature; } } /// <summary> /// Gets the number of features defined for the product. /// </summary> public int Count { get { return this.session.Database.CountRows("Feature"); } } bool ICollection<FeatureInfo>.IsReadOnly { get { return true; } } bool ICollection<FeatureInfo>.Remove(FeatureInfo item) { throw new InvalidOperationException(); } /// <summary> /// Enumerates the features in the collection. /// </summary> /// <returns>an enumerator over all features in the collection</returns> public IEnumerator<FeatureInfo> GetEnumerator() { using (View featureView = this.session.Database.OpenView( "SELECT `Feature` FROM `Feature`")) { featureView.Execute(); foreach (Record featureRec in featureView) using (featureRec) { string feature = featureRec.GetString(1); yield return new FeatureInfo(this.session, feature); } } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } /// <summary> /// Provides access to information about a feature within the context of an installation session. /// </summary> internal class FeatureInfo { private Session session; private string name; internal FeatureInfo(Session session, string name) { this.session = session; this.name = name; } /// <summary> /// Gets the name of the feature (primary key in the Feature table). /// </summary> public string Name { get { return this.name; } } /// <summary> /// Gets the current install state of the feature. /// </summary> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="ArgumentException">an unknown feature was requested</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetfeaturestate.asp">MsiGetFeatureState</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public InstallState CurrentState { get { int installState, actionState; uint ret = RemotableNativeMethods.MsiGetFeatureState((int) this.session.Handle, this.name, out installState, out actionState); if (ret != 0) { if (ret == (uint) NativeMethods.Error.UNKNOWN_FEATURE) { throw InstallerException.ExceptionFromReturnCode(ret, this.name); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } if (installState == (int) InstallState.Advertised) { return InstallState.Advertised; } return (InstallState) installState; } } /// <summary> /// Gets or sets the action state of the feature. /// </summary> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="ArgumentException">an unknown feature was requested</exception> /// <remarks><p> /// When changing the feature action, the action state of all the Components linked to the changed /// Feature records are also updated appropriately, based on the new feature Select state. /// All Features can be configured at once by specifying the keyword ALL instead of a specific feature name. /// </p><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetfeaturestate.asp">MsiGetFeatureState</a>, /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisetfeaturestate.asp">MsiSetFeatureState</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public InstallState RequestState { get { int installState, actionState; uint ret = RemotableNativeMethods.MsiGetFeatureState((int) this.session.Handle, this.name, out installState, out actionState); if (ret != 0) { if (ret == (uint) NativeMethods.Error.UNKNOWN_FEATURE) { throw InstallerException.ExceptionFromReturnCode(ret, this.name); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } return (InstallState) actionState; } set { uint ret = RemotableNativeMethods.MsiSetFeatureState((int) this.session.Handle, this.name, (int) value); if (ret != 0) { if (ret == (uint) NativeMethods.Error.UNKNOWN_FEATURE) { throw InstallerException.ExceptionFromReturnCode(ret, this.name); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } } } /// <summary> /// Gets a list of valid installation states for the feature. /// </summary> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="ArgumentException">an unknown feature was requested</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetfeaturevalidstates.asp">MsiGetFeatureValidStates</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ICollection<InstallState> ValidStates { get { List<InstallState> states = new List<InstallState>(); uint installState; uint ret = RemotableNativeMethods.MsiGetFeatureValidStates((int) this.session.Handle, this.name, out installState); if (ret != 0) { if (ret == (uint) NativeMethods.Error.UNKNOWN_FEATURE) { throw InstallerException.ExceptionFromReturnCode(ret, this.name); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } for (int i = 1; i <= (int) InstallState.Default; i++) { if (((int) installState & (1 << i)) != 0) { states.Add((InstallState) i); } } return states.AsReadOnly(); } } /// <summary> /// Gets or sets the attributes of the feature. /// </summary> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="ArgumentException">an unknown feature was requested</exception> /// <remarks><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetfeatureinfo.asp">MsiGetFeatureInfo</a>, /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisetfeatureattributes.asp">MsiSetFeatureAttributes</a> /// </p><p> /// Since the lpAttributes paramter of /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetfeatureinfo.asp">MsiGetFeatureInfo</a> /// does not contain an equivalent flag for <see cref="FeatureAttributes.UIDisallowAbsent"/>, this flag will /// not be retrieved. /// </p><p> /// Since the dwAttributes parameter of /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisetfeatureattributes.asp">MsiSetFeatureAttributes</a> /// does not contain an equivalent flag for <see cref="FeatureAttributes.UIDisallowAbsent"/>, the presence /// of this flag will be ignored. /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public FeatureAttributes Attributes { get { FeatureAttributes attributes; uint titleBufSize = 0; uint descBufSize = 0; uint attr; uint ret = NativeMethods.MsiGetFeatureInfo( (int) this.session.Handle, this.name, out attr, null, ref titleBufSize, null, ref descBufSize); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } // Values for attributes that MsiGetFeatureInfo returns are // double the values in the Attributes column of the Feature Table. attributes = (FeatureAttributes) (attr >> 1); // MsiGetFeatureInfo MSDN documentation indicates // NOUNSUPPORTEDADVERTISE is 32. Conversion above changes this to 16 // which is UIDisallowAbsent. MsiGetFeatureInfo isn't documented to // return an attribute for 'UIDisallowAbsent', so if UIDisallowAbsent // is set, change it to NoUnsupportedAdvertise which then maps correctly // to NOUNSUPPORTEDADVERTISE. if ((attributes & FeatureAttributes.UIDisallowAbsent) == FeatureAttributes.UIDisallowAbsent) { attributes &= ~FeatureAttributes.UIDisallowAbsent; attributes |= FeatureAttributes.NoUnsupportedAdvertise; } return attributes; } set { // MsiSetFeatureAttributes doesn't indicate UIDisallowAbsent is valid // so remove it. FeatureAttributes attributes = value; attributes &= ~FeatureAttributes.UIDisallowAbsent; // Values for attributes that MsiSetFeatureAttributes uses are // double the values in the Attributes column of the Feature Table. uint attr = ((uint) attributes) << 1; // MsiSetFeatureAttributes MSDN documentation indicates // NOUNSUPPORTEDADVERTISE is 32. Conversion above changes this to 64 // which is undefined. Change this back to 32. uint noUnsupportedAdvertiseDbl = ((uint)FeatureAttributes.NoUnsupportedAdvertise) << 1; if ((attr & noUnsupportedAdvertiseDbl) == noUnsupportedAdvertiseDbl) { attr &= ~noUnsupportedAdvertiseDbl; attr |= (uint) FeatureAttributes.NoUnsupportedAdvertise; } uint ret = RemotableNativeMethods.MsiSetFeatureAttributes((int) this.session.Handle, this.name, attr); if (ret != (uint)NativeMethods.Error.SUCCESS) { if (ret == (uint)NativeMethods.Error.UNKNOWN_FEATURE) { throw InstallerException.ExceptionFromReturnCode(ret, this.name); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } } } /// <summary> /// Gets the title of the feature. /// </summary> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="ArgumentException">an unknown feature was requested</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetfeatureinfo.asp">MsiGetFeatureInfo</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Title { get { StringBuilder titleBuf = new StringBuilder(80); uint titleBufSize = (uint) titleBuf.Capacity; uint descBufSize = 0; uint attr; uint ret = NativeMethods.MsiGetFeatureInfo( (int) this.session.Handle, this.name, out attr, titleBuf, ref titleBufSize, null, ref descBufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { titleBuf.Capacity = (int) ++titleBufSize; ret = NativeMethods.MsiGetFeatureInfo( (int) this.session.Handle, this.name, out attr, titleBuf, ref titleBufSize, null, ref descBufSize); } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return titleBuf.ToString(); } } /// <summary> /// Gets the description of the feature. /// </summary> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="ArgumentException">an unknown feature was requested</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetfeatureinfo.asp">MsiGetFeatureInfo</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Description { get { StringBuilder descBuf = new StringBuilder(256); uint titleBufSize = 0; uint descBufSize = (uint) descBuf.Capacity; uint attr; uint ret = NativeMethods.MsiGetFeatureInfo( (int) this.session.Handle, this.name, out attr, null, ref titleBufSize, descBuf, ref descBufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { descBuf.Capacity = (int) ++descBufSize; ret = NativeMethods.MsiGetFeatureInfo( (int) this.session.Handle, this.name, out attr, null, ref titleBufSize, descBuf, ref descBufSize); } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return descBuf.ToString(); } } /// <summary> /// Calculates the disk space required by the feature and its selected children and parent features. /// </summary> /// <param name="includeParents">If true, the parent features are included in the cost.</param> /// <param name="includeChildren">If true, the child features are included in the cost.</param> /// <param name="installState">Specifies the installation state.</param> /// <returns>The disk space requirement in bytes.</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetfeaturecost.asp">MsiGetFeatureCost</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public long GetCost(bool includeParents, bool includeChildren, InstallState installState) { const int MSICOSTTREE_CHILDREN = 1; const int MSICOSTTREE_PARENTS = 2; int cost; uint ret = RemotableNativeMethods.MsiGetFeatureCost( (int) this.session.Handle, this.name, (includeParents ? MSICOSTTREE_PARENTS : 0) | (includeChildren ? MSICOSTTREE_CHILDREN : 0), (int) installState, out cost); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return cost * 512L; } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if PARALLEL using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Threading; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Execution { /// <summary> /// Summary description for EventQueueTests. /// </summary> [TestFixture] public class EventQueueTests { private static readonly Event[] events = { new TestStartedEvent(null), new TestStartedEvent(null), new TestFinishedEvent(null), new TestStartedEvent(null), new TestFinishedEvent(null), new TestFinishedEvent(null), }; private static void EnqueueEvents(EventQueue q) { foreach (Event e in events) q.Enqueue(e); } private static void SendEvents(ITestListener listener) { foreach (Event e in events) e.Send(listener); } private static void VerifyQueue(EventQueue q) { for (int index = 0; index < events.Length; index++) { Event e = q.Dequeue(false); Assert.AreEqual(events[index].GetType(), e.GetType(), string.Format("Event {0}", index)); } } private static void StartPump(EventPump pump, int waitTime) { pump.Start(); WaitForPumpToStart(pump, waitTime); } private static void StopPump(EventPump pump, int waitTime) { pump.Stop(); WaitForPumpToStop(pump, waitTime); } private static void WaitForPumpToStart(EventPump pump, int waitTime) { while (waitTime > 0 && pump.PumpState != EventPumpState.Pumping) { Thread.Sleep(100); waitTime -= 100; } } private static void WaitForPumpToStop(EventPump pump, int waitTime) { while (waitTime > 0 && pump.PumpState != EventPumpState.Stopped) { Thread.Sleep(100); waitTime -= 100; } } #region EventQueue Tests [Test] public void QueueEvents() { EventQueue q = new EventQueue(); EnqueueEvents(q); VerifyQueue(q); } [Test] public void DequeueEmpty() { EventQueue q = new EventQueue(); Assert.IsNull(q.Dequeue(false)); } [TestFixture] public class DequeueBlocking_StopTest : ProducerConsumerTest { private EventQueue q; private volatile int receivedEvents; [Test] [Timeout(1000)] public void DequeueBlocking_Stop() { this.q = new EventQueue(); this.receivedEvents = 0; this.RunProducerConsumer(); Assert.AreEqual(events.Length + 1, this.receivedEvents); } protected override void Producer() { EnqueueEvents(this.q); while (this.receivedEvents < events.Length) Thread.Sleep(30); this.q.Stop(); } protected override void Consumer() { Event e; do { e = this.q.Dequeue(true); this.receivedEvents++; Thread.MemoryBarrier(); } while (e != null); } } [TestFixture] public class SetWaitHandle_Enqueue_AsynchronousTest : ProducerConsumerTest { private EventQueue q; private volatile bool afterEnqueue; [Test] [Timeout(1000)] public void SetWaitHandle_Enqueue_Asynchronous() { using (AutoResetEvent waitHandle = new AutoResetEvent(false)) { this.q = new EventQueue(); this.q.SetWaitHandleForSynchronizedEvents(waitHandle); this.afterEnqueue = false; this.RunProducerConsumer(); } } protected override void Producer() { Event asynchronousEvent = new TestStartedEvent(new TestSuite("Dummy")); Assert.IsFalse(asynchronousEvent.IsSynchronous); this.q.Enqueue(asynchronousEvent); this.afterEnqueue = true; Thread.MemoryBarrier(); } protected override void Consumer() { this.q.Dequeue(true); Thread.Sleep(30); Assert.IsTrue(this.afterEnqueue); } } #endregion #region QueuingEventListener Tests [Test] public void SendEvents() { QueuingEventListener el = new QueuingEventListener(); SendEvents(el); VerifyQueue(el.Events); } #endregion #region EventPump Tests [Test] public void StartAndStopPumpOnEmptyQueue() { using (EventPump pump = new EventPump(TestListener.NULL, new EventQueue())) { pump.Name = "StartAndStopPumpOnEmptyQueue"; StartPump(pump, 1000); Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Pumping)); StopPump(pump, 1000); Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Stopped)); } } [Test] [Timeout(3000)] public void PumpEvents() { EventQueue q = new EventQueue(); QueuingEventListener el = new QueuingEventListener(); using (EventPump pump = new EventPump(el, q)) { pump.Name = "PumpEvents"; Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Stopped)); StartPump(pump, 1000); Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Pumping)); EnqueueEvents(q); StopPump(pump, 1000); Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Stopped)); } VerifyQueue(el.Events); } [Test] [Timeout(1000)] public void PumpSynchronousAndAsynchronousEvents() { EventQueue q = new EventQueue(); using (EventPump pump = new EventPump(TestListener.NULL, q)) { pump.Name = "PumpSynchronousAndAsynchronousEvents"; pump.Start(); int numberOfAsynchronousEvents = 0; int sumOfAsynchronousQueueLength = 0; const int Repetitions = 2; for (int i = 0; i < Repetitions; i++) { foreach (Event e in events) { q.Enqueue(e); if (e.IsSynchronous) Assert.That(q.Count, Is.EqualTo(0)); else { sumOfAsynchronousQueueLength += q.Count; numberOfAsynchronousEvents++; } } } Console.WriteLine("Average queue length: {0}", (float)sumOfAsynchronousQueueLength / numberOfAsynchronousEvents); } } /// <summary> /// Floods the queue of an EventPump with multiple concurrent event producers. /// Prints the maximum queue length to Console, but does not implement an /// oracle on what the maximum queue length should be. /// </summary> /// <param name="numberOfProducers">The number of concurrent producer threads.</param> /// <param name="producerDelay"> /// If <c>true</c>, the producer threads slow down by adding a short delay time. /// </param> [TestCase(1, false)] [TestCase(5, true)] [TestCase(5, false)] [Explicit("Takes several seconds. Just prints the queue length of the EventPump to Console, but has no oracle regarding this.")] public void EventPumpQueueLength(int numberOfProducers, bool producerDelay) { EventQueue q = new EventQueue(); EventProducer[] producers = new EventProducer[numberOfProducers]; for (int i = 0; i < numberOfProducers; i++) producers[i] = new EventProducer(q, i, producerDelay); using (EventPump pump = new EventPump(TestListener.NULL, q)) { pump.Name = "EventPumpQueueLength"; pump.Start(); foreach (EventProducer p in producers) p.ProducerThread.Start(); foreach (EventProducer p in producers) p.ProducerThread.Join(); pump.Stop(); } Assert.That(q.Count, Is.EqualTo(0)); foreach (EventProducer p in producers) { Console.WriteLine("#Events: {0}, MaxQueueLength: {1}", p.SentEventsCount, p.MaxQueueLength); Assert.IsNull(p.Exception, "{0}", p.Exception); } } #endregion public abstract class ProducerConsumerTest { private volatile Exception myConsumerException; protected void RunProducerConsumer() { this.myConsumerException = null; Thread consumerThread = new Thread(new ThreadStart(this.ConsumerThreadWrapper)); try { consumerThread.Start(); this.Producer(); bool consumerStopped = consumerThread.Join(1000); Assert.IsTrue(consumerStopped); } finally { ThreadUtility.Kill(consumerThread); } Assert.IsNull(this.myConsumerException); } protected abstract void Producer(); protected abstract void Consumer(); private void ConsumerThreadWrapper() { try { this.Consumer(); } catch (System.Threading.ThreadAbortException) { #if !NETCF Thread.ResetAbort(); #endif } catch (Exception ex) { this.myConsumerException = ex; } } } private class EventProducer { public readonly Thread ProducerThread; public int SentEventsCount; public int MaxQueueLength; public Exception Exception; private readonly EventQueue queue; private readonly bool delay; public EventProducer(EventQueue q, int id, bool delay) { this.queue = q; this.ProducerThread = new Thread(new ThreadStart(this.Produce)); this.ProducerThread.Name = this.GetType().FullName + id; this.delay = delay; } private void Produce() { try { Event e = new TestStartedEvent(new TestSuite("Dummy")); DateTime start = DateTime.Now; while (DateTime.Now - start <= TimeSpan.FromSeconds(3)) { this.queue.Enqueue(e); this.SentEventsCount++; this.MaxQueueLength = Math.Max(this.queue.Count, this.MaxQueueLength); // without Sleep or with just a Sleep(0), the EventPump thread does not keep up and the queue gets very long if (this.delay) Thread.Sleep(1); } } catch (Exception ex) { this.Exception = ex; } } } } } #endif
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Reflection; using ServiceStack.Text.Common; using ServiceStack.Text.Json; namespace ServiceStack.Text { /// <summary> /// Creates an instance of a Type from a string value /// </summary> public static class JsonSerializer { private static readonly UTF8Encoding UTF8EncodingWithoutBom = new UTF8Encoding(false); public static T DeserializeFromString<T>(string value) { if (string.IsNullOrEmpty(value)) return default(T); return (T)JsonReader<T>.Parse(value); } public static T DeserializeFromReader<T>(TextReader reader) { return DeserializeFromString<T>(reader.ReadToEnd()); } public static object DeserializeFromString(string value, Type type) { return string.IsNullOrEmpty(value) ? null : JsonReader.GetParseFn(type)(value); } public static object DeserializeFromReader(TextReader reader, Type type) { return DeserializeFromString(reader.ReadToEnd(), type); } public static string SerializeToString<T>(T value) { if (value == null || value is Delegate) return null; if (typeof(T) == typeof(object) || typeof(T).IsAbstract() || typeof(T).IsInterface()) { if (typeof(T).IsAbstract() || typeof(T).IsInterface()) JsState.IsWritingDynamic = true; var result = SerializeToString(value, value.GetType()); if (typeof(T).IsAbstract() || typeof(T).IsInterface()) JsState.IsWritingDynamic = false; return result; } var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { if (typeof(T) == typeof(string)) { JsonUtils.WriteString(writer, value as string); } else { JsonWriter<T>.WriteRootObject(writer, value); } } return sb.ToString(); } public static string SerializeToString(object value, Type type) { if (value == null) return null; var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { if (type == typeof(string)) { JsonUtils.WriteString(writer, value as string); } else { JsonWriter.GetWriteFn(type)(writer, value); } } return sb.ToString(); } public static void SerializeToWriter<T>(T value, TextWriter writer) { if (value == null) return; if (typeof(T) == typeof(string)) { writer.Write(value); return; } if (typeof(T) == typeof(object) || typeof(T).IsAbstract() || typeof(T).IsInterface()) { if (typeof(T).IsAbstract() || typeof(T).IsInterface()) JsState.IsWritingDynamic = true; SerializeToWriter(value, value.GetType(), writer); if (typeof(T).IsAbstract() || typeof(T).IsInterface()) JsState.IsWritingDynamic = false; return; } JsonWriter<T>.WriteRootObject(writer, value); } public static void SerializeToWriter(object value, Type type, TextWriter writer) { if (value == null) return; if (type == typeof(string)) { writer.Write(value); return; } JsonWriter.GetWriteFn(type)(writer, value); } public static void SerializeToStream<T>(T value, Stream stream) { if (value == null) return; if (typeof(T) == typeof(object) || typeof(T).IsAbstract() || typeof(T).IsInterface()) { if (typeof(T).IsAbstract() || typeof(T).IsInterface()) JsState.IsWritingDynamic = true; SerializeToStream(value, value.GetType(), stream); if (typeof(T).IsAbstract() || typeof(T).IsInterface()) JsState.IsWritingDynamic = false; return; } var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsonWriter<T>.WriteRootObject(writer, value); writer.Flush(); } public static void SerializeToStream(object value, Type type, Stream stream) { var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsonWriter.GetWriteFn(type)(writer, value); writer.Flush(); } public static T DeserializeFromStream<T>(Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString<T>(reader.ReadToEnd()); } } public static object DeserializeFromStream(Type type, Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString(reader.ReadToEnd(), type); } } #if !WINDOWS_PHONE && !SILVERLIGHT public static T DeserializeResponse<T>(WebRequest webRequest) { #if NETFX_CORE var async = webRequest.GetResponseAsync(); async.Wait(); var webRes = async.Result; using (var stream = webRes.GetResponseStream()) { return DeserializeFromStream<T>(stream); } #else using (var webRes = webRequest.GetResponse()) { using (var stream = webRes.GetResponseStream()) { return DeserializeFromStream<T>(stream); } } #endif } public static object DeserializeResponse<T>(Type type, WebRequest webRequest) { #if NETFX_CORE var async = webRequest.GetResponseAsync(); async.Wait(); var webRes = async.Result; using (var stream = webRes.GetResponseStream()) { return DeserializeFromStream(type, stream); } #else using (var webRes = webRequest.GetResponse()) { using (var stream = webRes.GetResponseStream()) { return DeserializeFromStream(type, stream); } } #endif } public static T DeserializeRequest<T>(WebRequest webRequest) { #if NETFX_CORE var async = webRequest.GetResponseAsync(); async.Wait(); var webRes = async.Result; return DeserializeResponse<T>(webRes); #else using (var webRes = webRequest.GetResponse()) { return DeserializeResponse<T>(webRes); } #endif } public static object DeserializeRequest(Type type, WebRequest webRequest) { #if NETFX_CORE var async = webRequest.GetResponseAsync(); async.Wait(); var webRes = async.Result; return DeserializeResponse(type, webRes); #else using (var webRes = webRequest.GetResponse()) { return DeserializeResponse(type, webRes); } #endif } #endif public static T DeserializeResponse<T>(WebResponse webResponse) { using (var stream = webResponse.GetResponseStream()) { return DeserializeFromStream<T>(stream); } } public static object DeserializeResponse(Type type, WebResponse webResponse) { using (var stream = webResponse.GetResponseStream()) { return DeserializeFromStream(type, stream); } } } }
// 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 HorizontalAddSingle() { var test = new HorizontalBinaryOpTest__HorizontalAddSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class HorizontalBinaryOpTest__HorizontalAddSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private HorizontalBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static HorizontalBinaryOpTest__HorizontalAddSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public HorizontalBinaryOpTest__HorizontalAddSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new HorizontalBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse3.HorizontalAdd( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse3.HorizontalAdd( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse3.HorizontalAdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse3.HorizontalAdd(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new HorizontalBinaryOpTest__HorizontalAddSingle(); var result = Sse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { for (var outer = 0; outer < (VectorSize / 16); outer++) { for (var inner = 0; inner < (8 / sizeof(Single)); inner++) { var i1 = (outer * (16 / sizeof(Single))) + inner; var i2 = i1 + (8 / sizeof(Single)); var i3 = (outer * (16 / sizeof(Single))) + (inner * 2); if (BitConverter.SingleToInt32Bits(result[i1]) != BitConverter.SingleToInt32Bits(left[i3] + left[i3 + 1])) { Succeeded = false; break; } if (BitConverter.SingleToInt32Bits(result[i2]) != BitConverter.SingleToInt32Bits(right[i3] + right[i3 + 1])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse3)}.{nameof(Sse3.HorizontalAdd)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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 CompareGreaterThanInt64() { var test = new SimpleBinaryOpTest__CompareGreaterThanInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanInt64 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int64); private const int Op2ElementCount = VectorSize / sizeof(Int64); private const int RetElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64, Int64, Int64> _dataTable; static SimpleBinaryOpTest__CompareGreaterThanInt64() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareGreaterThanInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64, Int64, Int64>(_data1, _data2, new Int64[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.CompareGreaterThan( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.CompareGreaterThan( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.CompareGreaterThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx2.CompareGreaterThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareGreaterThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareGreaterThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareGreaterThanInt64(); var result = Avx2.CompareGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.CompareGreaterThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] > right[0]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] > right[i]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.CompareGreaterThan)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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; using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Tests { public static class Array17Tests { [Fact] public static void AsReadOnly() { var array = new string[] { "a", "b" }; System.Collections.ObjectModel.ReadOnlyCollection<string> ro = Array.AsReadOnly(array); Assert.Equal(array, ro); Assert.Equal(new System.Collections.ObjectModel.ReadOnlyCollection<string>(array), ro); } [Fact] public static void Construction() { // Check a number of the simple APIs on Array for dimensions up to 4. Array array = new int[] { 1, 2, 3 }; VerifyArray(array, 1, new int[] { 3 }, new int[] { 0 }, new int[] { 2 }, true); array = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; VerifyArray(array, 2, new int[] { 2, 3 }, new int[] { 0, 0 }, new int[] { 1, 2 }, true); array = new int[2, 3, 4]; VerifyArray(array, 3, new int[] { 2, 3, 4 }, new int[] { 0, 0, 0 }, new int[] { 1, 2, 3 }, true); array = new int[2, 3, 4, 5]; VerifyArray(array, 4, new int[] { 2, 3, 4, 5 }, new int[] { 0, 0, 0, 0 }, new int[] { 1, 2, 3, 4 }, true); } [Theory] public static void ForEach() { Array.ForEach<int>(new int[] { }, new Action<int>(i => { throw new InvalidOperationException(); })); // Did not throw; no items int counter = 0; int exp = 0; Array.ForEach<int>(new int[] { 1, 2, 3 }, new Action<int>(i => { counter += i; exp = (i==1)?1:(i==2)?3:6; Assert.Equal(exp, counter); })); } [Fact] public static void ForEach_Invalid() { AssertExtensions.Throws<ArgumentNullException>("array", () => { Array.ForEach<short>(null, new Action<short>(i => i++)); }); // Array is null AssertExtensions.Throws<ArgumentNullException>("action", () => { Array.ForEach<string>(new string[] { }, null); }); // Action is null Assert.Throws<InvalidOperationException>(() => { Array.ForEach<string>(new string[] { "a" }, i => { throw new InvalidOperationException(); }); // Action throws }); } public static IEnumerable<object[]> Copy_TestData() { yield return new object[] { new int[] { 0x12345678, 0x22334455, 0x778899aa }, 0, new int[3], 0, 3, new int[] { 0x12345678, 0x22334455, 0x778899aa } }; int[] intArray1 = new int[] { 0x12345678, 0x22334455, 0x778899aa, 0x55443322, 0x33445566 }; yield return new object[] { intArray1, 3, intArray1, 2, 2, new int[] { 0x12345678, 0x22334455, 0x55443322, 0x33445566, 0x33445566 } }; int[] intArray2 = new int[] { 0x12345678, 0x22334455, 0x778899aa, 0x55443322, 0x33445566 }; yield return new object[] { intArray2, 2, intArray2, 3, 2, new int[] { 0x12345678, 0x22334455, 0x778899aa, 0x778899aa, 0x55443322 } }; yield return new object[] { new string[] { "Red", "Green", null, "Blue" }, 0, new string[] { "X", "X", "X", "X" }, 0, 4, new string[] { "Red", "Green", null, "Blue" } }; string[] stringArray = new string[] { "Red", "Green", null, "Blue" }; yield return new object[] { stringArray, 1, stringArray, 2, 2, new string[] { "Red", "Green", "Green", null } }; // Value type array to reference type array yield return new object[] { new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new object[10], 5, 3, new object[] { null, null, null, null, null, 2, 3, 4, null, null } }; yield return new object[] { new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new IEquatable<int>[10], 5, 3, new IEquatable<int>[] { null, null, null, null, null, 2, 3, 4, null, null } }; yield return new object[] { new int?[] { 0, 1, 2, default(int?), 4, 5, 6, 7, 8, 9 }, 2, new object[10], 5, 3, new object[] { null, null, null, null, null, 2, null, 4, null, null } }; // Reference type array to value type array yield return new object[] { new object[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, 4, 0xcc, 0xcc } }; yield return new object[] { new IEquatable<int>[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, 4, 0xcc, 0xcc } }; yield return new object[] { new IEquatable<int>[] { 0, new NotInt32(), 2, 3, 4, new NotInt32(), 6, 7, 8, 9 }, 2, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, 4, 0xcc, 0xcc } }; yield return new object[] { new object[] { 0, 1, 2, 3, null, 5, 6, 7, 8, 9 }, 2, new int?[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int?[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, null, 0xcc, 0xcc } }; } [Theory] [MemberData(nameof(Copy_TestData))] public static void Copy_Long(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, Array expected) { if (sourceIndex == 0 && destinationIndex == 0) { // Use Copy(Array, Array, long) Array testArray = (Array)sourceArray.Clone(); Array.Copy(sourceArray, destinationArray, (long)length); Assert.Equal(expected, destinationArray); } // Use Copy(Array, long, Array, long, long) Array.Copy(sourceArray, (long)sourceIndex, destinationArray, (long)destinationIndex, (long)length); Assert.Equal(expected, destinationArray); } public static IEnumerable<object[]> CopyTo_TestData() { yield return new object[] { new B1[10], new D1[10], 0, new D1[10] }; yield return new object[] { new D1[10], new B1[10], 0, new B1[10] }; yield return new object[] { new B1[10], new I1[10], 0, new I1[10] }; yield return new object[] { new I1[10], new B1[10], 0, new B1[10] }; yield return new object[] { new int[] { 0, 1, 2, 3 }, new int[4], 0, new int[] { 0, 1, 2, 3 } }; yield return new object[] { new int[] { 0, 1, 2, 3 }, new int[7], 2, new int[] { 0, 0, 0, 1, 2, 3, 0 } }; } [Theory] [MemberData(nameof(CopyTo_TestData))] public static void CopyTo_Long(Array source, Array destination, long index, Array expected) { source.CopyTo(destination, index); Assert.Equal(expected, destination); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")] public static void CreateInstance_Type_Int_Int() { int[,] intArray2 = (int[,])Array.CreateInstance(typeof(int), 1, 2); VerifyArray(intArray2, 2, new int[] { 1, 2 }, new int[] { 0, 0 }, new int[] { 0, 1 }, false); intArray2[0, 1] = 42; Assert.Equal(42, intArray2[0, 1]); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")] public static void CreateInstance_Type_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0)); // Element type is null Assert.Throws<NotSupportedException>(() => Array.CreateInstance(typeof(void), 0)); // Element type is not supported (void) Assert.Throws<NotSupportedException>(() => Array.CreateInstance(typeof(List<>), 0)); // Element type is not supported (generic) Assert.Throws<NotSupportedException>(() => Array.CreateInstance(typeof(int).MakeByRefType(), 0)); // Element type is not supported (ref) AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Array.CreateInstance(typeof(int), -1)); // Length < 0 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")] public static void CreateInstance_Type_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0, 1)); // Element type is null Assert.Throws<NotSupportedException>(() => Array.CreateInstance(typeof(void), 0, 1)); // Element type is not supported (void) Assert.Throws<NotSupportedException>(() => Array.CreateInstance(typeof(List<>), 0, 1)); // Element type is not supported (generic) Assert.Throws<NotSupportedException>(() => Array.CreateInstance(typeof(int).MakeByRefType(), 0, 1)); // Element type is not supported (ref) AssertExtensions.Throws<ArgumentOutOfRangeException>("length2", () => Array.CreateInstance(typeof(int), 0, -1)); // Length < 0 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")] public static void CreateInstance_Type_Int_Int_Int() { int[,,] intArray3 = (int[,,])Array.CreateInstance(typeof(int), 1, 2, 3); VerifyArray(intArray3, 3, new int[] { 1, 2, 3 }, new int[] { 0, 0, 0 }, new int[] { 0, 1, 2 }, false); intArray3[0, 1, 2] = 42; Assert.Equal(42, intArray3[0, 1, 2]); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")] public static void CreateInstance_Type_Int_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0, 1, 2)); // Element type is null Assert.Throws<NotSupportedException>(() => Array.CreateInstance(typeof(void), 0, 1, 2)); // Element type is not supported (void) Assert.Throws<NotSupportedException>(() => Array.CreateInstance(typeof(List<>), 0, 1, 2)); // Element type is not supported (generic) Assert.Throws<NotSupportedException>(() => Array.CreateInstance(typeof(int).MakeByRefType(), 0, 1, 2)); // Element type is not supported (ref) AssertExtensions.Throws<ArgumentOutOfRangeException>("length3", () => Array.CreateInstance(typeof(int), 0, 1, -1)); // Length < 0 } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")] public static void CreateInstance_Type_IntArray() { string[] stringArray = (string[])Array.CreateInstance(typeof(string), new int[] { 10 }); Assert.Equal(stringArray, new string[10]); stringArray = (string[])Array.CreateInstance(typeof(string), new int[] { 0 }); Assert.Equal(stringArray, new string[0]); int[] intArray1 = (int[])Array.CreateInstance(typeof(int), new int[] { 1 }); VerifyArray(intArray1, 1, new int[] { 1 }, new int[] { 0 }, new int[] { 0 }, false); Assert.Equal(intArray1, new int[1]); int[,] intArray2 = (int[,])Array.CreateInstance(typeof(int), new int[] { 1, 2 }); VerifyArray(intArray2, 2, new int[] { 1, 2 }, new int[] { 0, 0 }, new int[] { 0, 1 }, false); intArray2[0, 1] = 42; Assert.Equal(42, intArray2[0, 1]); int[,,] intArray3 = (int[,,])Array.CreateInstance(typeof(int), new int[] { 1, 2, 3 }); VerifyArray(intArray3, 3, new int[] { 1, 2, 3 }, new int[] { 0, 0, 0 }, new int[] { 0, 1, 2 }, false); intArray3[0, 1, 2] = 42; Assert.Equal(42, intArray3[0, 1, 2]); int[,,,] intArray4 = (int[,,,])Array.CreateInstance(typeof(int), new int[] { 1, 2, 3, 4 }); VerifyArray(intArray4, 4, new int[] { 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0 }, new int[] { 0, 1, 2 }, false); intArray4[0, 1, 2, 3] = 42; Assert.Equal(42, intArray4[0, 1, 2, 3]); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")] public static void CreateInstance_Type_IntArray_IntArray() { int[] intArray1 = (int[])Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 0 }); Assert.Equal(intArray1, new int[5]); VerifyArray(intArray1, 1, new int[] { 5 }, new int[] { 0 }, new int[] { 4 }, false); int[,,] intArray2 = (int[,,])Array.CreateInstance(typeof(int), new int[] { 7, 8, 9 }, new int[] { 1, 2, 3 }); Assert.Equal(intArray2, new int[7, 8, 9]); VerifyArray(intArray2, 3, new int[] { 7, 8, 9 }, new int[] { 1, 2, 3 }, new int[] { 7, 9, 11 }, false); } [Theory] public static void ConvertAll() { var result = Array.ConvertAll<int, int>(new int[] { }, new Converter<int, int>(i => { throw new InvalidOperationException(); })); // Does not throw - no entries Assert.Equal(new int[] { }, result); var result2 = Array.ConvertAll<int, string>(new int[] { 1 }, new Converter<int, string>(i => i++.ToString())); Assert.Equal(new string[] { "2" }, result2); result2 = Array.ConvertAll<int, string>(new int[] { 1, 2 }, new Converter<int, string>(i => i++.ToString())); Assert.Equal(new string[] { "2", "3" }, result2); result2 = Array.ConvertAll<int, string>(new int[] { 1 }, new Converter<int, string>(i => null)); Assert.Equal(new string[] { null }, result2); } [Fact] public static void ConvertAll_Invalid() { AssertExtensions.Throws<ArgumentNullException>("array", () => { Array.ConvertAll<short, short>(null, i => i); }); // Array is null AssertExtensions.Throws<ArgumentNullException>("converter", () => { Array.ConvertAll<string, string>(new string[] { }, null); }); // Converter is null Assert.Throws<InvalidOperationException>(() => { Array.ConvertAll<string, string>(new string[] { "x" }, i => { throw new InvalidOperationException(); }); // Converter throws }); } [Fact] public static void IsFixedSize() { Assert.Equal(true, new string[] { }.IsFixedSize); } [Fact] public static void IsReadOnly() { Assert.Equal(false, new int[] { }.IsReadOnly); } [Fact] public static void IsSynchronized() { Assert.Equal(false, new int[] { }.IsSynchronized); } public static IEnumerable<object[]> Length_TestData() { yield return new object[] { new object[] { }, 0 }; yield return new object[] { new object[] { 1, 2 }, 2 }; } [Theory] [MemberData(nameof(Length_TestData))] public static void Length(Array array, int expected) { Assert.Equal(expected, array.Length); Assert.Equal(expected, array.LongLength); } [Fact] public static void SyncRoot_Equals_This() { var array = new string[] { }; Assert.Same(array, array.SyncRoot); } internal static void VerifyArray(Array array, int rank, int[] lengths, int[] lowerBounds, int[] upperBounds, bool checkIList) { Assert.Equal(rank, array.Rank); for (int i = 0; i < lengths.Length; i++) { Assert.Equal(lengths[i], array.GetLength(i)); Assert.Equal(lengths[i], array.GetLongLength(i)); } for (int i = 0; i < lowerBounds.Length; i++) Assert.Equal(lowerBounds[i], array.GetLowerBound(i)); for (int i = 0; i < upperBounds.Length; i++) Assert.Equal(upperBounds[i], array.GetUpperBound(i)); Assert.Throws<IndexOutOfRangeException>(() => array.GetLength(-1)); // Dimension < 0 Assert.Throws<IndexOutOfRangeException>(() => array.GetLength(array.Rank)); // Dimension >= array.Rank Assert.Throws<IndexOutOfRangeException>(() => array.GetLowerBound(-1)); // Dimension < 0 Assert.Throws<IndexOutOfRangeException>(() => array.GetLowerBound(array.Rank)); // Dimension >= array.Rank Assert.Throws<IndexOutOfRangeException>(() => array.GetUpperBound(-1)); // Dimension < 0 Assert.Throws<IndexOutOfRangeException>(() => array.GetUpperBound(array.Rank)); // Dimension >= array.Rank if (checkIList) { VerifyArrayAsIList(array); } Assert.Equal(array, array.SyncRoot); Assert.False(array.IsSynchronized); Assert.True(array.IsFixedSize); Assert.False(array.IsReadOnly); } private static void VerifyArrayAsIList(Array array) { IList ils = array; Assert.Equal(array.Length, ils.Count); Assert.Equal(array, ils.SyncRoot); Assert.False(ils.IsSynchronized); Assert.True(ils.IsFixedSize); Assert.False(ils.IsReadOnly); Assert.Throws<NotSupportedException>(() => ils.Add(2)); Assert.Throws<NotSupportedException>(() => ils.Insert(0, 2)); Assert.Throws<NotSupportedException>(() => ils.Remove(0)); Assert.Throws<NotSupportedException>(() => ils.RemoveAt(0)); if (array.Rank == 1) { for (int i = 0; i < array.Length; i++) { object obj = ils[i]; Assert.Equal(array.GetValue(i), obj); Assert.True(ils.Contains(obj)); Assert.Equal(i, ils.IndexOf(obj)); } Assert.False(ils.Contains(null)); Assert.False(ils.Contains(999)); Assert.Equal(-1, ils.IndexOf(null)); Assert.Equal(-1, ils.IndexOf(999)); ils[1] = 10; Assert.Equal(10, ils[1]); } else { Assert.Throws<RankException>(() => ils.Contains(null)); Assert.Throws<RankException>(() => ils.IndexOf(null)); } } private class NotInt32 : IEquatable<int> { public bool Equals(int other) { throw new NotImplementedException(); } } private class B1 { } private class D1 : B1 { } private class B2 { } private class D2 : B2 { } private interface I1 { } private interface I2 { } } }
using System; using System.Linq; using System.Collections.Generic; using System.IO; using System.Windows.Forms; using DOKuStar.Diagnostics.Tracing; // Enable compiler switches for your export extension #if ProcessSuite using CaptureCenter.ProcessSuite; #endif #if CMIS using CaptureCenter.CMIS; #endif #if SQL using CaptureCenter.SqlEE; #endif #if EDOCS using CaptureCenter.eDocs; #endif #if HELLO_WORLD using CaptureCenter.HelloWorld; #endif #if SPO using CaptureCenter.SPO; #endif #if AX using CaptureCenter.ApplicationExtender; #endif #if xECM using CaptureCenter.xECM; #endif namespace ExportExtensionCommon { public partial class Main : Form { #region Construction private SIEEControl control; private SIEESettings settings; private SIEEExport export; private SIEEDescription description; private SIEEFieldlist schema; private SIEEBatch batch; private string document; private SIEEDefaultValues defaultSettings = null; private SIEEDefaultValues defaultFieldValues = null; private string defaultDocument; Dictionary<string, string> factoryNameMap = new Dictionary<string, string>(); public Main() { InitializeComponent(); } #endregion #region Form load and close private void Main_Load(object sender, EventArgs e) { string basePath = AppDomain.CurrentDomain.BaseDirectory; if (!Directory.Exists(basePath)) return; string targetTraceFile = Path.Combine(TraceManager.RootPath, "CaptureCenter.traceconfig"); TraceConfigurator.ConfigureAndWatch(new FileInfo(targetTraceFile)); #if ProcessSuite SIEEFactoryManager.Add(new ProcessSuiteFactory()); #endif #if CMIS SIEEFactoryManager.Add(new CMISFactory()); #endif #if SQL SIEEFactoryManager.Add(new SqlEEFactory()); #endif #if EDOCS SIEEFactoryManager.Add(new eDocsFactory()); #endif #if HELLO_WORLD SIEEFactoryManager.Add(new HelloWorldFactory()); #endif #if SPO SIEEFactoryManager.Add(new SPOFactory()); #endif #if AX SIEEFactoryManager.Add(new AXFactory()); #endif #if xECM SIEEFactoryManager.Add(new xECMFactory()); #endif foreach (string ext in SIEEFactoryManager.GetKeysFromTypeName()) { string name = ext.Split('.').Last(); cbox_extensionSelector.Items.Add(name); factoryNameMap[name] = ext; } cbox_extensionSelector.Text = Properties.Settings.Default.CurrentExtension; if (Properties.Settings.Default.MainSize.Width != 0) Size = Properties.Settings.Default.MainSize; if (Properties.Settings.Default.MaintRichTextFont != null) richTextBox_settings.Font = Properties.Settings.Default.MaintRichTextFont; richTextBox_settings.ForeColor = Properties.Settings.Default.MainRichTextColor; setDefaults(); } private void Main_Closing(object sender, FormClosingEventArgs e) { Properties.Settings.Default.MainSize = Size; Properties.Settings.Default.Save(); } #endregion #region Defaults private void setDefaults() { defaultSettings = new SIEEDefaultValues(); if (!string.IsNullOrEmpty(Properties.Settings.Default.DefaultSettings)) { try { defaultSettings.Initialize(Properties.Settings.Default.DefaultSettings); } catch (Exception e) { MessageBox.Show("Could not load default settings from " + Properties.Settings.Default.DefaultSettings + ":\n" + e.Message); defaultSettings = null; } } defaultFieldValues = new SIEEDefaultValues(); if (!string.IsNullOrEmpty(Properties.Settings.Default.DefaultValues)) { try { defaultFieldValues.Initialize(Properties.Settings.Default.DefaultValues); } catch (Exception e) { MessageBox.Show("Could not load default values from " + Properties.Settings.Default.DefaultValues + ":\n" + e.Message); defaultFieldValues = null; } } defaultDocument = Properties.Settings.Default.DefaultDocument; } #endregion #region Configure private void btn_configure_Click(object sender, EventArgs e) { Configure confDlg = new Configure(); Cursor.Current = Cursors.WaitCursor; try { cbox_extensionSelector_SelectedIndexChanged(null, null); confDlg.AddControl(control); control.Size = confDlg.Size; // Simulate serialization by SIEE and by OCC confDlg.Settings = (SIEESettings)SIEESerializer.Clone(settings); string xmlString = Serializer.SerializeToXmlString(settings, System.Text.Encoding.Unicode); if (Properties.Settings.Default.ConfigSize.Width != 0) confDlg.Size = Properties.Settings.Default.ConfigSize; if (confDlg.MyShowDialog() == DialogResult.OK) { settings = confDlg.Settings; try { schema = settings.CreateSchema(); schema.MakeFieldnamesOCCCompliant(); verifySchema(schema); lbl_message.Text = "Settings and schema"; lbl_location.Text = description.GetLocation(settings); richTextBox_settings.Text = settings.ToString() + Environment.NewLine + "---------------" + Environment.NewLine + schema.ToString(data: false) + Environment.NewLine + "---------------" + Environment.NewLine + "Location = " + description.GetLocation(settings); btn_export.Enabled = false; btn_capture.Enabled = true; lbl_status.Text = "Configuration ready"; } catch (Exception e1) { MessageBox.Show("Error loading configuration\n" + e1.Message); } Properties.Settings.Default.ConfigSize = confDlg.Size; saveCurrentSettings(); } } finally { Cursor.Current = Cursors.Default; } } private void verifySchema(SIEEFieldlist schema) { if (schema.Where(n => n.ExternalId == null || n.ExternalId == string.Empty).Count() > 0) throw new Exception("ExternalID null or empty"); if (schema.Select(n => n.ExternalId).Distinct().Count() != schema.Count()) throw new Exception("ExternamIDs are not distinct"); } #endregion #region Capture private void btn_capture_Click(object sender, EventArgs e) { Capture captureDlg = new Capture(settings, schema); captureDlg.DefaultFieldValues = defaultFieldValues; captureDlg.DefaultDocument = defaultDocument; if (Properties.Settings.Default.CaptuerSize.Width != 0) captureDlg.Size = Properties.Settings.Default.CaptuerSize; if (captureDlg.MyShowDialog() == DialogResult.OK) { btn_export.Enabled = true; lbl_message.Text = "Data"; batch = captureDlg.GetData(); document = captureDlg.GetDocument(); richTextBox_settings.Text = batch.ToString(); lbl_status.Text = batch.Count + " document(s) ready for export"; } Properties.Settings.Default.CaptuerSize = captureDlg.Size; //captureDlg.Dispose(); } #endregion #region Export private void btn_export_Click(object sender, EventArgs e) { if (description == null) return; if (chkbox_clear.Checked) description.ClearLocation(settings); if (chbox_ignoreEmtpyFields.Checked) { List<SIEEField> toBeRemoved = new List<SIEEField>(); foreach (SIEEDocument doc in batch) { toBeRemoved = doc.Fieldlist.Where(n => !(n is SIEETableField) && n.Value == string.Empty).ToList(); foreach (SIEEField f in toBeRemoved) doc.Fieldlist.Remove(f); } } Cursor.Current = Cursors.WaitCursor; DateTime startTime = DateTime.Now; export.ExportBatch(settings, batch); TimeSpan duration = DateTime.Now - startTime; Cursor.Current = Cursors.Default; string timeTakenString = "Time taken: " + duration.Milliseconds + " milliseconds"; if (batch.ExportSucceeded()) SIEEMessageBox.Show("Success!\n" + timeTakenString, "Export result", System.Windows.MessageBoxImage.None); else SIEEMessageBox.Show("Failed:\n" + batch.ErrorMessage() + "\n" + timeTakenString, "Export result", System.Windows.MessageBoxImage.Error); export.Term(); } #endregion #region Other event handler private void cbox_extensionSelector_SelectedIndexChanged(object sender, EventArgs e) { string ext = cbox_extensionSelector.SelectedItem.ToString(); loadExportExtention(SIEEFactoryManager.GetFromSettingsTypename(factoryNameMap[ext])); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Simplified Interface for OCC Export Extension"); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { btn_exit_Click(sender, e); } private void openLocationToolStripMenuItem_Click(object sender, EventArgs e) { if (description == null) return; description.OpenLocation(description.GetLocation(settings)); } private void preferencesToolStripMenuItem_Click(object sender, EventArgs e) { Preferences preferencesDlg = new Preferences(); if (preferencesDlg.ShowDialog() == DialogResult.OK) { setDefaults(); } } private void btn_exit_Click(object sender, EventArgs e) { saveCurrentSettings(); Application.Exit(); } private void btn_font_Click(object sender, EventArgs e) { changeFont(); } private void lbl_location_Click(object sender, EventArgs e) { if (description == null) return; description.OpenLocation(description.GetLocation(settings)); } #endregion #region Functions private void loadExportExtention(SIEEFactory factory) { try { control = new SIEEControl(factory); settings = (SIEESettings)factory.CreateSettings(); export = (SIEEExport)factory.CreateExport(); description = (SIEEDescription)factory.CreateDescription(); } catch (Exception ex) { MessageBox.Show("Factory error.\n" + ex.Message); } if (chbox_reloadConfiguration.Checked && Properties.Settings.Default.SavedConfigurationType == description.TypeName) try { settings = (SIEESettings)SIEESerializer.StringToObject(Properties.Settings.Default.SavedConfiguration); } catch (Exception e) { MessageBox.Show("Loading saved configuration failed. Rason:\n" + e.Message); } btn_configure.Enabled = false; btn_capture.Enabled = false; btn_export.Enabled = false; try { SIEESerializer.StringToObject(SIEESerializer.ObjectToString(settings)); } catch (Exception ex) { MessageBox.Show("Serialization for settings object failed:\n" + ex.Message); cbox_extensionSelector.SelectedText = Properties.Settings.Default.CurrentExtension; return; } pict_Icon.Image = description.Image; btn_configure.Enabled = true; Properties.Settings.Default.CurrentExtension = cbox_extensionSelector.Text; lbl_status.Text = "Extension selected"; } private void saveCurrentSettings() { if (description != null) { Properties.Settings.Default.SavedConfigurationType = description.TypeName; Properties.Settings.Default.SavedConfiguration = SIEESerializer.ObjectToString(settings); } Properties.Settings.Default.Save(); } private void changeFont() { FontDialog dialog = new FontDialog() { ShowColor = true, Font = richTextBox_settings.Font, Color = richTextBox_settings.ForeColor, }; if (dialog.ShowDialog() != DialogResult.Cancel) { richTextBox_settings.Font = dialog.Font; richTextBox_settings.ForeColor = dialog.Color; Properties.Settings.Default.MaintRichTextFont = dialog.Font; Properties.Settings.Default.MainRichTextColor = dialog.Color; } } #endregion } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Collections.Generic; using System.Linq; using NodaTime.TimeZones; using NodaTime.Utility; namespace NodaTime.TzdbCompiler.Tzdb { /// <summary> /// Mutable class with only a static entry point, which converts and ID + sequence of ZoneRuleSet /// elements into a DateTimeZone. /// </summary> internal sealed class DateTimeZoneBuilder { private readonly List<ZoneInterval> zoneIntervals; private StandardDaylightAlternatingMap? tailZone; private DateTimeZoneBuilder() { this.zoneIntervals = new List<ZoneInterval>(); } /// <summary> /// Builds a time zone with the given ID from a sequence of rule sets. /// </summary> internal static DateTimeZone Build(string id, IList<ZoneRuleSet> ruleSets) { Preconditions.CheckArgument(ruleSets.Count > 0, nameof(ruleSets), "Cannot create a time zone without any Zone entries"); var builder = new DateTimeZoneBuilder(); return builder.BuildZone(id, ruleSets); } private DateTimeZone BuildZone(string id, IList<ZoneRuleSet> ruleSets) { // This does most of the work: for each rule set (corresponding to a zone line // in the original data) we add some zone intervals. foreach (var ruleSet in ruleSets) { AddIntervals(ruleSet); } // Some of the abutting zone intervals from the rule set boundaries may have the // same offsets and name, in which case they can be coalesced. CoalesceIntervals(); // Finally, construct the time zone itself. Usually, we'll end up with a // PrecalculatedDateTimeZone here. if (zoneIntervals.Count == 1 && tailZone is null) { return new FixedDateTimeZone(id, zoneIntervals[0].WallOffset, zoneIntervals[0].Name); } else { return new PrecalculatedDateTimeZone(id, zoneIntervals.ToArray(), tailZone); } } /// <summary> /// Adds the intervals from the given rule set to the end of the zone /// being built. The rule is deemed to take effect from the end of the previous /// zone interval, or the start of time if this is the first rule set (which must /// be a fixed one). Intervals are added until the rule set expires, or /// until we determine that the rule set continues to the end of time, /// possibly with a tail zone - a pair of standard/daylight rules which repeat /// forever. /// </summary> private void AddIntervals(ZoneRuleSet ruleSet) { // We use the last zone interval computed so far (if there is one) to work out where to start. var lastZoneInterval = zoneIntervals.LastOrDefault(); var start = lastZoneInterval?.End ?? Instant.BeforeMinValue; // Simple case: a zone line with fixed savings (or - for 0) // instead of a rule name. Just a single interval. if (ruleSet.IsFixed) { zoneIntervals.Add(ruleSet.CreateFixedInterval(start)); return; } // Work on a copy of the rule set. We eliminate rules from it as they expire, // so that we can tell when we're down to an infinite pair which can be represented // as a tail zone. var activeRules = new List<ZoneRecurrence>(ruleSet.Rules); // Surprisingly tricky bit to work out: how to handle the transition from // one rule set to another. We know the instant at which the new rule set // come in, but not what offsets/name to use from that point onwards: which // of the new rules is in force. We find out which rule would have taken // effect most recently before or on the transition instant - but using // the offsets from the final interval before the transition, instead // of the offsets which would have been in force if the new rule set were // actually extended backwards forever. // // It's possible that the most recent transition we find would actually // have started before that final interval anyway - but this appears to // match what zic produces. // // If we don't have a zone interval at all, we're starting at the start of // time, so there definitely aren't any preceding rules. var firstRule = lastZoneInterval is null ? null : activeRules .Select(rule => new { rule, prev = rule.PreviousOrSame(start, lastZoneInterval.StandardOffset, lastZoneInterval.Savings) }) .Where(pair => pair.prev != null) .OrderBy(pair => pair.prev!.Value.Instant) .Select(pair => pair.rule) .LastOrDefault(); // Every transition in this rule set will use the same standard offset. var standardOffset = ruleSet.StandardOffset; // previousTransition here is ongoing as we loop through the transitions. It's not like // lastZoneInterval, lastStandard and lastSavings, which refer to the last aspects of the // previous rule set. When we set it up, this is effectively the *first* transition leading // into the period in which the new rule set is ZoneTransition previousTransition; if (firstRule != null) { previousTransition = new ZoneTransition(start, firstRule.Name, standardOffset, firstRule.Savings); } else { // None of the rules in the current set have *any* transitions in the past, apparently. // For an example of this, see Europe/Prague (in 2015e, anyway). A zone line with the // Czech rule takes effect in 1944, but all the rules are from 1945 onwards. // Use standard time until the first transition, regardless of the previous savings, // and take the name for this first interval from the first standard time rule. var name = activeRules.First(rule => rule.Savings == Offset.Zero).Name; previousTransition = new ZoneTransition(start, name, standardOffset, Offset.Zero); } // Main loop - we keep going round until we run out of rules or hit infinity, each of which // corresponds with a return statement in the loop. while (true) { ZoneTransition? bestTransition = null; for (int i = 0; i < activeRules.Count; i++) { var rule = activeRules[i]; var nextTransition = rule.Next(previousTransition.Instant, standardOffset, previousTransition.Savings); // Once a rule is no longer active, remove it from the list. That way we can tell // when we can create a tail zone. if (nextTransition is null) { activeRules.RemoveAt(i); i--; continue; } var zoneTransition = new ZoneTransition(nextTransition.Value.Instant, rule.Name, standardOffset, rule.Savings); if (!zoneTransition.IsTransitionFrom(previousTransition)) { continue; } if (bestTransition is null || zoneTransition.Instant <= bestTransition.Instant) { bestTransition = zoneTransition; } } Instant currentUpperBound = ruleSet.GetUpperLimit(previousTransition.Savings); if (bestTransition is null || bestTransition.Instant >= currentUpperBound) { // No more transitions to find. (We may have run out of rules, or they may be beyond where this rule set expires.) // Add a final interval leading up to the upper bound of the rule set, unless the previous transition took us up to // this current bound anyway. // (This is very rare, but can happen if changing rule brings the upper bound down to the time // that the transition occurred. Example: 2008d, Europe/Sofia, April 1945.) if (currentUpperBound > previousTransition.Instant) { zoneIntervals.Add(previousTransition.ToZoneInterval(currentUpperBound)); } return; } // We have a non-final transition. so add an interval from the previous transition to // this one. zoneIntervals.Add(previousTransition.ToZoneInterval(bestTransition.Instant)); previousTransition = bestTransition; // Tail zone handling. // The final rule set must extend to infinity. There are potentially three ways // this can happen: // - All rules expire, leaving us with the final real transition, and an upper // bound of infinity. This is handled above. // - 1 rule is left, but it cannot create more than one transition in a row, // so again we end up with no transitions to record, and we bail out with // a final infinite interval. // - 2 rules are left which would alternate infinitely. This is represented // using a DaylightSavingZone as the tail zone. // // The code here caters for that last option, but needs to do it in stages. // When we first realize we will have a tail zone (an infinite rule set, // two rules left, both of which are themselves infinite) we can create the // tail zone, but we don't yet know that we're into its regular tick/tock. // It's possible that one rule only starts years after our current transition, // so we need to hit the first transition of that rule before we can create a // "seam" from the list of precomputed zone intervals to the calculated-on-demand // part of history. // For an example of why this is necessary, see Asia/Amman in 2013e: in late 2011 // we hit "two rules left" but the final rule only starts in 2013 - we don't want // to see a bogus transition into that rule in 2012. // We could potentially record fewer zone intervals by keeping track of which // rules have created at least one transition, but this approach is simpler. if (ruleSet.IsInfinite && activeRules.Count == 2) { if (tailZone != null) { // Phase two: both rules must now be active, so we're done. return; } ZoneRecurrence startRule = activeRules[0]; ZoneRecurrence endRule = activeRules[1]; if (startRule.IsInfinite && endRule.IsInfinite) { // Phase one: build the zone, so we can go round once again and then return. tailZone = new StandardDaylightAlternatingMap(standardOffset, startRule, endRule); } } } } /// <summary> /// Potentially join some abutting zone intervals, usually created /// due to the interval at the end of one rule set having the same name and offsets /// as the interval at the start of the next rule set. /// </summary> private void CoalesceIntervals() { for (int i = 0; i < zoneIntervals.Count - 1; i++) { var current = zoneIntervals[i]; var next = zoneIntervals[i + 1]; if (current.Name == next.Name && current.WallOffset == next.WallOffset && current.StandardOffset == next.StandardOffset) { zoneIntervals[i] = current.WithEnd(next.RawEnd); zoneIntervals.RemoveAt(i + 1); i--; // We may need to coalesce the next one, too. } } } } }
// 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; using System.Globalization; using System.Linq; using System.Runtime.Versioning; namespace System.Collections.Immutable { /// <summary> /// A readonly array with O(1) indexable lookup time. /// </summary> /// <typeparam name="T">The type of element stored by the array.</typeparam> /// <devremarks> /// This type has a documented contract of being exactly one reference-type field in size. /// Our own <see cref="T:System.Collections.Immutable.ImmutableInterlocked"/> class depends on it, as well as others externally. /// IMPORTANT NOTICE FOR MAINTAINERS AND REVIEWERS: /// This type should be thread-safe. As a struct, it cannot protect its own fields /// from being changed from one thread while its members are executing on other threads /// because structs can change *in place* simply by reassigning the field containing /// this struct. Therefore it is extremely important that /// ** Every member should only dereference <c>this</c> ONCE. ** /// If a member needs to reference the array field, that counts as a dereference of <c>this</c>. /// Calling other instance members (properties or methods) also counts as dereferencing <c>this</c>. /// Any member that needs to use <c>this</c> more than once must instead /// assign <c>this</c> to a local variable and use that for the rest of the code instead. /// This effectively copies the one field in the struct to a local variable so that /// it is insulated from other threads. /// </devremarks> [DebuggerDisplay("{DebuggerDisplay,nq}")] [NonVersionable] // Applies to field layout public partial struct ImmutableArray<T> : IEnumerable<T>, IEquatable<ImmutableArray<T>>, IImmutableArray { /// <summary> /// An empty (initialized) instance of <see cref="ImmutableArray{T}"/>. /// </summary> public static readonly ImmutableArray<T> Empty = new ImmutableArray<T>(new T[0]); /// <summary> /// The backing field for this instance. References to this value should never be shared with outside code. /// </summary> /// <remarks> /// This would be private, but we make it internal so that our own extension methods can access it. /// </remarks> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal T[] array; /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct /// *without making a defensive copy*. /// </summary> /// <param name="items">The array to use. May be null for "default" arrays.</param> internal ImmutableArray(T[] items) { this.array = items; } #region Operators /// <summary> /// Checks equality between two instances. /// </summary> /// <param name="left">The instance to the left of the operator.</param> /// <param name="right">The instance to the right of the operator.</param> /// <returns><c>true</c> if the values' underlying arrays are reference equal; <c>false</c> otherwise.</returns> [NonVersionable] public static bool operator ==(ImmutableArray<T> left, ImmutableArray<T> right) { return left.Equals(right); } /// <summary> /// Checks inequality between two instances. /// </summary> /// <param name="left">The instance to the left of the operator.</param> /// <param name="right">The instance to the right of the operator.</param> /// <returns><c>true</c> if the values' underlying arrays are reference not equal; <c>false</c> otherwise.</returns> [NonVersionable] public static bool operator !=(ImmutableArray<T> left, ImmutableArray<T> right) { return !left.Equals(right); } /// <summary> /// Checks equality between two instances. /// </summary> /// <param name="left">The instance to the left of the operator.</param> /// <param name="right">The instance to the right of the operator.</param> /// <returns><c>true</c> if the values' underlying arrays are reference equal; <c>false</c> otherwise.</returns> public static bool operator ==(ImmutableArray<T>? left, ImmutableArray<T>? right) { return left.GetValueOrDefault().Equals(right.GetValueOrDefault()); } /// <summary> /// Checks inequality between two instances. /// </summary> /// <param name="left">The instance to the left of the operator.</param> /// <param name="right">The instance to the right of the operator.</param> /// <returns><c>true</c> if the values' underlying arrays are reference not equal; <c>false</c> otherwise.</returns> public static bool operator !=(ImmutableArray<T>? left, ImmutableArray<T>? right) { return !left.GetValueOrDefault().Equals(right.GetValueOrDefault()); } #endregion /// <summary> /// Gets the element at the specified index in the read-only list. /// </summary> /// <param name="index">The zero-based index of the element to get.</param> /// <returns>The element at the specified index in the read-only list.</returns> public T this[int index] { [NonVersionable] get { // We intentionally do not check this.array != null, and throw NullReferenceException // if this is called while uninitialized. // The reason for this is perf. // Length and the indexer must be absolutely trivially implemented for the JIT optimization // of removing array bounds checking to work. return this.array[index]; } } #if !NETSTANDARD10 /// <summary> /// Gets a read-only reference to the element at the specified index in the read-only list. /// </summary> /// <param name="index">The zero-based index of the element to get a reference to.</param> /// <returns>A read-only reference to the element at the specified index in the read-only list.</returns> public ref readonly T ItemRef(int index) { // We intentionally do not check this.array != null, and throw NullReferenceException // if this is called while uninitialized. // The reason for this is perf. // Length and the indexer must be absolutely trivially implemented for the JIT optimization // of removing array bounds checking to work. return ref this.array[index]; } #endif /// <summary> /// Gets a value indicating whether this collection is empty. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsEmpty { [NonVersionable] get { return this.Length == 0; } } /// <summary> /// Gets the number of elements in the array. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int Length { [NonVersionable] get { // We intentionally do not check this.array != null, and throw NullReferenceException // if this is called while uninitialized. // The reason for this is perf. // Length and the indexer must be absolutely trivially implemented for the JIT optimization // of removing array bounds checking to work. return this.array.Length; } } /// <summary> /// Gets a value indicating whether this struct was initialized without an actual array instance. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsDefault { get { return this.array == null; } } /// <summary> /// Gets a value indicating whether this struct is empty or uninitialized. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsDefaultOrEmpty { get { var self = this; return self.array == null || self.array.Length == 0; } } /// <summary> /// Gets an untyped reference to the array. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] Array IImmutableArray.Array { get { return this.array; } } /// <summary> /// Gets the string to display in the debugger watches window for this instance. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { var self = this; return self.IsDefault ? "Uninitialized" : string.Format(CultureInfo.CurrentCulture, "Length = {0}", self.Length); } } /// <summary> /// Copies the contents of this array to the specified array. /// </summary> /// <param name="destination">The array to copy to.</param> [Pure] public void CopyTo(T[] destination) { var self = this; self.ThrowNullRefIfNotInitialized(); Array.Copy(self.array, 0, destination, 0, self.Length); } /// <summary> /// Copies the contents of this array to the specified array. /// </summary> /// <param name="destination">The array to copy to.</param> /// <param name="destinationIndex">The index into the destination array to which the first copied element is written.</param> [Pure] public void CopyTo(T[] destination, int destinationIndex) { var self = this; self.ThrowNullRefIfNotInitialized(); Array.Copy(self.array, 0, destination, destinationIndex, self.Length); } /// <summary> /// Copies the contents of this array to the specified array. /// </summary> /// <param name="sourceIndex">The index into this collection of the first element to copy.</param> /// <param name="destination">The array to copy to.</param> /// <param name="destinationIndex">The index into the destination array to which the first copied element is written.</param> /// <param name="length">The number of elements to copy.</param> [Pure] public void CopyTo(int sourceIndex, T[] destination, int destinationIndex, int length) { var self = this; self.ThrowNullRefIfNotInitialized(); Array.Copy(self.array, sourceIndex, destination, destinationIndex, length); } /// <summary> /// Returns a builder that is populated with the same contents as this array. /// </summary> /// <returns>The new builder.</returns> [Pure] public ImmutableArray<T>.Builder ToBuilder() { var self = this; if (self.Length == 0) { return new Builder(); // allow the builder to create itself with a reasonable default capacity } var builder = new Builder(self.Length); builder.AddRange(self); return builder; } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> [Pure] public Enumerator GetEnumerator() { var self = this; self.ThrowNullRefIfNotInitialized(); return new Enumerator(self.array); } /// <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> [Pure] public override int GetHashCode() { var self = this; return self.array == null ? 0 : self.array.GetHashCode(); } /// <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> [Pure] public override bool Equals(object obj) { IImmutableArray other = obj as IImmutableArray; if (other != null) { return this.array == other.Array; } return false; } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> [Pure] [NonVersionable] public bool Equals(ImmutableArray<T> other) { return this.array == other.array; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct based on the contents /// of an existing instance, allowing a covariant static cast to efficiently reuse the existing array. /// </summary> /// <param name="items">The array to initialize the array with. No copy is made.</param> /// <remarks> /// Covariant upcasts from this method may be reversed by calling the /// <see cref="ImmutableArray{T}.As{TOther}"/> or <see cref="ImmutableArray{T}.CastArray{TOther}"/>method. /// </remarks> [Pure] public static ImmutableArray<T> CastUp<TDerived>(ImmutableArray<TDerived> items) where TDerived : class, T { return new ImmutableArray<T>(items.array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct by casting the underlying /// array to an array of type <typeparam name="TOther"/>. /// </summary> /// <exception cref="InvalidCastException">Thrown if the cast is illegal.</exception> [Pure] public ImmutableArray<TOther> CastArray<TOther>() where TOther : class { return new ImmutableArray<TOther>((TOther[])(object)array); } /// <summary> /// Creates an immutable array for this array, cast to a different element type. /// </summary> /// <typeparam name="TOther">The type of array element to return.</typeparam> /// <returns> /// A struct typed for the base element type. If the cast fails, an instance /// is returned whose <see cref="IsDefault"/> property returns <c>true</c>. /// </returns> /// <remarks> /// Arrays of derived elements types can be cast to arrays of base element types /// without reallocating the array. /// These upcasts can be reversed via this same method, casting an array of base /// element types to their derived types. However, downcasting is only successful /// when it reverses a prior upcasting operation. /// </remarks> [Pure] public ImmutableArray<TOther> As<TOther>() where TOther : class { return new ImmutableArray<TOther>(this.array as TOther[]); } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> [Pure] IEnumerator<T> IEnumerable<T>.GetEnumerator() { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return EnumeratorObject.Create(self.array); } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> [Pure] IEnumerator IEnumerable.GetEnumerator() { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return EnumeratorObject.Create(self.array); } /// <summary> /// Throws a null reference exception if the array field is null. /// </summary> internal void ThrowNullRefIfNotInitialized() { // Force NullReferenceException if array is null by touching its Length. // This way of checking has a nice property of requiring very little code // and not having any conditions/branches. // In a faulting scenario we are relying on hardware to generate the fault. // And in the non-faulting scenario (most common) the check is virtually free since // if we are going to do anything with the array, we will need Length anyways // so touching it, and potentially causing a cache miss, is not going to be an // extra expense. var unused = this.array.Length; } /// <summary> /// Throws an <see cref="InvalidOperationException"/> if the <see cref="array"/> field is null, i.e. the /// <see cref="IsDefault"/> property returns true. The /// <see cref="InvalidOperationException"/> message specifies that the operation cannot be performed /// on a default instance of <see cref="ImmutableArray{T}"/>. /// /// This is intended for explicitly implemented interface method and property implementations. /// </summary> private void ThrowInvalidOperationIfNotInitialized() { if (this.IsDefault) { throw new InvalidOperationException(SR.InvalidOperationOnDefaultArray); } } } }
namespace Epi.Windows.MakeView.Dialogs { partial class DialogListDialog { /// <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(DialogListDialog)); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.gbxSelections = new System.Windows.Forms.GroupBox(); this.dgList = new System.Windows.Forms.DataGrid(); this.btnDelete = new System.Windows.Forms.Button(); this.btnInsert = new System.Windows.Forms.Button(); this.gbxSelections.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgList)).BeginInit(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); this.baseImageList.Images.SetKeyName(76, ""); this.baseImageList.Images.SetKeyName(77, ""); this.baseImageList.Images.SetKeyName(78, ""); this.baseImageList.Images.SetKeyName(79, ""); // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Name = "btnOK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; // // gbxSelections // resources.ApplyResources(this.gbxSelections, "gbxSelections"); this.gbxSelections.Controls.Add(this.dgList); this.gbxSelections.Controls.Add(this.btnDelete); this.gbxSelections.Controls.Add(this.btnInsert); this.gbxSelections.Name = "gbxSelections"; this.gbxSelections.TabStop = false; // // dgList // this.dgList.AlternatingBackColor = System.Drawing.Color.GhostWhite; resources.ApplyResources(this.dgList, "dgList"); this.dgList.BackColor = System.Drawing.Color.GhostWhite; this.dgList.BackgroundColor = System.Drawing.Color.Lavender; this.dgList.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dgList.CaptionBackColor = System.Drawing.Color.RoyalBlue; this.dgList.CaptionForeColor = System.Drawing.Color.White; this.dgList.CaptionVisible = false; this.dgList.DataMember = ""; this.dgList.ForeColor = System.Drawing.Color.MidnightBlue; this.dgList.GridLineColor = System.Drawing.Color.RoyalBlue; this.dgList.HeaderBackColor = System.Drawing.Color.MidnightBlue; this.dgList.HeaderFont = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.dgList.HeaderForeColor = System.Drawing.Color.Lavender; this.dgList.LinkColor = System.Drawing.Color.Teal; this.dgList.Name = "dgList"; this.dgList.ParentRowsBackColor = System.Drawing.Color.Lavender; this.dgList.ParentRowsForeColor = System.Drawing.Color.MidnightBlue; this.dgList.SelectionBackColor = System.Drawing.Color.Teal; this.dgList.SelectionForeColor = System.Drawing.Color.PaleGreen; this.dgList.MouseClick += new System.Windows.Forms.MouseEventHandler(this.dgList_MouseClick); // // btnDelete // resources.ApplyResources(this.btnDelete, "btnDelete"); this.btnDelete.Name = "btnDelete"; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // btnInsert // resources.ApplyResources(this.btnInsert, "btnInsert"); this.btnInsert.Name = "btnInsert"; this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click); // // DialogListDialog // resources.ApplyResources(this, "$this"); this.Controls.Add(this.gbxSelections); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnClear); this.Name = "DialogListDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; this.gbxSelections.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgList)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.GroupBox gbxSelections; private System.Windows.Forms.Button btnInsert; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.DataGrid dgList; } }
// 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.Reflection; 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 MaskStoreInt32() { var test = new StoreBinaryOpTest__MaskStoreInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 StoreBinaryOpTest__MaskStoreInt32 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(StoreBinaryOpTest__MaskStoreInt32 testClass) { Avx2.MaskStore((Int32*)testClass._dataTable.outArrayPtr, _fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static StoreBinaryOpTest__MaskStoreInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public StoreBinaryOpTest__MaskStoreInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreBinaryOpTest__MaskStoreInt32(); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, _fld1, _fld2); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] < 0) ? right[0] : result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < 0) ? right[i] : result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MaskStore)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
//------------------------------------------------------------------------------ // <copyright file="SingleObjectTransfer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.File; /// <summary> /// Represents a single object transfer operation. /// </summary> #if BINARY_SERIALIZATION [Serializable] #else [KnownType(typeof(AzureBlobDirectoryLocation))] [KnownType(typeof(AzureBlobLocation))] [KnownType(typeof(AzureFileDirectoryLocation))] [KnownType(typeof(AzureFileLocation))] [KnownType(typeof(DirectoryLocation))] [KnownType(typeof(FileLocation))] [KnownType(typeof(StreamLocation))] // StreamLocation intentionally omitted because it is not serializable [KnownType(typeof(UriLocation))] [DataContract] #endif // BINARY_SERIALIZATION internal class SingleObjectTransfer : Transfer { private const string TransferJobName = "TransferJob"; /// <summary> /// Internal transfer job. /// </summary> #if !BINARY_SERIALIZATION [DataMember] #endif private TransferJob transferJob; /// <summary> /// Initializes a new instance of the <see cref="SingleObjectTransfer"/> class. /// This constructor will check whether source and destination is valid for the operation: /// Uri is only valid for non-staging copy. /// cannot copy from local file/stream to local file/stream /// </summary> /// <param name="source">Transfer source.</param> /// <param name="dest">Transfer destination.</param> /// <param name="transferMethod">Transfer method, see <see cref="TransferMethod"/> for detail available methods.</param> public SingleObjectTransfer(TransferLocation source, TransferLocation dest, TransferMethod transferMethod) : base(source, dest, transferMethod) { Debug.Assert(source != null && dest != null); Debug.Assert( source.Type == TransferLocationType.FilePath || source.Type == TransferLocationType.Stream || source.Type == TransferLocationType.AzureBlob || source.Type == TransferLocationType.AzureFile || source.Type == TransferLocationType.SourceUri); Debug.Assert( dest.Type == TransferLocationType.FilePath || dest.Type == TransferLocationType.Stream || dest.Type == TransferLocationType.AzureBlob || dest.Type == TransferLocationType.AzureFile || dest.Type == TransferLocationType.SourceUri); Debug.Assert(!((source.Type == TransferLocationType.FilePath || source.Type == TransferLocationType.Stream) && (dest.Type == TransferLocationType.FilePath || dest.Type == TransferLocationType.Stream))); if (source.Type == TransferLocationType.AzureBlob && dest.Type == TransferLocationType.AzureBlob) { CloudBlob sourceBlob = (source as AzureBlobLocation).Blob; CloudBlob destBlob = (dest as AzureBlobLocation).Blob; if (sourceBlob.BlobType != destBlob.BlobType) { throw new InvalidOperationException(Resources.SourceAndDestinationBlobTypeDifferent); } if (StorageExtensions.Equals(sourceBlob, destBlob)) { throw new InvalidOperationException(Resources.SourceAndDestinationLocationCannotBeEqualException); } } if (source.Type == TransferLocationType.AzureFile && dest.Type == TransferLocationType.AzureFile) { CloudFile sourceFile = (source as AzureFileLocation).AzureFile; CloudFile destFile = (dest as AzureFileLocation).AzureFile; if (string.Equals(sourceFile.Uri.Host, destFile.Uri.Host, StringComparison.OrdinalIgnoreCase) && string.Equals(sourceFile.Uri.AbsolutePath, destFile.Uri.AbsolutePath, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(Resources.SourceAndDestinationLocationCannotBeEqualException); } } this.transferJob = new TransferJob(this); } #if !BINARY_SERIALIZATION /// <summary> /// Initializes a deserialized SingleObjectTransfer /// </summary> /// <param name="context"></param> [OnDeserialized] private void OnDeserializedCallback(StreamingContext context) { this.transferJob.Transfer = this; } #endif #if BINARY_SERIALIZATION /// <summary> /// Initializes a new instance of the <see cref="SingleObjectTransfer"/> class. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected SingleObjectTransfer(SerializationInfo info, StreamingContext context) : base(info, context) { this.transferJob = (TransferJob)info.GetValue(TransferJobName, typeof(TransferJob)); this.transferJob.Transfer = this; } #endif // BINARY_SERIALIZATION /// <summary> /// Initializes a new instance of the <see cref="SingleObjectTransfer"/> class. /// </summary> /// <param name="other">Another <see cref="SingleObjectTransfer"/> object. </param> private SingleObjectTransfer(SingleObjectTransfer other) : base(other) { this.ProgressTracker = other.ProgressTracker.Copy(); this.transferJob = other.transferJob.Copy(); this.transferJob.Transfer = this; } #if BINARY_SERIALIZATION /// <summary> /// Serializes the object. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(TransferJobName, this.transferJob, typeof(TransferJob)); } #endif // BINARY_SERIALIZATION /// <summary> /// Creates a copy of current transfer object. /// </summary> /// <returns>A copy of current transfer object.</returns> public override Transfer Copy() { return new SingleObjectTransfer(this); } public void UpdateProgressLock(ReaderWriterLockSlim uploadLock) { this.transferJob.ProgressUpdateLock = uploadLock; } /// <summary> /// Execute the transfer asynchronously. /// </summary> /// <param name="scheduler">Transfer scheduler</param> /// <param name="cancellationToken">Token that can be used to cancel the transfer.</param> /// <returns>A task representing the transfer operation.</returns> public override async Task ExecuteAsync(TransferScheduler scheduler, CancellationToken cancellationToken) { if (this.transferJob.Status == TransferJobStatus.Finished || this.transferJob.Status == TransferJobStatus.Skipped) { return; } TransferEventArgs eventArgs = new TransferEventArgs(this.Source.Instance, this.Destination.Instance); eventArgs.StartTime = DateTime.UtcNow; if (this.transferJob.Status == TransferJobStatus.Failed) { // Resuming a failed transfer job if (string.IsNullOrEmpty(this.transferJob.CopyId)) { this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Transfer); } else { this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Monitor); } } try { await scheduler.ExecuteJobAsync(this.transferJob, cancellationToken); this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Finished); eventArgs.EndTime = DateTime.UtcNow; if (this.Context != null) { this.Context.OnTransferSuccess(eventArgs); } } catch (TransferException exception) { eventArgs.EndTime = DateTime.UtcNow; eventArgs.Exception = exception; if (exception.ErrorCode == TransferErrorCode.NotOverwriteExistingDestination) { // transfer skipped this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Skipped); if (this.Context != null) { this.Context.OnTransferSkipped(eventArgs); } throw; } else { this.OnTransferFailed(eventArgs); throw; } } catch (Exception ex) { eventArgs.EndTime = DateTime.UtcNow; eventArgs.Exception = ex; this.OnTransferFailed(eventArgs); throw; } this.Journal?.RemoveTransfer(this); } public void OnTransferFailed(Exception ex) { TransferEventArgs eventArgs = new TransferEventArgs(this.Source.Instance, this.Destination.Instance); eventArgs.StartTime = DateTime.UtcNow; eventArgs.EndTime = DateTime.UtcNow; eventArgs.Exception = ex; this.OnTransferFailed(eventArgs); } private void OnTransferFailed(TransferEventArgs eventArgs) { // transfer failed this.UpdateTransferJobStatus(this.transferJob, TransferJobStatus.Failed); if (this.Context != null) { this.Context.OnTransferFailed(eventArgs); } } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace Gearset.Components { /// <summary> /// This is a game component that implements IUpdateable. /// </summary> public class MouseComponent : Gear { MouseState state; MouseState prevState; /// <summary> /// Can last only one frame true /// </summary> private bool justClicked; /// <summary> /// Can last only one frame true /// </summary> private bool justDragging; /// <summary> /// Remains true while the left mouse button is pressed. /// </summary> private bool mouseDown; /// <summary> /// How long the mouse was down. /// </summary> private int mouseDownTime; /// <summary> /// The position where the left button became pressed. /// </summary> private Vector2 mouseDownPosition; private bool dragging; public Vector2 Position { get { return new Vector2(state.X, state.Y); } } private bool HaveFocus { get { return Game.IsActive; } } /// <summary> /// The distance the (down left) mouse can move without being /// considered a drag (still a click). Should be zero for PC /// games and some higher value for tablets. /// </summary> public float ClickThreshold { get; set; } /// <summary> /// Set to true if the component should force the mouse to /// stay inside the client logger bounds. /// </summary> public bool KeepMouseInWindow { get; set; } /// <summary> /// Get the movement the mouse have made since it started dragging. /// If the mouse is not dragging it will return Vector2.Zero. /// </summary> public Vector2 DragOffset { get { if (dragging) return Position - mouseDownPosition; else return Vector2.Zero; } } #region Constructor public MouseComponent() : base(new GearConfig()) { state = Mouse.GetState(); } #endregion #region Update public override void Update(GameTime gameTime) { prevState = state; state = Mouse.GetState(); justClicked = false; justDragging = false; if (mouseDown) { if (Vector2.Distance(Position, mouseDownPosition) > ClickThreshold && !dragging) { justDragging = true; dragging = true; } mouseDownTime += gameTime.ElapsedGameTime.Milliseconds; } if (IsLeftJustUp()) { if (!dragging) justClicked = true; dragging = false; mouseDown = false; } if (IsLeftJustDown()) { mouseDownPosition = Position; mouseDown = true; mouseDownTime = 0; } // Keep the mouse inside if (KeepMouseInWindow) { #if WINDOWS Rectangle rect = Game.Window.ClientBounds; // Rectangle to clip (in screen coordinates) System.Windows.Forms.Cursor.Clip = new System.Drawing.Rectangle(rect.X, rect.Y, rect.Width, rect.Height); #endif } else { #if WINDOWS System.Windows.Forms.Cursor.Clip = new System.Drawing.Rectangle(int.MinValue / 2, int.MinValue / 2, int.MaxValue, int.MaxValue); #endif } base.Update(gameTime); } #endregion #region Is Left Just Up/Down/Click /// <summary> /// True if the mouse was just pressed, last one frame true. /// </summary> public bool IsLeftJustDown() { return (state.LeftButton == ButtonState.Pressed && prevState.LeftButton == ButtonState.Released && HaveFocus); } /// <summary> /// True if the mouse was just released, last one frame true. /// </summary> public bool IsLeftJustUp() { return (state.LeftButton == ButtonState.Released && prevState.LeftButton == ButtonState.Pressed && HaveFocus); } /// <summary> /// True if mouse did a released-pressed-released cycle /// without moving the ClickThreshold. /// </summary> public bool IsLeftClick() { return justClicked && HaveFocus; } #endregion #region Is Right Just Up/Down/Click /// <summary> /// True if the mouse was just pressed, last one frame true. /// </summary> public bool IsRightJustDown() { return (state.RightButton == ButtonState.Pressed && prevState.RightButton == ButtonState.Released && HaveFocus); } /// <summary> /// True if the mouse was just released, last one frame true. /// </summary> public bool IsRightJustUp() { return (state.RightButton == ButtonState.Released && prevState.RightButton == ButtonState.Pressed && HaveFocus); } #endregion #region Dragging /// <summary> /// The mouse mave moved the ClickThreshold since it was pressed. /// </summary> /// <returns></returns> public bool IsDragging() { return dragging && HaveFocus; } /// <summary> /// The mouse just moved the threshold, this will only be true /// for one frame. /// </summary> public bool IsJustDragging() { return justDragging && HaveFocus; } #endregion } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Compatibility { /// <summary> /// MenuItem. /// </summary> public class MenuItem : IMenuItem { #region Fields private readonly ToolStripMenuItem _menuItem; #endregion /// <summary> /// Initializes a new instance of the <see cref="MenuItem"/> class. /// </summary> /// <param name="inMenuItem">The ToolStripMenuItem to wrap with this item.</param> public MenuItem(ToolStripMenuItem inMenuItem) { _menuItem = inMenuItem; } #region Properties /// <summary> /// Gets or sets a value indicating whether or not this item should draw a dividing line between itself and any /// items before this item. /// </summary> public bool BeginsGroup { get { return PreviousItemIsSeparator; } set { if (value) { if (PreviousItemIsSeparator == false) { InsertSeparator(); } } else { if (PreviousItemIsSeparator) { ToolStripMenuItem tm = _menuItem.OwnerItem as ToolStripMenuItem; if (tm != null) { tm.DropDownItems.Remove(PreviousItem); } else { _menuItem.Owner?.Items.Remove(PreviousItem); } } } } } /// <summary> /// Gets or sets the category for this item (used when the user customizes the menu). /// </summary> public string Category { get; set; } /// <summary> /// Gets or sets a value indicating whether the item is checked. /// </summary> public bool Checked { get { return _menuItem.Checked; } set { _menuItem.Checked = value; } } /// <summary> /// Gets or sets the cursor used when the mouse is over this control. /// </summary> public Cursor Cursor { get { return _menuItem.Owner.Cursor; } set { _menuItem.Owner.Cursor = value; } } /// <summary> /// Gets or sets the description of this menu item, used in customization of menu by the user. /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets a value indicating whether the item is displayed. /// ... Side Note /// ... I have no idea what this is supposed to do, so it is redundant with visible for now /// and possibly should be made obsolete. /// </summary> public bool Displayed { get { return _menuItem.Visible; } set { _menuItem.Visible = value; } } /// <summary> /// Gets or sets a value indicating whether the item is enabled. /// </summary> public bool Enabled { get { return _menuItem.Enabled; } set { _menuItem.Enabled = value; } } /// <summary> /// Gets a value indicating whether this menu item is the first visible submenu item. /// This is only valid in submenus, i.e. menus which have a parent. /// </summary> public bool IsFirstVisibleSubmenuItem { get { ToolStripMenuItem parent = _menuItem.OwnerItem as ToolStripMenuItem; if (parent != null) { foreach (ToolStripItem tsi in parent.DropDownItems) { if (tsi == _menuItem) return true; if (tsi.Visible) return false; } } ToolStrip cont = _menuItem.Owner; foreach (ToolStripItem tsi in cont.Items) { if (tsi == _menuItem) return true; if (tsi.Visible) return false; } return true; } } /// <summary> /// Gets the Name of this item. /// </summary> public string Name => _menuItem.Name; /// <summary> /// Gets the count of the submenu items contained within this item. /// </summary> public int NumSubItems => _menuItem.DropDownItems.Count; /// <summary> /// Gets or sets the icon for the menu item. /// </summary> public Image Picture { get { return _menuItem.Image; } set { _menuItem.Image = value; } } /// <summary> /// Gets or sets the Text shown for the MenuItem. /// </summary> public string Text { get { return _menuItem.Text; } set { _menuItem.Text = value; } } /// <summary> /// Gets or sets the tool tip text that will pop up for the item when a mouse over event occurs. /// </summary> public string Tooltip { get { return _menuItem.ToolTipText; } set { _menuItem.ToolTipText = value; } } /// <summary> /// Gets or sets a value indicating whether the item is visible. /// </summary> public bool Visible { get { return _menuItem.Visible; } set { _menuItem.Visible = value; } } private ToolStripItem PreviousItem { get { int indx; ToolStripMenuItem parent = _menuItem.OwnerItem as ToolStripMenuItem; if (parent != null) { indx = parent.DropDownItems.IndexOf(_menuItem) - 1; if (indx > -1) { return parent.DropDownItems[indx]; } } ToolStrip cont = _menuItem.Owner; indx = cont.Items.IndexOf(_menuItem) - 1; if (indx > -1) { return cont.Items[indx]; } return null; } } private bool PreviousItemIsSeparator { get { ToolStripSeparator ts = PreviousItem as ToolStripSeparator; if (ts != null) return true; return false; } } #endregion #region Methods /// <summary> /// Gets a submenu item by its 0-based index. /// </summary> /// <param name="index">Index of the item that should be returned.</param> /// <returns>The MenuItem with the given index.</returns> public IMenuItem SubItem(int index) { return new MenuItem(_menuItem.DropDownItems[index] as ToolStripMenuItem); } /// <summary> /// Gets a submenu item by its string name. /// </summary> /// <param name="name">Name of the item that should be returned.</param> /// <returns>The MenuItem with the given name.</returns> public IMenuItem SubItem(string name) { return new MenuItem(_menuItem.DropDownItems[name] as ToolStripMenuItem); } private void InsertSeparator() { int indx; ToolStripMenuItem parent = _menuItem.OwnerItem as ToolStripMenuItem; if (parent != null) { indx = parent.DropDownItems.IndexOf(_menuItem); parent.DropDownItems.Insert(indx, new ToolStripSeparator()); } ToolStrip cont = _menuItem.Owner; indx = cont.Items.IndexOf(_menuItem); cont.Items.Insert(indx, new ToolStripSeparator()); } #endregion } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.Util; namespace Encog.MathUtil { /// <summary> /// A complex number class. This class is based on source code by /// /// Andrew G. Bennett, Department of Mathematics /// Kansas State University /// /// The original version can be found here: /// /// http://www.math.ksu.edu/~bennett/jomacg/c.html /// /// </summary> public class ComplexNumber { /// <summary> /// The real part. /// </summary> private readonly double _x; /// <summary> /// The imaginary part. /// </summary> private readonly double _y; /// <summary> /// Constructs the complex number z = u + i*v /// </summary> /// <param name="u">Real part</param> /// <param name="v">Imaginary part</param> public ComplexNumber(double u, double v) { _x = u; _y = v; } /// <summary> /// Create a complex number from another complex number. /// </summary> /// <param name="other">The other complex number. </param> public ComplexNumber(ComplexNumber other) { _x = other.Real; _y = other.Imaginary; } /** */ /// <summary> /// Real part of this Complex number /// (the x-coordinate in rectangular coordinates). /// </summary> public double Real { get { return _x; } } /// <summary> /// Imaginary part of this Complex number /// </summary> public double Imaginary { get { return _y; } } /** @return */ /// <summary> /// Modulus of this Complex number /// (the distance from the origin in polar coordinates). /// </summary> /// <returns>|z| where z is this Complex number.</returns> public double Mod() { if (_x != 0 || _y != 0) { return Math.Sqrt(_x*_x + _y*_y); } return 0d; } /// <summary> /// Argument of this Complex number /// (the angle in radians with the x-axis in polar coordinates). /// </summary> /// <returns>arg(z) where z is this Complex number.</returns> public double Arg() { return Math.Atan2(_y, _x); } /// <summary> /// Complex conjugate of this Complex number /// (the conjugate of x+i*y is x-i*y). /// </summary> /// <returns>z-bar where z is this Complex number.</returns> public ComplexNumber Conj() { return new ComplexNumber(_x, -_y); } /// <summary> /// Addition of Complex numbers (doesn't change this Complex number). /// (x+i*y) + (s+i*t) = (x+s)+i*(y+t) /// </summary> /// <param name="c1">The first argument.</param> /// <param name="c2">The second argument.</param> /// <returns>The result of the addition.</returns> public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2) { return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); } /// <summary> /// Subtraction of Complex numbers. /// (x-i*y) + (s-i*t) = (x-s)+i*(y-t) /// </summary> /// <param name="c1">The first argument.</param> /// <param name="c2">The second argument.</param> /// <returns>The result of the addition.</returns> public static ComplexNumber operator -(ComplexNumber c1, ComplexNumber c2) { return new ComplexNumber(c1.Real - c2.Real, c1.Imaginary - c2.Imaginary); } /// <summary> /// Multiplication of Complex numbers. /// </summary> /// <param name="c1">The first argument.</param> /// <param name="c2">The second argument.</param> /// <returns>The result of the addition.</returns> public static ComplexNumber operator *(ComplexNumber c1, ComplexNumber c2) { return new ComplexNumber(c1.Real*c2.Real - c1.Imaginary*c2.Imaginary, c1.Real*c2.Imaginary + c1.Imaginary *c2.Real); } /// <summary> /// Division of Complex numbers. /// </summary> /// <param name="c1">The first argument.</param> /// <param name="c2">The second argument.</param> /// <returns>The result of the addition.</returns> public static ComplexNumber operator /(ComplexNumber c1, ComplexNumber c2) { var mod = c2.Mod(); double den = mod * mod; return new ComplexNumber((c1.Real*c2.Real + c1.Imaginary *c2.Imaginary)/den, (c1.Imaginary *c2.Real - c1.Real*c2.Imaginary)/den); } /// <summary> /// Complex exponential (doesn't change this Complex number). /// </summary> /// <returns>exp(z) where z is this Complex number.</returns> public ComplexNumber Exp() { return new ComplexNumber(Math.Exp(_x)*Math.Cos(_y), Math.Exp(_x) *Math.Sin(_y)); } /// <summary> /// Principal branch of the Complex logarithm of this Complex number. /// (doesn't change this Complex number). /// The principal branch is the branch with -pi less arg les-equals pi. /// </summary> /// <returns>log(z) where z is this Complex number.</returns> public ComplexNumber Log() { return new ComplexNumber(Math.Log(Mod()), Arg()); } /// <summary> /// Complex square root (doesn't change this complex number). /// Computes the principal branch of the square root, which /// is the value with 0 less equals arg less pi. /// </summary> /// <returns>sqrt(z) where z is this Complex number.</returns> public ComplexNumber Sqrt() { double r = Math.Sqrt(Mod()); double theta = Arg()/2; return new ComplexNumber(r*Math.Cos(theta), r*Math.Sin(theta)); } /// <summary> /// Real cosh function (used to compute complex trig functions). /// </summary> /// <param name="theta">The argument.</param> /// <returns>The result.</returns> private static double Cosh(double theta) { return (Math.Exp(theta) + Math.Exp(-theta))/2; } /// <summary> /// Real sinh function (used to compute complex trig functions). /// </summary> /// <param name="theta">The argument.</param> /// <returns>The result.</returns> private static double Sinh(double theta) { return (Math.Exp(theta) - Math.Exp(-theta))/2; } /// <summary> /// Sine of this Complex number (doesn't change this Complex number). /// sin(z) = (exp(i*z)-exp(-i*z))/(2*i). /// </summary> /// <returns>sin(z) where z is this Complex number.</returns> public ComplexNumber Sin() { return new ComplexNumber(Cosh(_y)*Math.Sin(_x), Sinh(_y)*Math.Cos(_x)); } /// <summary> /// Cosine of this Complex number (doesn't change this Complex number). /// cos(z) = (exp(i*z)+exp(-i*z))/ 2. /// </summary> /// <returns>cos(z) where z is this Complex number.</returns> public ComplexNumber Cos() { return new ComplexNumber(Cosh(_y)*Math.Cos(_x), -Sinh(_y)*Math.Sin(_x)); } /// <summary> /// Hyperbolic sine of this Complex number /// (doesn't change this Complex number). /// sinh(z) = (exp(z)-exp(-z))/2. /// </summary> /// <returns>sinh(z) where z is this Complex number.</returns> public ComplexNumber Sinh() { return new ComplexNumber(Sinh(_x)*Math.Cos(_y), Cosh(_x)*Math.Sin(_y)); } /// <summary> /// Hyperbolic cosine of this Complex number /// (doesn't change this Complex number). /// cosh(z) = (exp(z) + exp(-z)) / 2. /// </summary> /// <returns>cosh(z) where z is this Complex number.</returns> public ComplexNumber Cosh() { return new ComplexNumber(Cosh(_x)*Math.Cos(_y), Sinh(_x)*Math.Sin(_y)); } /// <summary> /// Tangent of this Complex number (doesn't change this Complex number). /// </summary> /// <returns>tan(z) = sin(z)/cos(z).</returns> public ComplexNumber Tan() { return (Sin())/(Cos()); } /// <summary> /// Negative of this complex number (chs stands for change sign). /// This produces a new Complex number and doesn't change /// this Complex number. /// -(x+i*y) = -x-i*y. /// </summary> /// <param name="op"></param> /// <returns>-op where op is this Complex number.</returns> public static ComplexNumber operator -(ComplexNumber op) { return new ComplexNumber(-op.Real, -op.Imaginary); } /// <inheritdoc/> public new String ToString() { if (_x != 0 && _y > 0) { return _x + " + " + _y + "i"; } if (_x != 0 && _y < 0) { return _x + " - " + (-_y) + "i"; } if (_y == 0) { return Format.FormatDouble(_x, 4); } if (_x == 0) { return _y + "i"; } // shouldn't get here (unless Inf or NaN) return _x + " + i*" + _y; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// An optician's store. /// </summary> public class Optician_Core : TypeCore, IMedicalOrganization { public Optician_Core() { this._TypeId = 192; this._Id = "Optician"; this._Schema_Org_Url = "http://schema.org/Optician"; string label = ""; GetLabel(out label, "Optician", typeof(Optician_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,163}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{163}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Bcpg { /** * Basic output stream. */ public class ArmoredOutputStream : BaseOutputStream { private static readonly byte[] encodingTable = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** * encode the input data producing a base 64 encoded byte array. */ private static void Encode( Stream outStream, int[] data, int len) { Debug.Assert(len > 0); Debug.Assert(len < 4); byte[] bs = new byte[4]; int d1 = data[0]; bs[0] = encodingTable[(d1 >> 2) & 0x3f]; switch (len) { case 1: { bs[1] = encodingTable[(d1 << 4) & 0x3f]; bs[2] = (byte)'='; bs[3] = (byte)'='; break; } case 2: { int d2 = data[1]; bs[1] = encodingTable[((d1 << 4) | (d2 >> 4)) & 0x3f]; bs[2] = encodingTable[(d2 << 2) & 0x3f]; bs[3] = (byte)'='; break; } case 3: { int d2 = data[1]; int d3 = data[2]; bs[1] = encodingTable[((d1 << 4) | (d2 >> 4)) & 0x3f]; bs[2] = encodingTable[((d2 << 2) | (d3 >> 6)) & 0x3f]; bs[3] = encodingTable[d3 & 0x3f]; break; } } outStream.Write(bs, 0, bs.Length); } private readonly Stream outStream; private int[] buf = new int[3]; private int bufPtr = 0; private Crc24 crc = new Crc24(); private int chunkCount = 0; private int lastb; private bool start = true; private bool clearText = false; private bool newLine = false; private string type; private static readonly string nl = Platform.NewLine; private static readonly string headerStart = "-----BEGIN PGP "; private static readonly string headerTail = "-----"; private static readonly string footerStart = "-----END PGP "; private static readonly string footerTail = "-----"; private static readonly string version = "BCPG C# v" + Assembly.GetExecutingAssembly().GetName().Version; private readonly IDictionary headers; public ArmoredOutputStream(Stream outStream) { this.outStream = outStream; this.headers = Platform.CreateHashtable(); this.headers["Version"] = version; } public ArmoredOutputStream(Stream outStream, IDictionary headers) { this.outStream = outStream; this.headers = Platform.CreateHashtable(headers); this.headers["Version"] = version; } /** * Set an additional header entry. * * @param name the name of the header entry. * @param v the value of the header entry. */ public void SetHeader( string name, string v) { headers[name] = v; } /** * Reset the headers to only contain a Version string. */ public void ResetHeaders() { headers.Clear(); headers["Version"] = version; } /** * Start a clear text signed message. * @param hashAlgorithm */ public void BeginClearText( HashAlgorithmTag hashAlgorithm) { string hash; switch (hashAlgorithm) { case HashAlgorithmTag.Sha1: hash = "SHA1"; break; case HashAlgorithmTag.Sha256: hash = "SHA256"; break; case HashAlgorithmTag.Sha384: hash = "SHA384"; break; case HashAlgorithmTag.Sha512: hash = "SHA512"; break; case HashAlgorithmTag.MD2: hash = "MD2"; break; case HashAlgorithmTag.MD5: hash = "MD5"; break; case HashAlgorithmTag.RipeMD160: hash = "RIPEMD160"; break; default: throw new IOException("unknown hash algorithm tag in beginClearText: " + hashAlgorithm); } DoWrite("-----BEGIN PGP SIGNED MESSAGE-----" + nl); DoWrite("Hash: " + hash + nl + nl); clearText = true; newLine = true; lastb = 0; } public void EndClearText() { clearText = false; } public override void WriteByte( byte b) { if (clearText) { outStream.WriteByte(b); if (newLine) { if (!(b == '\n' && lastb == '\r')) { newLine = false; } if (b == '-') { outStream.WriteByte((byte)' '); outStream.WriteByte((byte)'-'); // dash escape } } if (b == '\r' || (b == '\n' && lastb != '\r')) { newLine = true; } lastb = b; return; } if (start) { bool newPacket = (b & 0x40) != 0; int tag; if (newPacket) { tag = b & 0x3f; } else { tag = (b & 0x3f) >> 2; } switch ((PacketTag)tag) { case PacketTag.PublicKey: type = "PUBLIC KEY BLOCK"; break; case PacketTag.SecretKey: type = "PRIVATE KEY BLOCK"; break; case PacketTag.Signature: type = "SIGNATURE"; break; default: type = "MESSAGE"; break; } DoWrite(headerStart + type + headerTail + nl); // Eddington - Disable Version //WriteHeaderEntry("Version", (string) headers["Version"]); foreach (DictionaryEntry de in headers) { string k = (string) de.Key; if (k != "Version") { string v = (string) de.Value; WriteHeaderEntry(k, v); } } DoWrite(nl); start = false; } if (bufPtr == 3) { Encode(outStream, buf, bufPtr); bufPtr = 0; if ((++chunkCount & 0xf) == 0) { DoWrite(nl); } } crc.Update(b); buf[bufPtr++] = b & 0xff; } /** * <b>Note</b>: close does nor close the underlying stream. So it is possible to write * multiple objects using armoring to a single stream. */ public override void Close() { if (type != null) { if (bufPtr > 0) { Encode(outStream, buf, bufPtr); } DoWrite(nl + '='); int crcV = crc.Value; buf[0] = ((crcV >> 16) & 0xff); buf[1] = ((crcV >> 8) & 0xff); buf[2] = (crcV & 0xff); Encode(outStream, buf, 3); DoWrite(nl); DoWrite(footerStart); DoWrite(type); DoWrite(footerTail); DoWrite(nl); outStream.Flush(); type = null; start = true; base.Close(); } } private void WriteHeaderEntry( string name, string v) { DoWrite(name + ": " + v + nl); } private void DoWrite( string s) { byte[] bs = Strings.ToAsciiByteArray(s); outStream.Write(bs, 0, bs.Length); } } }
using System; using Cocos2D; using Random = Cocos2D.CCRandom; namespace tests.Extensions { class CCControlButtonTest_HelloVariableSize : CCControlScene { public override bool Init() { if (base.Init()) { CCSize screenSize = CCDirector.SharedDirector.WinSize; // Defines an array of title to create buttons dynamically var stringArray = new[] { "Hello", "Variable", "Size", "!" }; CCNode layer = new CCNode (); AddChild(layer, 1); float total_width = 0, height = 0; // For each title in the array object pObj = null; int i = 0; foreach(var title in stringArray) { // Creates a button with this string as title var button = standardButtonWithTitle(title); if (i == 0) { button.Opacity = 50; button.Color = new CCColor3B(0, 255, 0); } else if (i == 1) { button.Opacity = 200; button.Color = new CCColor3B(0, 255, 0); } else if (i == 2) { button.Opacity = 100; button.Color = new CCColor3B(0, 0, 255); } button.Position = new CCPoint (total_width + button.ContentSize.Width / 2, button.ContentSize.Height / 2); layer.AddChild(button); // Compute the size of the layer height = button.ContentSize.Height; total_width += button.ContentSize.Width; i++; } layer.AnchorPoint = new CCPoint(0.5f, 0.5f); layer.ContentSize = new CCSize(total_width, height); layer.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); // Add the black background var background = new CCScale9SpriteFile("extensions/buttonBackground"); background.ContentSize = new CCSize(total_width + 14, height + 14); background.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(background); return true; } return false; } /** Creates and return a button with a default background and title color. */ public CCControlButton standardButtonWithTitle(string title) { /** Creates and return a button with a default background and title color. */ var backgroundButton = new CCScale9SpriteFile("extensions/button"); var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); var titleButton = new CCLabelTTF(title, "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var button = new CCControlButton(titleButton, backgroundButton); button.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); button.SetTitleColorForState(CCTypes.CCWhite, CCControlState.Highlighted); return button; } public new static CCScene sceneWithTitle(string title) { var pScene = new CCScene(); var controlLayer = new CCControlButtonTest_HelloVariableSize(); controlLayer.getSceneTitleLabel().Text = (title); pScene.AddChild(controlLayer); return pScene; } } class CCControlButtonTest_Inset : CCControlScene { public override bool Init() { if (base.Init()) { CCSize screenSize = CCDirector.SharedDirector.WinSize; // Defines an array of title to create buttons dynamically var stringArray = new[] { "Inset", "Inset", "Inset" }; CCNode layer = new CCNode (); AddChild(layer, 1); float total_width = 0, height = 0; // For each title in the array object pObj = null; foreach (var title in stringArray) { // Creates a button with this string as title CCControlButton button = insetButtonWithTitle(title, new CCRect(5, 5, 5, 5)); button.Position = new CCPoint(total_width + button.ContentSize.Width / 2, button.ContentSize.Height / 2); layer.AddChild(button); // Compute the size of the layer height = button.ContentSize.Height; total_width += button.ContentSize.Width; } layer.AnchorPoint = new CCPoint(0.5f, 0.5f); layer.ContentSize = new CCSize(total_width, height); layer.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); // Add the black background var background = new CCScale9SpriteFile("extensions/buttonBackground"); background.ContentSize = new CCSize(total_width + 14, height + 14); background.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(background); return true; } return false; } /** Creates and return a button with a default background and title color. */ public CCControlButton standardButtonWithTitle(string title) { /** Creates and return a button with a default background and title color. */ var backgroundButton = new CCScale9SpriteFile("extensions/button"); var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); var titleButton = new CCLabelTTF(title, "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var button = new CCControlButton(titleButton, backgroundButton); button.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); button.SetTitleColorForState(CCTypes.CCWhite, CCControlState.Highlighted); return button; } public CCControlButton insetButtonWithTitle(string title, CCRect inset) { /** Creates and return a button with a default background and title color. */ var backgroundButton = new CCScale9SpriteFile("extensions/button"); var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); backgroundButton.CapInsets = inset; backgroundHighlightedButton.CapInsets = inset; var titleButton = new CCLabelTTF(title, "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var button = new CCControlButton(titleButton, backgroundButton); button.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); button.SetTitleColorForState(CCTypes.CCWhite, CCControlState.Highlighted); return button; } public new static CCScene sceneWithTitle(string title) { var pScene = new CCScene(); var controlLayer = new CCControlButtonTest_Inset(); controlLayer.getSceneTitleLabel().Text = (title); pScene.AddChild(controlLayer); return pScene; } } class CCControlButtonTest_Event : CCControlScene { public override bool Init() { if (base.Init()) { CCSize screenSize = CCDirector.SharedDirector.WinSize; // Add a label in which the button events will be displayed setDisplayValueLabel(new CCLabelTTF("No Event", "Arial", 32)); m_pDisplayValueLabel.AnchorPoint = new CCPoint(0.5f, -1); m_pDisplayValueLabel.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(m_pDisplayValueLabel, 1); // Add the button var backgroundButton = new CCScale9SpriteFile("extensions/button"); var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); var titleButton = new CCLabelTTF("Touch Me!", "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var controlButton = new CCControlButton(titleButton, backgroundButton); controlButton.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); controlButton.SetTitleColorForState(CCTypes.CCWhite, CCControlState.Highlighted); controlButton.AnchorPoint = new CCPoint(0.5f, 1); controlButton.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(controlButton, 1); // Add the black background var background = new CCScale9SpriteFile("extensions/buttonBackground"); background.ContentSize = new CCSize(300, 170); background.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(background); // Sets up event handlers controlButton.AddTargetWithActionForControlEvent(this, touchDownAction, CCControlEvent.TouchDown); controlButton.AddTargetWithActionForControlEvent(this, touchDragInsideAction, CCControlEvent.TouchDragInside); controlButton.AddTargetWithActionForControlEvent(this, touchDragOutsideAction, CCControlEvent.TouchDragOutside); controlButton.AddTargetWithActionForControlEvent(this, touchDragEnterAction, CCControlEvent.TouchDragEnter); controlButton.AddTargetWithActionForControlEvent(this, touchDragExitAction, CCControlEvent.TouchDragExit); controlButton.AddTargetWithActionForControlEvent(this, touchUpInsideAction, CCControlEvent.TouchUpInside); controlButton.AddTargetWithActionForControlEvent(this, touchUpOutsideAction, CCControlEvent.TouchUpOutside); controlButton.AddTargetWithActionForControlEvent(this, touchCancelAction, CCControlEvent.TouchCancel); return true; } return false; } public void touchDownAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Touch Down"); } public void touchDragInsideAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Drag Inside"); } public void touchDragOutsideAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Drag Outside"); } public void touchDragEnterAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Drag Enter"); } public void touchDragExitAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Drag Exit"); } public void touchUpInsideAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Touch Up Inside."); } public void touchUpOutsideAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Touch Up Outside."); } public void touchCancelAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Touch Cancel"); } private CCLabelTTF m_pDisplayValueLabel; public virtual CCLabelTTF getDisplayValueLabel() { return m_pDisplayValueLabel; } public virtual void setDisplayValueLabel(CCLabelTTF var) { if (m_pDisplayValueLabel != var) { m_pDisplayValueLabel = var; } } public new static CCScene sceneWithTitle(string title) { var pScene = new CCScene(); var controlLayer = new CCControlButtonTest_Event(); if (controlLayer != null) { controlLayer.getSceneTitleLabel().Text = (title); pScene.AddChild(controlLayer); } return pScene; } } class CCControlButtonTest_Styling : CCControlScene { public override bool Init() { if (base.Init()) { CCSize screenSize = CCDirector.SharedDirector.WinSize; var layer = new CCNode (); AddChild(layer, 1); int space = 10; // px float max_w = 0, max_h = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // Add the buttons var button = standardButtonWithTitle(CCRandom.Next(30).ToString()); button.SetAdjustBackgroundImage(false); // Tells the button that the background image must not be adjust // It'll use the prefered size of the background image button.Position = new CCPoint(button.ContentSize.Width / 2 + (button.ContentSize.Width + space) * i, button.ContentSize.Height / 2 + (button.ContentSize.Height + space) * j); layer.AddChild(button); max_w = Math.Max(button.ContentSize.Width * (i + 1) + space * i, max_w); max_h = Math.Max(button.ContentSize.Height * (j + 1) + space * j, max_h); } } layer.AnchorPoint = new CCPoint (0.5f, 0.5f); layer.ContentSize = new CCSize(max_w, max_h); layer.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); // Add the black background var backgroundButton = new CCScale9SpriteFile("extensions/buttonBackground"); backgroundButton.ContentSize = new CCSize(max_w + 14, max_h + 14); backgroundButton.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(backgroundButton); return true; } return false; } public CCControlButton standardButtonWithTitle(string title) { /** Creates and return a button with a default background and title color. */ var backgroundButton = new CCScale9SpriteFile("extensions/button"); backgroundButton.PreferredSize = new CCSize(55, 55); // Set the prefered size var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); backgroundHighlightedButton.PreferredSize = new CCSize(55, 55); // Set the prefered size var titleButton = new CCLabelTTF(title, "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var button = new CCControlButton(titleButton, backgroundButton); button.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); button.SetTitleColorForState(CCTypes.CCWhite, CCControlState.Highlighted); return button; } public new static CCScene sceneWithTitle(string title) { var pScene = new CCScene(); var controlLayer = new CCControlButtonTest_Styling(); if (controlLayer != null) { controlLayer.getSceneTitleLabel().Text = (title); pScene.AddChild(controlLayer); } return pScene; } } }
using System; using System.Linq.Expressions; using System.Web.Mvc; namespace MvcContrib.TestHelper { /// <summary> /// Contains extension methods for testing action results. /// </summary> public static class ActionResultHelper { /// <summary> /// Asserts that the ActionResult is of the specified type. /// </summary> /// <typeparam name="T">Type of action result to convert to.</typeparam> /// <param name="result">Action Result to convert.</param> /// <returns></returns> public static T AssertResultIs<T>(this ActionResult result) where T : ActionResult { var converted = result as T; if(converted == null) { throw new ActionResultAssertionException(string.Format("Expected result to be of type {0}. It is actually of type {1}.", typeof(T).Name, result.GetType().Name)); } return converted; } /// <summary> /// Asserts that the action result is a RenderViewResult. /// </summary> /// <param name="result">The result to convert.</param> /// <returns></returns> public static ViewResult AssertViewRendered(this ActionResult result) { return result.AssertResultIs<ViewResult>(); } /// <summary> /// Asserts that the action result is a RenderPartialViewResult /// </summary> /// <param name="result">The result to convert</param> /// <returns></returns> public static PartialViewResult AssertPartialViewRendered(this ActionResult result) { return result.AssertResultIs<PartialViewResult>(); } /// <summary> /// Asserts that the action result is a HttpRedirectResult. /// </summary> /// <param name="result">The result to convert.</param> /// <returns></returns> public static RedirectResult AssertHttpRedirect(this ActionResult result) { return result.AssertResultIs<RedirectResult>(); } /// <summary> /// Asserts that the action result is an ActionRedirectResult. /// </summary> /// <param name="result">The result to convert.</param> /// <returns></returns> public static RedirectToRouteResult AssertActionRedirect(this ActionResult result) { return result.AssertResultIs<RedirectToRouteResult>(); } /// <summary> /// Asserts that an ActionRedirectResult is for the specified controller. /// </summary> /// <param name="result">The result to check.</param> /// <param name="controller">The name of the controller.</param> /// <returns></returns> public static RedirectToRouteResult ToController(this RedirectToRouteResult result, string controller) { return result.WithParameter("controller", controller); } /// <summary> /// Asserts that an ActionRedirectReslt is for the specified action. /// </summary> /// <param name="result">The result to check.</param> /// <param name="action">The name of the action.</param> /// <returns></returns> public static RedirectToRouteResult ToAction(this RedirectToRouteResult result, string action) { return result.WithParameter("action", action); } /// <summary> /// Asserts that an ActionRedirectResult is for the specified action on the specified controller /// </summary> /// <typeparam name="TController">The type of the controller.</typeparam> /// <param name="result">The result to check.</param> /// <param name="action">The action to call on the controller.</param> /// <returns></returns> public static RedirectToRouteResult ToAction<TController>(this RedirectToRouteResult result, Expression<Action<TController>> action) where TController : IController { var methodCall = (MethodCallExpression)action.Body; string actionName = methodCall.Method.Name; const string ControllerSuffix = "Controller"; var controllerTypeName = typeof(TController).Name; if (controllerTypeName.EndsWith(ControllerSuffix, StringComparison.OrdinalIgnoreCase)) { controllerTypeName = controllerTypeName.Substring(0, controllerTypeName.Length - ControllerSuffix.Length); } return result.ToController(controllerTypeName).ToAction(actionName); } /// <summary> /// Asserts that an ActionRedirectResult contains a specified value in its RouteValueCollection. /// </summary> /// <param name="result">The result to check.</param> /// <param name="paramName">The name of the parameter to check for.</param> /// <param name="value">The expected value.</param> /// <returns></returns> public static RedirectToRouteResult WithParameter(this RedirectToRouteResult result, string paramName, object value) { if(!result.RouteValues.ContainsKey(paramName)) { throw new ActionResultAssertionException(string.Format("Could not find a parameter named '{0}' in the result's Values collection.", paramName)); } var paramValue = result.RouteValues[paramName]; if(!paramValue.Equals(value)) { throw new ActionResultAssertionException(string.Format("When looking for a parameter named '{0}', expected '{1}' but was '{2}'.", paramName, value, paramValue)); } return result; } /// <summary> /// Gets a parameter from a RedirectToRouteResult. /// </summary> /// <param name="result">The result to check.</param> /// <param name="controller">The controller that you redirected FROM.</param> /// <param name="paramName">The name of the parameter to check for.</param> /// <returns></returns> public static object GetStronglyTypedParameter(this RedirectToRouteResult result, Controller controller, string paramName) { if(result.RouteValues.ContainsKey(paramName)) { return result.RouteValues[paramName]; } const string passParameterDuringRedirectPrefix = "__RedirectParameter__"; if(controller.TempData.ContainsKey(passParameterDuringRedirectPrefix + paramName)) { return controller.TempData[passParameterDuringRedirectPrefix + paramName]; } throw new ActionResultAssertionException( string.Format("Could not find a parameter named '{0}' in the result's Values collection.", paramName)); } /// <summary> /// Asserts that a RenderViewResult is rendering the specified view. /// </summary> /// <param name="result">The result to check.</param> /// <param name="viewName">The name of the view.</param> /// <returns></returns> public static ViewResult ForView(this ViewResult result, string viewName) { if(result.ViewName != viewName) { throw new ActionResultAssertionException(string.Format("Expected view name '{0}', actual was '{1}'", viewName, result.ViewName)); } return result; } /// <summary> /// Asserts that a RenderPartialViewResult is rendering the specified partial view /// </summary> /// <param name="result">The result to check</param> /// <param name="partialViewName">The name of the partial view</param> /// <returns></returns> public static PartialViewResult ForView(this PartialViewResult result, string partialViewName) { if(result.ViewName != partialViewName) { throw new ActionResultAssertionException(string.Format("Expected partial view name '{0}', actual was '{1}'", partialViewName, result.ViewName)); } return result; } /// <summary> /// Asserts that a HttpRedirectResult is redirecting to the specified URL. /// </summary> /// <param name="result">The result to check</param> /// <param name="url">The URL that the result should be redirecting to.</param> /// <returns></returns> public static RedirectResult ToUrl(this RedirectResult result, string url) { if(result.Url != url) { throw new ActionResultAssertionException(string.Format("Expected redirect to '{0}', actual was '{1}'", url, result.Url)); } return result; } /// <summary> /// Asserts that a RenderViewResult's value has been set using a strongly typed value, returning that value if successful. /// If the type is a reference type, a view data set to null will be returned as null. /// If the type is a value type, a view data set to null will throw an exception. /// </summary> /// <typeparam name="TViewData">The custom type for the view data.</typeparam> /// <param name="actionResult">The result to check.</param> /// <returns>The ViewData in it's strongly-typed form.</returns> public static TViewData WithViewData<TViewData>(this PartialViewResult actionResult) { return AssertViewDataModelType<TViewData>(actionResult); } /// <summary> /// Asserts that a RenderViewResult's value has been set using a strongly typed value, returning that value if successful. /// If the type is a reference type, a view data set to null will be returned as null. /// If the type is a value type, a view data set to null will throw an exception. /// </summary> /// <typeparam name="TViewData">The custom type for the view data.</typeparam> /// <param name="actionResult">The result to check.</param> /// <returns>The ViewData in it's strongly-typed form.</returns> public static TViewData WithViewData<TViewData>(this ViewResult actionResult) { return AssertViewDataModelType<TViewData>(actionResult); } private static TViewData AssertViewDataModelType<TViewData>(ViewResultBase actionResult) { var actualViewData = actionResult.ViewData.Model; var expectedType = typeof(TViewData); if (actualViewData == null) { throw new ActionResultAssertionException(string.Format("Expected view data of type '{0}', actual was NULL", expectedType.Name)); } if (actualViewData == null) { return (TViewData)actualViewData; } if (!typeof(TViewData).IsAssignableFrom(actualViewData.GetType())) { throw new ActionResultAssertionException(string.Format("Expected view data of type '{0}', actual was '{1}'", typeof(TViewData).Name, actualViewData.GetType().Name)); } return (TViewData)actualViewData; } } }
/* * reachability.cs from * https://github.com/xamarin/monotouch-samples/blob/master/ReachabilitySample/reachability.cs * * Copyright 2011 Xamarin Inc * */ using System; using System.Net; #if __UNIFIED__ using SystemConfiguration; using CoreFoundation; using System.Diagnostics; #else using MonoTouch.SystemConfiguration; using MonoTouch.CoreFoundation; using System.Diagnostics; #endif namespace Plugin.Connectivity { /// <summary> /// Status of newtowkr enum /// </summary> public enum NetworkStatus { /// <summary> /// No internet connection /// </summary> NotReachable, /// <summary> /// Reachable view Cellular. /// </summary> ReachableViaCarrierDataNetwork, /// <summary> /// Reachable view wifi /// </summary> ReachableViaWiFiNetwork } /// <summary> /// Reachability helper /// </summary> public static class Reachability { /// <summary> /// Default host name to use /// </summary> public static string HostName = "www.google.com"; /// <summary> /// Checks if reachable without requireing a connection /// </summary> /// <param name="flags"></param> /// <returns></returns> public static bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags) { // Is it reachable with the current network configuration? bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0; // Do we need a connection to reach it? bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0; // Since the network stack will automatically try to get the WAN up, // probe that if ((flags & NetworkReachabilityFlags.IsWWAN) != 0) noConnectionRequired = true; return isReachable && noConnectionRequired; } /// <summary> /// Checks if host is reachable /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <returns></returns> public static bool IsHostReachable(string host, int port) { if (string.IsNullOrWhiteSpace(host)) return false; IPAddress address; if (!IPAddress.TryParse(host + ":" + port, out address)) { Debug.WriteLine(host + ":" + port + " is not valid"); return false; } using (var r = new NetworkReachability(host)) { NetworkReachabilityFlags flags; if (r.TryGetFlags(out flags)) { return IsReachableWithoutRequiringConnection(flags); } } return false; } /// <summary> /// Is the host reachable with the current network configuration /// </summary> /// <param name="host"></param> /// <returns></returns> public static bool IsHostReachable(string host) { if (string.IsNullOrWhiteSpace(host)) return false; using (var r = new NetworkReachability(host)) { NetworkReachabilityFlags flags; if (r.TryGetFlags(out flags)) { return IsReachableWithoutRequiringConnection(flags); } } return false; } /// <summary> /// Raised every time there is an interesting reachable event, /// we do not even pass the info as to what changed, and /// we lump all three status we probe into one /// </summary> public static event EventHandler ReachabilityChanged; static void OnChange(NetworkReachabilityFlags flags) { var h = ReachabilityChanged; if (h != null) h(null, EventArgs.Empty); } // // Returns true if it is possible to reach the AdHoc WiFi network // and optionally provides extra network reachability flags as the // out parameter // static NetworkReachability adHocWiFiNetworkReachability; /// <summary> /// Checks ad hoc wifi is available /// </summary> /// <param name="flags"></param> /// <returns></returns> public static bool IsAdHocWiFiNetworkAvailable(out NetworkReachabilityFlags flags) { if (adHocWiFiNetworkReachability == null) { adHocWiFiNetworkReachability = new NetworkReachability(new IPAddress(new byte[] { 169, 254, 0, 0 })); adHocWiFiNetworkReachability.SetNotification(OnChange); adHocWiFiNetworkReachability.Schedule(CFRunLoop.Main, CFRunLoop.ModeDefault); } if (!adHocWiFiNetworkReachability.TryGetFlags(out flags)) return false; return IsReachableWithoutRequiringConnection(flags); } static NetworkReachability defaultRouteReachability; static bool IsNetworkAvailable(out NetworkReachabilityFlags flags) { if (defaultRouteReachability == null) { defaultRouteReachability = new NetworkReachability(new IPAddress(0)); defaultRouteReachability.SetNotification(OnChange); defaultRouteReachability.Schedule(CFRunLoop.Main, CFRunLoop.ModeDefault); } if (!defaultRouteReachability.TryGetFlags(out flags)) return false; return IsReachableWithoutRequiringConnection(flags); } static NetworkReachability remoteHostReachability; /// <summary> /// Checks the remote host status /// </summary> /// <returns></returns> public static NetworkStatus RemoteHostStatus() { NetworkReachabilityFlags flags; bool reachable; if (remoteHostReachability == null) { remoteHostReachability = new NetworkReachability(HostName); // Need to probe before we queue, or we wont get any meaningful values // this only happens when you create NetworkReachability from a hostname reachable = remoteHostReachability.TryGetFlags(out flags); remoteHostReachability.SetNotification(OnChange); remoteHostReachability.Schedule(CFRunLoop.Main, CFRunLoop.ModeDefault); } else reachable = remoteHostReachability.TryGetFlags(out flags); if (!reachable) return NetworkStatus.NotReachable; if (!IsReachableWithoutRequiringConnection(flags)) return NetworkStatus.NotReachable; if ((flags & NetworkReachabilityFlags.IsWWAN) != 0) return NetworkStatus.ReachableViaCarrierDataNetwork; return NetworkStatus.ReachableViaWiFiNetwork; } /// <summary> /// Checks internet connection status /// </summary> /// <returns></returns> public static NetworkStatus InternetConnectionStatus() { NetworkStatus status = NetworkStatus.NotReachable; NetworkReachabilityFlags flags; bool defaultNetworkAvailable = IsNetworkAvailable(out flags); // If the connection is reachable and no connection is required, then assume it's WiFi if (defaultNetworkAvailable) { status = NetworkStatus.ReachableViaWiFiNetwork; } // If the connection is on-demand or on-traffic and no user intervention // is required, then assume WiFi. if (((flags & NetworkReachabilityFlags.ConnectionOnDemand) != 0 || (flags & NetworkReachabilityFlags.ConnectionOnTraffic) != 0) && (flags & NetworkReachabilityFlags.InterventionRequired) == 0) { status = NetworkStatus.ReachableViaWiFiNetwork; } // If it's a WWAN connection.. if ((flags & NetworkReachabilityFlags.IsWWAN) != 0) status = NetworkStatus.ReachableViaCarrierDataNetwork; return status; } /// <summary> /// Check local wifi status /// </summary> /// <returns></returns> public static NetworkStatus LocalWifiConnectionStatus() { NetworkReachabilityFlags flags; if (IsAdHocWiFiNetworkAvailable(out flags)) { if ((flags & NetworkReachabilityFlags.IsDirect) != 0) return NetworkStatus.ReachableViaWiFiNetwork; } return NetworkStatus.NotReachable; } /// <summary> /// Dispose /// </summary> public static void Dispose() { if (remoteHostReachability != null) { remoteHostReachability.Dispose(); remoteHostReachability = null; } if (defaultRouteReachability != null) { defaultRouteReachability.Dispose(); defaultRouteReachability = null; } if (adHocWiFiNetworkReachability != null) { adHocWiFiNetworkReachability.Dispose(); adHocWiFiNetworkReachability = null; } } } }
// ----------------------------------------------------------------------------------------- // <copyright file="CloudQueueMessage.Common.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.Queue { using Microsoft.WindowsAzure.Storage.Core; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; /// <summary> /// Represents a message in the Windows Azure Queue service. /// </summary> public sealed partial class CloudQueueMessage { /// <summary> /// The maximum message size in bytes. /// </summary> private const long MaximumMessageSize = 64 * Constants.KB; /// <summary> /// Gets the maximum message size in bytes. /// </summary> /// <value>The maximum message size in bytes.</value> public static long MaxMessageSize { get { return MaximumMessageSize; } } /// <summary> /// The maximum amount of time a message is kept in the queue. /// </summary> private static readonly TimeSpan MaximumTimeToLive = TimeSpan.FromDays(7); /// <summary> /// Gets the maximum amount of time a message is kept in the queue. /// </summary> /// <value>A <see cref="TimeSpan"/> specifying the maximum amount of time a message is kept in the queue.</value> public static TimeSpan MaxTimeToLive { get { return MaximumTimeToLive; } } /// <summary> /// The maximum number of messages that can be peeked at a time. /// </summary> private const int MaximumNumberOfMessagesToPeek = 32; /// <summary> /// Gets the maximum number of messages that can be peeked at a time. /// </summary> /// <value>The maximum number of messages that can be peeked at a time.</value> public static int MaxNumberOfMessagesToPeek { get { return MaximumNumberOfMessagesToPeek; } } /// <summary> /// Custom UTF8Encoder to throw exception in case of invalid bytes. /// </summary> private static UTF8Encoding utf8Encoder = new UTF8Encoding(false, true); /// <summary> /// Initializes a new instance of the <see cref="CloudQueueMessage"/> class with the given byte array. /// </summary> internal CloudQueueMessage() { } /// <summary> /// Initializes a new instance of the <see cref="CloudQueueMessage"/> class with the given string. /// </summary> /// <param name="content">The content of the message as a string of text.</param> public CloudQueueMessage(string content) { this.SetMessageContent(content); // At this point, without knowing whether or not the message will be Base64 encoded, we can't fully validate the message size. // So we leave it to CloudQueue so that we have a central place for this logic. } /// <summary> /// Initializes a new instance of the <see cref="CloudQueueMessage"/> class with the given message ID and pop receipt. /// </summary> /// <param name="messageId">A string specifying the message ID.</param> /// <param name="popReceipt">A string containing the pop receipt token.</param> public CloudQueueMessage(string messageId, string popReceipt) { this.Id = messageId; this.PopReceipt = popReceipt; } /// <summary> /// Initializes a new instance of the <see cref="CloudQueueMessage"/> class with the given Base64 encoded string. /// This method is only used internally. /// </summary> /// <param name="content">The text string.</param> /// <param name="isBase64Encoded">Whether the string is Base64 encoded.</param> internal CloudQueueMessage(string content, bool isBase64Encoded) { if (content == null) { content = string.Empty; } this.RawString = content; this.MessageType = isBase64Encoded ? QueueMessageType.Base64Encoded : QueueMessageType.RawString; } /// <summary> /// Gets the content of the message as a byte array. /// </summary> /// <value>The content of the message as a byte array.</value> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Reviewed.")] public byte[] AsBytes { get { if (this.MessageType == QueueMessageType.RawString) { return Encoding.UTF8.GetBytes(this.RawString); } else { return Convert.FromBase64String(this.RawString); } } } /// <summary> /// Gets the message ID. /// </summary> /// <value>A string containing the message ID.</value> public string Id { get; internal set; } /// <summary> /// Gets the message's pop receipt. /// </summary> /// <value>A string containing the pop receipt value.</value> public string PopReceipt { get; internal set; } /// <summary> /// Gets the time that the message was added to the queue. /// </summary> /// <value>A <see cref="DateTimeOffset"/> indicating the time that the message was added to the queue.</value> public DateTimeOffset? InsertionTime { get; internal set; } /// <summary> /// Gets the time that the message expires. /// </summary> /// <value>A <see cref="DateTimeOffset"/> indicating the time that the message expires.</value> public DateTimeOffset? ExpirationTime { get; internal set; } /// <summary> /// Gets the time that the message will next be visible. /// </summary> /// <value>A <see cref="DateTimeOffset"/> indicating the time that the message will next be visible.</value> public DateTimeOffset? NextVisibleTime { get; internal set; } /// <summary> /// Gets the content of the message, as a string. /// </summary> /// <value>A string containing the message content.</value> public string AsString { get { if (this.MessageType == QueueMessageType.RawString) { return this.RawString; } else { byte[] messageData = Convert.FromBase64String(this.RawString); return utf8Encoder.GetString(messageData, 0, messageData.Length); } } } /// <summary> /// Gets the number of times this message has been dequeued. /// </summary> /// <value>The number of times this message has been dequeued.</value> public int DequeueCount { get; internal set; } /// <summary> /// Gets message type that indicates if the RawString is the original message string or Base64 encoding of the original binary data. /// </summary> internal QueueMessageType MessageType { get; private set; } /// <summary> /// Gets or sets the original message string or Base64 encoding of the original binary data. /// </summary> /// <value>The original message string.</value> internal string RawString { get; set; } /// <summary> /// Gets the content of the message for transfer (internal use only). /// </summary> /// <param name="shouldEncodeMessage">Indicates if the message should be encoded.</param> /// <returns>The message content as a string.</returns> internal string GetMessageContentForTransfer(bool shouldEncodeMessage) { if (!shouldEncodeMessage && this.MessageType == QueueMessageType.Base64Encoded) { throw new ArgumentException(SR.BinaryMessageShouldUseBase64Encoding); } string outgoingMessageString = null; if (this.MessageType == QueueMessageType.RawString) { if (shouldEncodeMessage) { outgoingMessageString = Convert.ToBase64String(this.AsBytes); // the size of Base64 encoded string is the number of bytes this message will take up on server. if (outgoingMessageString.Length > CloudQueueMessage.MaxMessageSize) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, SR.MessageTooLarge, CloudQueueMessage.MaxMessageSize)); } } else { outgoingMessageString = this.RawString; // we need to calculate the size of its UTF8 byte array, as that will be the storage usage on server. if (Encoding.UTF8.GetBytes(outgoingMessageString).Length > CloudQueueMessage.MaxMessageSize) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, SR.MessageTooLarge, CloudQueueMessage.MaxMessageSize)); } } } else { // at this point, this.EncodeMessage must be true outgoingMessageString = this.RawString; // the size of Base64 encoded string is the number of bytes this message will take up on server. if (outgoingMessageString.Length > CloudQueueMessage.MaxMessageSize) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, SR.MessageTooLarge, CloudQueueMessage.MaxMessageSize)); } } return outgoingMessageString; } /// <summary> /// Sets the content of this message. /// </summary> /// <param name="content">A string containing the new message content.</param> public void SetMessageContent(string content) { if (content == null) { // Protocol will return null for empty content content = string.Empty; } this.RawString = content; this.MessageType = QueueMessageType.RawString; } } }
// 3D Projective Geometric Algebra // Written by a generator written by enki. using System; using System.Text; using static QUA.QUAT; // static variable acces namespace QUA { public class QUAT { // just for debug and print output, the basis names public static string[] _basis = new[] { "1","e1","e2","e12" }; private float[] _mVec = new float[4]; /// <summary> /// Ctor /// </summary> /// <param name="f"></param> /// <param name="idx"></param> public QUAT(float f = 0f, int idx = 0) { _mVec[idx] = f; } #region Array Access public float this[int idx] { get { return _mVec[idx]; } set { _mVec[idx] = value; } } #endregion #region Overloaded Operators /// <summary> /// QUAT.Reverse : res = ~a /// Reverse the order of the basis blades. /// </summary> public static QUAT operator ~ (QUAT a) { QUAT res = new QUAT(); res[0]=a[0]; res[1]=a[1]; res[2]=a[2]; res[3]=-a[3]; return res; } /// <summary> /// QUAT.Dual : res = !a /// Poincare duality operator. /// </summary> public static QUAT operator ! (QUAT a) { QUAT res = new QUAT(); res[0]=-a[3]; res[1]=-a[2]; res[2]=a[1]; res[3]=a[0]; return res; } /// <summary> /// QUAT.Conjugate : res = a.Conjugate() /// Clifford Conjugation /// </summary> public QUAT Conjugate () { QUAT res = new QUAT(); res[0]=this[0]; res[1]=-this[1]; res[2]=-this[2]; res[3]=-this[3]; return res; } /// <summary> /// QUAT.Involute : res = a.Involute() /// Main involution /// </summary> public QUAT Involute () { QUAT res = new QUAT(); res[0]=this[0]; res[1]=-this[1]; res[2]=-this[2]; res[3]=this[3]; return res; } /// <summary> /// QUAT.Mul : res = a * b /// The geometric product. /// </summary> public static QUAT operator * (QUAT a, QUAT b) { QUAT res = new QUAT(); res[0]=b[0]*a[0]-b[1]*a[1]-b[2]*a[2]-b[3]*a[3]; res[1]=b[1]*a[0]+b[0]*a[1]+b[3]*a[2]-b[2]*a[3]; res[2]=b[2]*a[0]-b[3]*a[1]+b[0]*a[2]+b[1]*a[3]; res[3]=b[3]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[3]; return res; } /// <summary> /// QUAT.Wedge : res = a ^ b /// The outer product. (MEET) /// </summary> public static QUAT operator ^ (QUAT a, QUAT b) { QUAT res = new QUAT(); res[0]=b[0]*a[0]; res[1]=b[1]*a[0]+b[0]*a[1]; res[2]=b[2]*a[0]+b[0]*a[2]; res[3]=b[3]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[3]; return res; } /// <summary> /// QUAT.Vee : res = a & b /// The regressive product. (JOIN) /// </summary> public static QUAT operator & (QUAT a, QUAT b) { QUAT res = new QUAT(); res[3]=1*(a[3]*b[3]); res[2]=-1*(a[2]*-1*b[3]+a[3]*b[2]*-1); res[1]=1*(a[1]*b[3]+a[3]*b[1]); res[0]=1*(a[0]*b[3]+a[1]*b[2]*-1-a[2]*-1*b[1]+a[3]*b[0]); return res; } /// <summary> /// QUAT.Dot : res = a | b /// The inner product. /// </summary> public static QUAT operator | (QUAT a, QUAT b) { QUAT res = new QUAT(); res[0]=b[0]*a[0]-b[1]*a[1]-b[2]*a[2]-b[3]*a[3]; res[1]=b[1]*a[0]+b[0]*a[1]+b[3]*a[2]-b[2]*a[3]; res[2]=b[2]*a[0]-b[3]*a[1]+b[0]*a[2]+b[1]*a[3]; res[3]=b[3]*a[0]+b[0]*a[3]; return res; } /// <summary> /// QUAT.Add : res = a + b /// Multivector addition /// </summary> public static QUAT operator + (QUAT a, QUAT b) { QUAT res = new QUAT(); res[0] = a[0]+b[0]; res[1] = a[1]+b[1]; res[2] = a[2]+b[2]; res[3] = a[3]+b[3]; return res; } /// <summary> /// QUAT.Sub : res = a - b /// Multivector subtraction /// </summary> public static QUAT operator - (QUAT a, QUAT b) { QUAT res = new QUAT(); res[0] = a[0]-b[0]; res[1] = a[1]-b[1]; res[2] = a[2]-b[2]; res[3] = a[3]-b[3]; return res; } /// <summary> /// QUAT.smul : res = a * b /// scalar/multivector multiplication /// </summary> public static QUAT operator * (float a, QUAT b) { QUAT res = new QUAT(); res[0] = a*b[0]; res[1] = a*b[1]; res[2] = a*b[2]; res[3] = a*b[3]; return res; } /// <summary> /// QUAT.muls : res = a * b /// multivector/scalar multiplication /// </summary> public static QUAT operator * (QUAT a, float b) { QUAT res = new QUAT(); res[0] = a[0]*b; res[1] = a[1]*b; res[2] = a[2]*b; res[3] = a[3]*b; return res; } /// <summary> /// QUAT.sadd : res = a + b /// scalar/multivector addition /// </summary> public static QUAT operator + (float a, QUAT b) { QUAT res = new QUAT(); res[0] = a+b[0]; res[1] = b[1]; res[2] = b[2]; res[3] = b[3]; return res; } /// <summary> /// QUAT.adds : res = a + b /// multivector/scalar addition /// </summary> public static QUAT operator + (QUAT a, float b) { QUAT res = new QUAT(); res[0] = a[0]+b; res[1] = a[1]; res[2] = a[2]; res[3] = a[3]; return res; } /// <summary> /// QUAT.ssub : res = a - b /// scalar/multivector subtraction /// </summary> public static QUAT operator - (float a, QUAT b) { QUAT res = new QUAT(); res[0] = a-b[0]; res[1] = -b[1]; res[2] = -b[2]; res[3] = -b[3]; return res; } /// <summary> /// QUAT.subs : res = a - b /// multivector/scalar subtraction /// </summary> public static QUAT operator - (QUAT a, float b) { QUAT res = new QUAT(); res[0] = a[0]-b; res[1] = a[1]; res[2] = a[2]; res[3] = a[3]; return res; } #endregion /// <summary> /// QUAT.norm() /// Calculate the Euclidean norm. (strict positive). /// </summary> public float norm() { return (float) Math.Sqrt(Math.Abs((this*this.Conjugate())[0]));} /// <summary> /// QUAT.inorm() /// Calculate the Ideal norm. (signed) /// </summary> public float inorm() { return this[1]!=0.0f?this[1]:this[15]!=0.0f?this[15]:(!this).norm();} /// <summary> /// QUAT.normalized() /// Returns a normalized (Euclidean) element. /// </summary> public QUAT normalized() { return this*(1/norm()); } // The basis blades public static QUAT e1 = new QUAT(1f, 1); public static QUAT e2 = new QUAT(1f, 2); public static QUAT e12 = new QUAT(1f, 3); /// string cast public override string ToString() { var sb = new StringBuilder(); var n=0; for (int i = 0; i < 4; ++i) if (_mVec[i] != 0.0f) { sb.Append($"{_mVec[i]}{(i == 0 ? string.Empty : _basis[i])} + "); n++; } if (n==0) sb.Append("0"); return sb.ToString().TrimEnd(' ', '+'); } } class Program { static void Main(string[] args) { Console.WriteLine("e1*e1 : "+e1*e1); Console.WriteLine("pss : "+e12); Console.WriteLine("pss*pss : "+e12*e12); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using com.google.zxing.common; /* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace com.google.zxing.client.result { using Result = com.google.zxing.Result; /// <summary> /// Parses contact information formatted according to the VCard (2.1) format. This is not a complete /// implementation but should parse information as commonly encoded in 2D barcodes. /// /// @author Sean Owen /// </summary> public sealed class VCardResultParser : ResultParser { private static readonly string BEGIN_VCARD = "BEGIN:VCARD"; private static readonly string VCARD_LIKE_DATE = "\\d{4}-?\\d{2}-?\\d{2}"; private static readonly string CR_LF_SPACE_TAB = "\r\n[ \t]"; private static readonly string NEWLINE_ESCAPE = "\\\\[nN]"; private static readonly string VCARD_ESCAPES = "\\\\([,;\\\\])"; private static readonly string EQUALS = "="; private static readonly string SEMICOLON = ";"; private static readonly string UNESCAPED_SEMICOLONS = "(?<!\\\\);+"; public override ParsedResult parse(Result result) { // Although we should insist on the raw text ending with "END:VCARD", there's no reason // to throw out everything else we parsed just because this was omitted. In fact, Eclair // is doing just that, and we can't parse its contacts without this leniency. string rawText = getMassagedText(result); Match m = Regex.Match(rawText, BEGIN_VCARD, RegexOptions.IgnoreCase); if (!m.Success || m.Index != 0) { return null; } IList<IList<string>> names = matchVCardPrefixedField("FN", rawText, true, false); if (names == null) { // If no display names found, look for regular name fields and format them names = matchVCardPrefixedField("N", rawText, true, false); formatNames(names); } IList<IList<string>> phoneNumbers = matchVCardPrefixedField("TEL", rawText, true, false); IList<IList<string>> emails = matchVCardPrefixedField("EMAIL", rawText, true, false); IList<string> note = matchSingleVCardPrefixedField("NOTE", rawText, false, false); IList<IList<string>> addresses = matchVCardPrefixedField("ADR", rawText, true, true); IList<string> org = matchSingleVCardPrefixedField("ORG", rawText, true, true); IList<string> birthday = matchSingleVCardPrefixedField("BDAY", rawText, true, false); if (birthday != null && !isLikeVCardDate(birthday[0])) { birthday = null; } IList<string> title = matchSingleVCardPrefixedField("TITLE", rawText, true, false); IList<string> url = matchSingleVCardPrefixedField("URL", rawText, true, false); IList<string> instantMessenger = matchSingleVCardPrefixedField("IMPP", rawText, true, false); return new AddressBookParsedResult(toPrimaryValues(names), null, toPrimaryValues(phoneNumbers), toTypes(phoneNumbers), toPrimaryValues(emails), toTypes(emails), toPrimaryValue(instantMessenger), toPrimaryValue(note), toPrimaryValues(addresses), toTypes(addresses), toPrimaryValue(org), toPrimaryValue(birthday), toPrimaryValue(title), toPrimaryValue(url)); } internal static IList<IList<string>> matchVCardPrefixedField(string prefix, string rawText, bool trim, bool parseFieldDivider) { IList<IList<string>> matches = null; int i = 0; int max = rawText.Length; while (i < max) { // At start or after newline, match prefix, followed by optional metadata // (led by ;) ultimately ending in colon //Matcher matcher = Pattern.compile("(?:^|\n)" + prefix + "(?:;([^:]*))?:", Pattern.CASE_INSENSITIVE).matcher(rawText); Regex matcher = new Regex("(?:^|\n)" + prefix + "(?:;([^:]*))?:", RegexOptions.IgnoreCase); //(rawText); if (i > 0) { i--; // Find from i-1 not i since looking at the preceding character } //if (!matcher.find(i)) Match match = matcher.Match(rawText); if (!match.Success) { break; } //i = matcher.end(0); // group 0 = whole pattern; end(0) is past final colon i = match.Groups[0].Index + match.Groups[0].Length; // group 0 = whole pattern; end(0) is past final colon string metadataString = match.Groups[1].Value; // group 1 = metadata substring IList<string> metadata = null; bool quotedPrintable = false; string quotedPrintableCharset = null; if (metadataString != null) { foreach (string metadatum in SEMICOLON.Split(new string[] {metadataString},StringSplitOptions.None)) { if (metadata == null) { metadata = new List<string>(1); } metadata.Add(metadatum); //string[] metadatumTokens = EQUALS.Split(metadatum, 2); string[] metadatumTokens = EQUALS.Split(new string[] {metadatum},2,StringSplitOptions.None); if (metadatumTokens.Length > 1) { string key = metadatumTokens[0]; string value = metadatumTokens[1]; if ("ENCODING"== key.ToUpper() && "QUOTED-PRINTABLE"==value.ToUpper()) { quotedPrintable = true; } else if ("CHARSET" == key.ToUpper()) { quotedPrintableCharset = value; } } } } int matchStart = i; // Found the start of a match here while ((i =(int) rawText.IndexOf( '\n', i)) >= 0) // Really, end in \r\n { if (i < rawText.Length - 1 && (rawText[i + 1] == ' ' || rawText[i + 1] == '\t')) // this is only a continuation - But if followed by tab or space, { i += 2; // Skip \n and continutation whitespace } // If preceded by = in quoted printable else if (quotedPrintable && ((i >= 1 && rawText[i - 1] == '=') || (i >= 2 && rawText[i - 2] == '='))) // this is a continuation { i++; // Skip \n } else { break; } } if (i < 0) { // No terminating end character? uh, done. Set i such that loop terminates and break i = max; } else if (i > matchStart) { // found a match if (matches == null) { matches = new List<IList<string>>(1); // lazy init } if (i >= 1 && rawText[i - 1] == '\r') { i--; // Back up over \r, which really should be there } string element = rawText.Substring(matchStart, i - matchStart); if (trim) { element = element.Trim(); } if (quotedPrintable) { element = decodeQuotedPrintable(element, quotedPrintableCharset); if (parseFieldDivider) { //element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").Trim(); element = new Regex(UNESCAPED_SEMICOLONS).Replace(element,("\n")).Trim(); } } else { if (parseFieldDivider) { //element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").Trim(); element = new Regex(UNESCAPED_SEMICOLONS).Replace(element,"\n").Trim(); } //element = CR_LF_SPACE_TAB.matcher(element).replaceAll(""); element = new Regex(CR_LF_SPACE_TAB).Replace(element,""); //element = NEWLINE_ESCAPE.matcher(element).replaceAll("\n"); element = new Regex(NEWLINE_ESCAPE).Replace(element,"\n"); //element = VCARD_ESCAPES.matcher(element).replaceAll("$1"); element = new Regex(VCARD_ESCAPES).Replace(element,"$1"); } if (metadata == null) { IList<string> matchList = new List<string>(1); matchList.Add(element); matches.Add(matchList); } else { metadata.Insert(0, element); matches.Add(metadata); } i++; } else { i++; } } return matches; } private static string decodeQuotedPrintable(string value, string charset) { int length = value.Length; StringBuilder result = new StringBuilder(length); MemoryStream fragmentBuffer = new MemoryStream(); for (int i = 0; i < length; i++) { char c = value[i]; switch (c) { case '\r': case '\n': break; case '=': if (i < length - 2) { char nextChar = value[i + 1]; if (nextChar != '\r' && nextChar != '\n') { char nextNextChar = value[i + 2]; int firstDigit = parseHexDigit(nextChar); int secondDigit = parseHexDigit(nextNextChar); if (firstDigit >= 0 && secondDigit >= 0) { fragmentBuffer.WriteByte((byte)((firstDigit << 4) + secondDigit)); } // else ignore it, assume it was incorrectly encoded i += 2; } } break; default: maybeAppendFragment(fragmentBuffer, charset, result); result.Append(c); break; } } maybeAppendFragment(fragmentBuffer, charset, result); return result.ToString(); } private static void maybeAppendFragment(MemoryStream fragmentBuffer, string charset, StringBuilder result) { Encoding en = Encoding.GetEncoding(charset); Encoding enFallback = Encoding.UTF8; if (fragmentBuffer.Length > 0) { sbyte[] fragmentBytes = fragmentBuffer.ToArray().ToSBytes(); string fragment; if (charset == null) { fragment = en.GetString((byte[])(Array)fragmentBytes); ; } else { try { fragment = en.GetString((byte[])(Array)fragmentBytes); ; } catch (ArgumentException e) { // Yikes, well try anyway: //fragment = new string(fragmentBytes); fragment = enFallback.GetString((byte[]) (Array) fragmentBytes); } } fragmentBuffer.Position=0; result.Append(fragment); } } internal static IList<string> matchSingleVCardPrefixedField(string prefix, string rawText, bool trim, bool parseFieldDivider) { IList<IList<string>> values = matchVCardPrefixedField(prefix, rawText, trim, parseFieldDivider); return values == null || values.Count == 0 ? null : values[0]; } private static string toPrimaryValue(IList<string> list) { return list == null || list.Count == 0 ? null : list[0]; } private static string[] toPrimaryValues(ICollection<IList<string>> lists) { if (lists == null || lists.Count == 0) { return null; } List<string> result = new List<string>(lists.Count); foreach (IList<string> list in lists) { result.Add(list[0]); } return result.ToArray(); } private static string[] toTypes(ICollection<IList<string>> lists) { if (lists == null || lists.Count == 0) { return null; } List<string> result = new List<string>(lists.Count); foreach (IList<string> list in lists) { string type = null; for (int i = 1; i < list.Count; i++) { string metadatum = list[i]; int equals = metadatum.IndexOf('='); if (equals < 0) { // take the whole thing as a usable label type = metadatum; break; } if ("TYPE" == (metadatum.Substring(0, equals)).ToUpper()) { type = metadatum.Substring(equals + 1); break; } } result.Add(type); } return result.ToArray(); } private static bool isLikeVCardDate(string value) { //return value == null || VCARD_LIKE_DATE.matcher(value).matches(); return value == null || new Regex(VCARD_LIKE_DATE).IsMatch(value); } /// <summary> /// Formats name fields of the form "Public;John;Q.;Reverend;III" into a form like /// "Reverend John Q. Public III". /// </summary> /// <param name="names"> name values to format, in place </param> private static void formatNames(IEnumerable<IList<string>> names) { if (names != null) { foreach (IList<string> list in names) { string name = list[0]; string[] components = new string[5]; int start = 0; int end; int componentIndex = 0; while (componentIndex < components.Length - 1 && (end = name.IndexOf(';', start)) > 0) { components[componentIndex] = name.Substring(start, end - start); componentIndex++; start = end + 1; } components[componentIndex] = name.Substring(start); StringBuilder newName = new StringBuilder(100); maybeAppendComponent(components, 3, newName); maybeAppendComponent(components, 1, newName); maybeAppendComponent(components, 2, newName); maybeAppendComponent(components, 0, newName); maybeAppendComponent(components, 4, newName); list[0] = newName.ToString().Trim(); } } } private static void maybeAppendComponent(string[] components, int i, StringBuilder newName) { if (components[i] != null) { newName.Append(' '); newName.Append(components[i]); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Legacy; using osu.Game.Extensions; using osu.Game.Graphics; using osu.Game.Rulesets; using osu.Game.Screens.Menu; using osuTK; using osuTK.Graphics; namespace osu.Game.Tournament.Components { public class SongBar : CompositeDrawable { private BeatmapInfo beatmapInfo; public const float HEIGHT = 145 / 2f; [Resolved] private IBindable<RulesetInfo> ruleset { get; set; } public BeatmapInfo BeatmapInfo { get => beatmapInfo; set { if (beatmapInfo == value) return; beatmapInfo = value; update(); } } private LegacyMods mods; public LegacyMods Mods { get => mods; set { mods = value; update(); } } private FillFlowContainer flow; private bool expanded; public bool Expanded { get => expanded; set { expanded = value; flow.Direction = expanded ? FillDirection.Full : FillDirection.Vertical; } } // Todo: This is a hack for https://github.com/ppy/osu-framework/issues/3617 since this container is at the very edge of the screen and potentially initially masked away. protected override bool ComputeIsMaskedAway(RectangleF maskingBounds) => false; [BackgroundDependencyLoader] private void load() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChildren = new Drawable[] { flow = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, LayoutDuration = 500, LayoutEasing = Easing.OutQuint, Direction = FillDirection.Full, Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, } }; Expanded = true; } private void update() { if (beatmapInfo == null) { flow.Clear(); return; } var bpm = beatmapInfo.BeatmapSet.OnlineInfo.BPM; var length = beatmapInfo.Length; string hardRockExtra = ""; string srExtra = ""; var ar = beatmapInfo.BaseDifficulty.ApproachRate; if ((mods & LegacyMods.HardRock) > 0) { hardRockExtra = "*"; srExtra = "*"; } if ((mods & LegacyMods.DoubleTime) > 0) { // temporary local calculation (taken from OsuDifficultyCalculator) double preempt = (int)IBeatmapDifficultyInfo.DifficultyRange(ar, 1800, 1200, 450) / 1.5; ar = (float)(preempt > 1200 ? (1800 - preempt) / 120 : (1200 - preempt) / 150 + 5); bpm *= 1.5f; length /= 1.5f; srExtra = "*"; } (string heading, string content)[] stats; switch (ruleset.Value.ID) { default: stats = new (string heading, string content)[] { ("CS", $"{beatmapInfo.BaseDifficulty.CircleSize:0.#}{hardRockExtra}"), ("AR", $"{ar:0.#}{hardRockExtra}"), ("OD", $"{beatmapInfo.BaseDifficulty.OverallDifficulty:0.#}{hardRockExtra}"), }; break; case 1: case 3: stats = new (string heading, string content)[] { ("OD", $"{beatmapInfo.BaseDifficulty.OverallDifficulty:0.#}{hardRockExtra}"), ("HP", $"{beatmapInfo.BaseDifficulty.DrainRate:0.#}{hardRockExtra}") }; break; case 2: stats = new (string heading, string content)[] { ("CS", $"{beatmapInfo.BaseDifficulty.CircleSize:0.#}{hardRockExtra}"), ("AR", $"{ar:0.#}"), }; break; } flow.Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.X, Height = HEIGHT, Width = 0.5f, Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, Children = new Drawable[] { new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Anchor = Anchor.Centre, Origin = Anchor.Centre, Direction = FillDirection.Vertical, Children = new Drawable[] { new DiffPiece(stats), new DiffPiece(("Star Rating", $"{beatmapInfo.StarDifficulty:0.#}{srExtra}")) } }, new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Anchor = Anchor.Centre, Origin = Anchor.Centre, Direction = FillDirection.Vertical, Children = new Drawable[] { new DiffPiece(("Length", length.ToFormattedDuration().ToString())), new DiffPiece(("BPM", $"{bpm:0.#}")), } }, new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, Alpha = 0.1f, }, new OsuLogo { Triangles = false, Scale = new Vector2(0.08f), Margin = new MarginPadding(50), X = -10, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, }, } }, }, } } } }, new TournamentBeatmapPanel(beatmapInfo) { RelativeSizeAxes = Axes.X, Width = 0.5f, Height = HEIGHT, Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, } }; } public class DiffPiece : TextFlowContainer { public DiffPiece(params (string heading, string content)[] tuples) { Margin = new MarginPadding { Horizontal = 15, Vertical = 1 }; AutoSizeAxes = Axes.Both; static void cp(SpriteText s, bool bold) { s.Font = OsuFont.Torus.With(weight: bold ? FontWeight.Bold : FontWeight.Regular, size: 15); } for (var i = 0; i < tuples.Length; i++) { var (heading, content) = tuples[i]; if (i > 0) { AddText(" / ", s => { cp(s, false); s.Spacing = new Vector2(-2, 0); }); } AddText(new TournamentSpriteText { Text = heading }, s => cp(s, false)); AddText(" ", s => cp(s, false)); AddText(new TournamentSpriteText { Text = content }, s => cp(s, true)); } } } } }
using System; using Microsoft.SPOT; using System.Collections; using System.Text; namespace MicroTweet { internal static class Utility { private static readonly Random _random = new Random(); private const string _alphanumericChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; /// <summary> /// Generates a random alphanumeric string of the specified length. /// </summary> /// <param name="length">The length of the string to be generated.</param> public static string GetRandomAlphanumericString(int length) { char[] randomChars = new char[length]; for (int i = 0; i < length; i++) randomChars[i] = _alphanumericChars[_random.Next(_alphanumericChars.Length)]; return new string(randomChars); } /// <summary> /// Converts the value of the DateTime instance to a Unix timestamp (the number of seconds since January 1, 1970). /// </summary> public static long ToUnixTimestamp(this DateTime dateTime) { DateTime epoch = new DateTime(1970, 1, 1); TimeSpan timeSpan = (dateTime - epoch); return timeSpan.Ticks / 10000000; } /// <summary> /// Applies percent-encoding (%xx) to a string value according to RFC3986. /// </summary> /// <param name="value">The string value to encode.</param> public static string UriEncode(string value) { if (value == null) return null; StringBuilder sb = new StringBuilder(); byte[] bytes = Encoding.UTF8.GetBytes(value); byte b; bool encodeByte; for (int i = 0; i < bytes.Length; i++) { b = bytes[i]; // Do we need to encode this byte? encodeByte = true; // Safe characters defined by RFC3986: http://oauth.net/core/1.0/#encoding_parameters if ((b >= '0' && b <= '9') || (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || b == '-' || b == '.' || b == '_' || b == '~') encodeByte = false; if (encodeByte) { sb.Append('%'); sb.Append(b.ToString("X2")); } else { sb.Append((char)b); } } return sb.ToString(); } /// <summary> /// Sorts a list of IComparable objects. /// </summary> /// <param name="list">The list to be sorted.</param> public static void SortList(IList list) { if (list.Count <= 1) return; // Simple insertion sort int i, j; IComparable item; for (i = 1; i < list.Count; i++) { item = (IComparable)list[i]; for (j = i - 1; j >= 0 && item.CompareTo(list[j]) < 0; j--) list[j + 1] = list[j]; list[j + 1] = item; } } /// <summary> /// Concatenates all the elements of a string array, using the specified separator between each element. /// </summary> /// <param name="separator">The string to use as a separator.</param> /// <param name="values">An array that contains the elements to concatenate.</param> public static string StringJoin(string separator, string[] values) { string result = string.Empty; for (int i = 0; i < values.Length; i++) { if (i > 0) result += separator; result += values[i]; } return result; } /// <summary> /// Converts bytes to an RFC4648-compliant Base64 string. /// </summary> /// <param name="value">The bytes to convert.</param> public static string ConvertToRFC4648Base64String(byte[] value) { // NETMF's Convert.ToBase64String() does not follow RFC4648 by default. '!' is used in place of '+' and '*' is used in place of '/'. // A static property (Convert.UseRFC4648Encoding) was added in NETMF 4.3 to fix this, but setting it could affect other parts of user code. // Instead, we'll just search for and replace the incorrect characters. char[] resultChars = Convert.ToBase64String(value).ToCharArray(); for (int i = 0; i < resultChars.Length; i++) { if (resultChars[i] == '!') resultChars[i] = '+'; else if (resultChars[i] == '*') resultChars[i] = '/'; } return new string(resultChars); } /// <summary> /// Converts a uint value between big-endian and little-endian representations. /// </summary> /// <param name="value">The uint value to convert.</param> public static uint ReverseBytes(uint value) { return (value & 0x000000FFu) << 24 | (value & 0x0000FF00u) << 8 | (value & 0x00FF0000u) >> 8 | (value & 0xFF000000u) >> 24; } /// <summary> /// Converts a ulong value between big-endian and little-endian representations. /// </summary> /// <param name="value">The ulong value to convert.</param> public static ulong ReverseBytes(ulong value) { return (value & 0x00000000000000FFul) << 56 | (value & 0x000000000000FF00ul) << 40 | (value & 0x0000000000FF0000ul) << 24 | (value & 0x00000000FF000000ul) << 8 | (value & 0x000000FF00000000ul) >> 8 | (value & 0x0000FF0000000000ul) >> 24 | (value & 0x00FF000000000000ul) >> 40 | (value & 0xFF00000000000000ul) >> 56; } /// <summary> /// Parses a Twitter date/time string (e.g., "Tue May 19 19:53:49 +0000 2015"). /// </summary> /// <param name="value">The string value to parse.</param> public static DateTime ParseTwitterDateTime(string value) { // Year int year = int.Parse(value.Substring(26, 4)); // Month int month; switch (value.Substring(4, 3)) { case "Jan": month = 1; break; case "Feb": month = 2; break; case "Mar": month = 3; break; case "Apr": month = 4; break; case "May": month = 5; break; case "Jun": month = 6; break; case "Jul": month = 7; break; case "Aug": month = 8; break; case "Sep": month = 9; break; case "Oct": month = 10; break; case "Nov": month = 11; break; case "Dec": month = 12; break; default: throw new Exception(); } // Day int day = int.Parse(value.Substring(8, 2)); // Hour int hour = int.Parse(value.Substring(11, 2)); // Minute int minute = int.Parse(value.Substring(14, 2)); // Second int second = int.Parse(value.Substring(17, 2)); return new DateTime(year, month, day, hour, minute, second); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.IO; using System.Collections.Generic; using System.Linq; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else #endif namespace GodLesZ.Library.Json.Utilities { internal static class JavaScriptUtils { internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (int i = 0; i < ' '; i++) { escapeChars.Add((char)i); } foreach (var escapeChar in escapeChars.Union(new[] { '\'' })) { SingleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"' })) { DoubleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) { HtmlCharEscapeFlags[escapeChar] = true; } } private const string EscapedUnicodeText = "!"; public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, ref char[] writeBuffer) { // leading delimiter if (appendDelimiters) writer.Write(delimiter); if (s != null) { int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) continue; string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer == null) writeBuffer = new char[6]; StringUtils.ToCharAsUnicode(c, writeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } } else { escapedValue = null; } break; } if (escapedValue == null) continue; bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); if (i > lastWritePosition) { int length = i - lastWritePosition + ((isEscapedUnicodeText) ? 6 : 0); int start = (isEscapedUnicodeText) ? 6 : 0; if (writeBuffer == null || writeBuffer.Length < length) { char[] newBuffer = new char[length]; // the unicode text is already in the buffer // copy it over when creating new buffer if (isEscapedUnicodeText) Array.Copy(writeBuffer, newBuffer, 6); writeBuffer = newBuffer; } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text writer.Write(writeBuffer, start, length - start); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) writer.Write(escapedValue); else writer.Write(writeBuffer, 0, 6); } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { int length = s.Length - lastWritePosition; if (writeBuffer == null || writeBuffer.Length < length) writeBuffer = new char[length]; s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text writer.Write(writeBuffer, 0, length); } } // trailing delimiter if (appendDelimiters) writer.Write(delimiter); } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters) { using (StringWriter w = StringUtils.CreateStringWriter(StringUtils.GetLength(value) ?? 16)) { char[] buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, (delimiter == '"') ? DoubleQuoteCharEscapeFlags : SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, ref buffer); return w.ToString(); } } } }
// 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 gagr = Google.Api.Gax.ResourceNames; using gcsv = Google.Cloud.SecurityCenter.V1P1Beta1; namespace Google.Cloud.SecurityCenter.V1P1Beta1 { public partial class CreateFindingRequest { /// <summary><see cref="SourceName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public SourceName ParentAsSourceName { get => string.IsNullOrEmpty(Parent) ? null : SourceName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class CreateNotificationConfigRequest { /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::OrganizationName ParentAsOrganizationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class CreateSourceRequest { /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::OrganizationName ParentAsOrganizationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteNotificationConfigRequest { /// <summary> /// <see cref="gcsv::NotificationConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::NotificationConfigName NotificationConfigName { get => string.IsNullOrEmpty(Name) ? null : gcsv::NotificationConfigName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetNotificationConfigRequest { /// <summary> /// <see cref="gcsv::NotificationConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::NotificationConfigName NotificationConfigName { get => string.IsNullOrEmpty(Name) ? null : gcsv::NotificationConfigName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetOrganizationSettingsRequest { /// <summary> /// <see cref="gcsv::OrganizationSettingsName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::OrganizationSettingsName OrganizationSettingsName { get => string.IsNullOrEmpty(Name) ? null : gcsv::OrganizationSettingsName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetSourceRequest { /// <summary> /// <see cref="gcsv::SourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::SourceName SourceName { get => string.IsNullOrEmpty(Name) ? null : gcsv::SourceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GroupAssetsRequest { /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::OrganizationName ParentAsOrganizationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::FolderName ParentAsFolderName { get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization)) { return organization; } if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder)) { return folder; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class GroupFindingsRequest { /// <summary><see cref="SourceName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public SourceName ParentAsSourceName { get => string.IsNullOrEmpty(Parent) ? null : SourceName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListNotificationConfigsRequest { /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::OrganizationName ParentAsOrganizationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListSourcesRequest { /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::OrganizationName ParentAsOrganizationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::FolderName ParentAsFolderName { get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization)) { return organization; } if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder)) { return folder; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class ListAssetsRequest { /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::OrganizationName ParentAsOrganizationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::FolderName ParentAsFolderName { get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization)) { return organization; } if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder)) { return folder; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class ListFindingsRequest { /// <summary><see cref="SourceName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public SourceName ParentAsSourceName { get => string.IsNullOrEmpty(Parent) ? null : SourceName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class SetFindingStateRequest { /// <summary> /// <see cref="gcsv::FindingName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::FindingName FindingName { get => string.IsNullOrEmpty(Name) ? null : gcsv::FindingName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class RunAssetDiscoveryRequest { /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::OrganizationName ParentAsOrganizationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using TestLibrary; enum TestResult { Success, ReturnFailure, ReturnNull, IncorrectEvaluation, ArgumentNull, ArgumentBad, DllNotFound, BadImage, InvalidOperation, EntryPointNotFound, GenericException }; public class NativeLibraryTest { static string CurrentTest; static bool Verbose = false; public static int Main() { bool success = true; Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); string testBinDir = Path.GetDirectoryName(assembly.Location); string libName; IntPtr handle; try { // ----------------------------------------------- // Simple LoadLibrary() API Tests // ----------------------------------------------- // Calls on correct full-path to native lib libName = Path.Combine(testBinDir, GetNativeLibraryName()); success &= EXPECT(LoadLibrarySimple(libName)); success &= EXPECT(TryLoadLibrarySimple(libName)); // Calls on non-existant file libName = Path.Combine(testBinDir, "notfound"); success &= EXPECT(LoadLibrarySimple(libName), TestResult.DllNotFound); success &= EXPECT(TryLoadLibrarySimple(libName), TestResult.ReturnFailure); // Calls on an invalid file libName = Path.Combine(testBinDir, "NativeLibrary.cpp"); success &= EXPECT(LoadLibrarySimple(libName), (TestLibrary.Utilities.IsWindows) ? TestResult.BadImage : TestResult.DllNotFound); success &= EXPECT(TryLoadLibrarySimple(libName), TestResult.ReturnFailure); // Calls on null input libName = null; success &= EXPECT(LoadLibrarySimple(libName), TestResult.ArgumentNull); success &= EXPECT(TryLoadLibrarySimple(libName), TestResult.ArgumentNull); // ----------------------------------------------- // Advanced LoadLibrary() API Tests // ----------------------------------------------- // Advanced LoadLibrary() API Tests // Calls on correct full-path to native lib libName = Path.Combine(testBinDir, GetNativeLibraryName()); success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null)); success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null)); // Calls on non-existant file libName = Path.Combine(testBinDir, "notfound"); success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null), TestResult.DllNotFound); success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null), TestResult.ReturnFailure); // Calls on an invalid file libName = Path.Combine(testBinDir, "NativeLibrary.cpp"); // The VM can only distinguish BadImageFormatException from DllNotFoundException on Windows. success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null), (TestLibrary.Utilities.IsWindows) ? TestResult.BadImage : TestResult.DllNotFound); success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null), TestResult.ReturnFailure); // Calls on just Native Library name libName = GetNativeLibraryPlainName(); success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null)); success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null)); // Calls on Native Library name with correct prefix-suffix libName = GetNativeLibraryName(); success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null)); success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null)); // Calls on full path without prefix-siffix libName = Path.Combine(testBinDir, GetNativeLibraryPlainName()); // DllImport doesn't add a prefix if the name is preceeded by a path specification. // Windows only needs a suffix, but Linux and Mac need both prefix and suffix success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null), (TestLibrary.Utilities.IsWindows) ? TestResult.Success : TestResult.DllNotFound); success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null), (TestLibrary.Utilities.IsWindows) ? TestResult.Success : TestResult.ReturnFailure); // Check for loading a native binary in the system32 directory. // The choice of the binary is arbitrary, and may not be available on // all Windows platforms (ex: Nano server) libName = "url.dll"; if (TestLibrary.Utilities.IsWindows && File.Exists(Path.Combine(Environment.SystemDirectory, libName))) { // Calls on a valid library from System32 directory success &= EXPECT(LoadLibraryAdvanced(libName, assembly, DllImportSearchPath.System32)); success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, DllImportSearchPath.System32)); // Calls on a valid library from application directory success &= EXPECT(LoadLibraryAdvanced(libName, assembly, DllImportSearchPath.ApplicationDirectory), TestResult.DllNotFound); success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, DllImportSearchPath.ApplicationDirectory), TestResult.ReturnFailure); } // Calls with null libName input success &= EXPECT(LoadLibraryAdvanced(null, assembly, null), TestResult.ArgumentNull); success &= EXPECT(TryLoadLibraryAdvanced(null, assembly, null), TestResult.ArgumentNull); // Calls with null assembly libName = GetNativeLibraryPlainName(); success &= EXPECT(LoadLibraryAdvanced(libName, null, null), TestResult.ArgumentNull); success &= EXPECT(TryLoadLibraryAdvanced(libName, null, null), TestResult.ArgumentNull); // Ensure that a lib is not picked up from current directory when // a different full-path is specified. libName = Path.Combine(testBinDir, Path.Combine("lib", GetNativeLibraryPlainName())); success &= EXPECT(LoadLibraryAdvanced(libName, assembly, DllImportSearchPath.AssemblyDirectory), TestResult.DllNotFound); success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, DllImportSearchPath.AssemblyDirectory), TestResult.ReturnFailure); // ----------------------------------------------- // FreeLibrary Tests // ----------------------------------------------- libName = Path.Combine(testBinDir, GetNativeLibraryName()); handle = NativeLibrary.Load(libName); // Valid Free success &= EXPECT(FreeLibrary(handle)); // Double Free if (TestLibrary.Utilities.IsWindows) { // The FreeLibrary() implementation simply calls the appropriate OS API // with the supplied handle. Not all OSes consistently return an error // when a library is double-freed. success &= EXPECT(FreeLibrary(handle), TestResult.InvalidOperation); } // Null Free success &= EXPECT(FreeLibrary(IntPtr.Zero)); // ----------------------------------------------- // GetLibraryExport Tests // ----------------------------------------------- libName = Path.Combine(testBinDir, GetNativeLibraryName()); handle = NativeLibrary.Load(libName); // Valid Call (with some hard-coded name mangling) success &= EXPECT(GetLibraryExport(handle, TestLibrary.Utilities.IsX86 ? "_NativeSum@8" : "NativeSum")); success &= EXPECT(TryGetLibraryExport(handle, TestLibrary.Utilities.IsX86 ? "_NativeSum@8" : "NativeSum")); // Call with null handle success &= EXPECT(GetLibraryExport(IntPtr.Zero, "NativeSum"), TestResult.ArgumentNull); success &= EXPECT(TryGetLibraryExport(IntPtr.Zero, "NativeSum"), TestResult.ArgumentNull); // Call with null string success &= EXPECT(GetLibraryExport(handle, null), TestResult.ArgumentNull); success &= EXPECT(TryGetLibraryExport(handle, null), TestResult.ArgumentNull); // Call with wrong string success &= EXPECT(GetLibraryExport(handle, "NonNativeSum"), TestResult.EntryPointNotFound); success &= EXPECT(TryGetLibraryExport(handle, "NonNativeSum"), TestResult.ReturnFailure); NativeLibrary.Free(handle); } catch (Exception e) { // Catch any exceptions in NativeLibrary calls directly within this function. // These calls are used to setup the environment for tests that follow, and are not expected to fail. // If they do fail (ex: incorrect build environment) fail with an error code, rather than segmentation fault. Console.WriteLine(String.Format("Unhandled exception {0}", e)); success = false; } return (success) ? 100 : -100; } static string GetNativeLibraryPlainName() { return "NativeLibrary"; } static string GetNativeLibraryName() { string baseName = GetNativeLibraryPlainName(); if (TestLibrary.Utilities.IsWindows) { return baseName + ".dll"; } if (TestLibrary.Utilities.IsLinux) { return "lib" + baseName + ".so"; } if (TestLibrary.Utilities.IsMacOSX) { return "lib" + baseName + ".dylib"; } return "ERROR"; } static bool EXPECT(TestResult actualValue, TestResult expectedValue = TestResult.Success) { if (actualValue == expectedValue) { if (Verbose) Console.WriteLine(String.Format("{0} : {1} : [OK]", CurrentTest, actualValue)); return true; } else { Console.WriteLine(String.Format(" {0} : {1} : [FAIL]", CurrentTest, actualValue)); return false; } } static TestResult Run (Func<TestResult> test) { TestResult result; try { result = test(); } catch (ArgumentNullException e) { return TestResult.ArgumentNull; } catch (ArgumentException e) { return TestResult.ArgumentBad; } catch (DllNotFoundException e) { return TestResult.DllNotFound; } catch (BadImageFormatException e) { return TestResult.BadImage; } catch (InvalidOperationException e) { return TestResult.InvalidOperation; } catch (EntryPointNotFoundException e) { return TestResult.EntryPointNotFound; } catch (Exception e) { //Console.WriteLine(e.ToString()); return TestResult.GenericException; } return result; } static TestResult LoadLibrarySimple(string libPath) { CurrentTest = String.Format("LoadLibrary({0})", libPath); IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { handle = NativeLibrary.Load(libPath); if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult TryLoadLibrarySimple(string libPath) { CurrentTest = String.Format("TryLoadLibrary({0})", libPath); IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { bool success = NativeLibrary.TryLoad(libPath, out handle); if(!success) return TestResult.ReturnFailure; if (handle == null) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult LoadLibraryAdvanced(string libName, Assembly assembly, DllImportSearchPath? searchPath) { CurrentTest = String.Format("LoadLibrary({0}, {1}, {2})", libName, assembly, searchPath); IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { handle = NativeLibrary.Load(libName, assembly, searchPath); if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult TryLoadLibraryAdvanced(string libName, Assembly assembly, DllImportSearchPath? searchPath) { CurrentTest = String.Format("TryLoadLibrary({0}, {1}, {2})", libName, assembly, searchPath); IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { bool success = NativeLibrary.TryLoad(libName, assembly, searchPath, out handle); if (!success) return TestResult.ReturnFailure; if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult FreeLibrary(IntPtr handle) { CurrentTest = String.Format("FreeLibrary({0})", handle); return Run(() => { NativeLibrary.Free(handle); return TestResult.Success; }); } static TestResult GetLibraryExport(IntPtr handle, string name) { CurrentTest = String.Format("GetLibraryExport({0}, {1})", handle, name); return Run(() => { IntPtr address = NativeLibrary.GetExport(handle, name); if (address == null) return TestResult.ReturnNull; if (RunExportedFunction(address, 1, 1) != 2) return TestResult.IncorrectEvaluation; return TestResult.Success; }); } static TestResult TryGetLibraryExport(IntPtr handle, string name) { CurrentTest = String.Format("TryGetLibraryExport({0}, {1})", handle, name); return Run(() => { IntPtr address = IntPtr.Zero; bool success = NativeLibrary.TryGetExport(handle, name, out address); if (!success) return TestResult.ReturnFailure; if (address == null) return TestResult.ReturnNull; if (RunExportedFunction(address, 1, 1) != 2) return TestResult.IncorrectEvaluation; return TestResult.Success; }); } [DllImport("NativeLibrary")] static extern int RunExportedFunction(IntPtr address, int arg1, int arg2); }
//----------------------------------------------------------------------------- // Verve // Copyright (C) - Violent Tulip //----------------------------------------------------------------------------- new ScriptObject( VMotionTrackPropertyList ) { SuperClass = "VEditorPropertyList"; Parent = "VObjectPropertyList"; Group[0] = "VMotionTrack"; Field[0, 0] = "Reference"; Type[0, 0] = "VControllerDataEnum"; Field[0, 1] = "OrientationMode"; Type[0, 1] = "VPathOrientationModeEnum"; Field[0, 2] = "OrientationData"; Field[0, 3] = "Relative"; }; //----------------------------------------------------------------------------- function VMotionTrack::CreateEvent( %this, %canCreateNode ) { if ( %canCreateNode $= "" ) %canCreateNode = true; // Fetch Object References. %object = %this.getParent().getSceneObject(); %path = %this.getPath(); if ( isObject( %object ) && isObject( %path ) ) { // Create Event. %event = new VMotionEvent(); // Create a Node? %createNode = ( %this.getCount() >= %path.getNodeCount() ); if ( !%canCreateNode || !%createNode ) { // Return Event. return %event; } // Use Transform. %transform = %object.getTransform(); // Object Attached? if ( %path.isObjectAttached( %object ) ) { // Get Offset. %positionOffset = %path.getPathObjectOffset( %object ); // Determine Real Position. %newPosition = VectorSub( %object.getPosition(), %positionOffset ); // Set Transform. %transform = %newPosition SPC getWords( %transform, 3 ); } else if ( %this.Relative && %path.getNodeCount() > 0 ) { // Fetch Node Position. %nodePosition = %path.getNodeWorldPosition( 0 ); // Set Position. %object.setTransform( %nodePosition SPC getWords( %transform, 3 ) ); } // Create New Node. %event.schedule( 32, "CreatePathNode", %transform ); // Return Event. return %event; } // No Object. return 0; } function VMotionTrack::OnSelect( %this ) { // Fetch Path. %path = %this.getPath(); if ( !isObject( EVPathEditor ) || !isObject( %path ) ) { // No Editor. return; } // Update Selection. EVPathEditor.setSelection( %path ); } //----------------------------------------------------------------------------- function VMotionTrack::GetContextMenu( %this ) { %contextMenu = $VerveEditor::VMotionTrack::ContextMenu; if ( !isObject( %contextMenu ) ) { %contextMenu = new PopupMenu() { SuperClass = "VerveWindowMenu"; IsPopup = true; Label = "VTrackContextMenu"; Position = 0; Item[0] = "&Add Event" TAB "" TAB "VEditorSelectableTrack::AddEvent();"; Item[1] = "" TAB ""; Item[2] = "&Import Path Nodes" TAB "" TAB "VMotionTrack::ImportPathNodes();"; Item[3] = "" TAB ""; Item[4] = "Cu&t" TAB "" TAB "VerveEditor::CutSelection();"; Item[5] = "&Copy" TAB "" TAB "VerveEditor::CopySelection();"; Item[6] = "&Paste" TAB "" TAB "VEditorSelectableTrack::PasteEvent();"; Item[7] = "" TAB ""; Item[8] = "&Delete" TAB "" TAB "VerveEditor::DeleteSelection();"; AddIndex = 0; PasteIndex = 4; }; %contextMenu.Init(); // Cache. $VerveEditor::VMotionTrack::ContextMenu = %contextMenu; } // Return Menu. return %contextMenu; } function VMotionTrack::ImportPathNodes() { if ( !VerveEditor::HasSelection() ) { // Invalid Selection. return; } %trackObject = $VerveEditor::InspectorObject; if ( !%trackObject.isMemberOfClass( "VMotionTrack" ) ) { // Invalid Selection. return; } // Load the Import Options Dialog. VerveEditorWindow.pushDialog( VerveEditorImportPathNodesGUI ); } function VMotionTrack::_ImportPathNodes( %speed ) { // Awake? if ( VerveEditorImportPathNodesGUI.isAwake() ) { // Close the GUI. VerveEditorWindow.popDialog( VerveEditorImportPathNodesGUI ); } if ( !VerveEditor::HasSelection() ) { // Invalid Selection. return; } %trackObject = $VerveEditor::InspectorObject; if ( !%trackObject.isMemberOfClass( "VMotionTrack" ) ) { // Invalid Selection. return; } // Fetch the Controller. %controller = %trackObject.getRoot(); // Group History Actions. VerveEditor::ToggleHistoryGroup(); // Clear the Track. while( %trackObject.getCount() > 0 ) { // Fetch Object. %event = %trackObject.getObject( 0 ); // Add History Item. %historyObject = new UndoScriptAction() { Class = "VerveEditorHistoryDeleteObject"; SuperClass = "VerveEditorHistoryObject"; ActionName = "Delete Object"; // Store Object References. Parent = %trackObject; Object = %event; }; // Detach Object. %trackObject.removeObject( %event ); } // Fetch the Path. %pathObject = %trackObject.getPath(); // New Duration. %controllerDuration = 0; // Last Event Time. %lastEventTime = 0; // Fetch the Node Count. %nodeCount = %pathObject.getNodeCount(); for ( %i = 0; %i < ( %nodeCount + %controller.Loop ); %i++ ) { // Create a new Event. %newEvent = %trackObject.CreateEvent( false ); if ( %i > 0 ) { // Fetch the Node Length. %nodeLength = %pathObject.getNodeLength( %i - 1 ); // Determine the Trigger Time. %triggerInterval = 1000 * ( %nodeLength / %speed ); // Determine the Trigger Time. %lastEventTime = ( %lastEventTime + %triggerInterval ); // Update Duration. %controllerDuration = %lastEventTime; // Set the Event's Trigger Time. %newEvent.TriggerTime = %lastEventTime; } if ( %i < %nodeCount ) { // Add the Event. %trackObject.addObject( %newEvent ); } // Do Event Callback. %newEvent.OnAdd(); } // Set the Controller Duration. %controller.setFieldValue( "Duration", %controllerDuration ); // Finish Up. VerveEditor::ToggleHistoryGroup(); // Refresh the Editor. VerveEditor::Refresh(); // Set Selection. VerveEditor::SetSelection( %trackObject.Control ); }
using NUnit.Framework; using NDeproxy; namespace NDeproxy.Tests { [TestFixture] class HeaderCollectionConstructorsTest { [Test] public void noArgumentsToTheConstructor() { when: //"call the constructor with no arguments" var hc = new HeaderCollection(); then: //"should be valid, empty collection" Assert.IsNotNull(hc); Assert.IsInstanceOf<HeaderCollection>(hc); Assert.AreEqual(0, hc.size()); } [Test] public void nullArgumentToTheConstructor() { when: //"call the constructor with a single null argument" var hc = new HeaderCollection((object)null); then: //"should be valid, empty collection" Assert.IsNotNull(hc); Assert.IsInstanceOf<HeaderCollection>(hc); Assert.AreEqual(0, hc.size()); } [Test] public void HeaderArgument() { when: HeaderCollection hc = new HeaderCollection(new Header("n1", "v1")); then: Assert.IsNotNull(hc); Assert.AreEqual(1, hc.size()); Assert.AreEqual("n1", hc[0].name); Assert.AreEqual("v1", hc[0].value); } [Test] public void StringArgument() { when: HeaderCollection hc = new HeaderCollection("n1:v1"); then: Assert.IsNotNull(hc); Assert.AreEqual(1, hc.size()); Assert.AreEqual("n1", hc[0].name); Assert.AreEqual("v1", hc[0].value); } [Test] public void StringArgumentLeadingSpaceInName() { when: HeaderCollection hc = new HeaderCollection(" n1:v1"); then: Assert.IsNotNull(hc); Assert.AreEqual(1, hc.size()); Assert.AreEqual("n1", hc[0].name); Assert.AreEqual("v1", hc[0].value); } [Test] public void StringArgumentTrailingSpaceInName() { when: HeaderCollection hc = new HeaderCollection("n1 :v1"); then: Assert.IsNotNull(hc); Assert.AreEqual(1, hc.size()); Assert.AreEqual("n1", hc[0].name); Assert.AreEqual("v1", hc[0].value); } [Test] public void StringArgumentLeadingSpaceInValue() { when: HeaderCollection hc = new HeaderCollection("n1: v1"); then: Assert.IsNotNull(hc); Assert.AreEqual(1, hc.size()); Assert.AreEqual("n1", hc[0].name); Assert.AreEqual("v1", hc[0].value); } [Test] public void StringArgumentTrailingSpaceInValue() { when: HeaderCollection hc = new HeaderCollection("n1:v1 "); then: Assert.IsNotNull(hc); Assert.AreEqual(1, hc.size()); Assert.AreEqual("n1", hc[0].name); Assert.AreEqual("v1", hc[0].value); } [Test] public void StringArgumentSinglePart() { when: HeaderCollection hc = new HeaderCollection("n1"); then: Assert.IsNotNull(hc); Assert.AreEqual(1, hc.size()); Assert.AreEqual("n1", hc[0].name); Assert.AreEqual("", hc[0].value); } [Test] public void StringArgumentThreeParts() { when: HeaderCollection hc = new HeaderCollection("n1: v1: v2"); then: Assert.IsNotNull(hc); Assert.AreEqual(1, hc.size()); Assert.AreEqual("n1", hc[0].name); Assert.AreEqual("v1: v2", hc[0].value); } // [Test] // public void "object argument"() { // // when: // HeaderCollection hc = new HeaderCollection(new DummyObject(id: 3)) // // then: // hc != null // hc.size() == 1 // hc[0].name == "dummy object, id = 3" // hc[0].value == "" // // } // // [Test] // public void "empty list"() { // // when: // HeaderCollection hc = new HeaderCollection([ ]); // // then: // hc != null // hc.size() == 0 // // } // // // [Test] // public void "list with string element"() { // // when: // HeaderCollection hc = new HeaderCollection([ "n1: v1" ]); // // then: // hc != null // hc.size() == 1 // hc[0].name == "n1" // hc[0].value == "v1" // // } // // [Test] // public void "list with null element"() { // // when: // HeaderCollection hc = new HeaderCollection([ // new Header("n1", "v1"), // null, // new Header("n2", "v2") // ]); // // then: // hc != null // hc.size() == 2 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // // } // // [Test] // public void "list of headers argument"() { // // when: "call the constructor with a list of headers" // HeaderCollection hc = new HeaderCollection([ new Header("name1", "value1"), new Header("name2", "value2") ]) // // then: "should be valid collection with the given headers in the given order" // hc != null // hc instanceof HeaderCollection // hc.size() == 2 // hc[0].name == "name1" // hc[0].value == "value1" // hc[1].name == "name2" // hc[1].value == "value2" // } // // [Test] // public void "map argument"() { // // when: // HeaderCollection hc = new HeaderCollection([ // n1: "v1", // n2: "v2", // n3: "v3", // n4: "v4", // ]) // // then: // hc != null // hc.size() == 4 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "n3" // hc[2].value == "v3" // hc[3].name == "n4" // hc[3].value == "v4" // // } // // [Test] // public void "empty map"() { // // when: // HeaderCollection hc = new HeaderCollection([:]) // // then: // hc != null // hc.size() == 0 // // } // // [Test] // public void "map with null key"() { // // when: // HeaderCollection hc = new HeaderCollection([ // n1: "v1", // (null): "v2", // ]) // // then: // hc != null // hc.size() == 2 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "" // hc[1].value == "v2" // // } // // [Test] // public void "map with null value"() { // // when: // HeaderCollection hc = new HeaderCollection([ // n1: "v1", // n2: null, // ]) // // then: // hc != null // hc.size() == 2 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "" // // } // // [Test] // public void "another HeaderCollection as argument"() { // // given: // var hc1 = new HeaderCollection() // hc1.add("n1", "v1") // hc1.add("n2", "v2") // // when: // HeaderCollection hc = new HeaderCollection(hc1) // // then: // hc != null // hc.size() == 2 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // } // // [Test] // public void "empty array"() { // // when: // HeaderCollection hc = new HeaderCollection([] as Object[]); // // then: // hc != null // hc.size() == 0 // // } // // [Test] // public void "array with string element"() { // // when: // HeaderCollection hc = new HeaderCollection([ // "n1: v1", // ] as Object[]); // // then: // hc != null // hc.size() == 1 // hc[0].name == "n1" // hc[0].value == "v1" // // } // // [Test] // public void "array with null element"() { // // when: // HeaderCollection hc = new HeaderCollection([ // new Header("n1", "v1"), // null, // new Header("n2", "v2") // ] as Object[]); // // then: // hc != null // hc.size() == 2 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // // } // // [Test] // public void "array of headers argument"() { // // when: // HeaderCollection hc = new HeaderCollection([ // new Header("n1", "v1"), // new Header("n2", "v2") // ] as Object[]); // // then: // hc != null // hc.size() == 2 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // // } // // [Test] // public void "multiple null arguments"() { // // when: // HeaderCollection hc = new HeaderCollection(null, null, null) // // then: // hc != null // hc.size() == 0 // // } // // [Test] // public void "multiple string arguments"() { // // when: // HeaderCollection hc = new HeaderCollection( // "n1: v1", // "n2: v2", // "n3: v3") // // then: // hc != null // hc.size() == 3 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "n3" // hc[2].value == "v3" // // } // // [Test] // public void "multiple object arguments"() { // // when: // HeaderCollection hc = new HeaderCollection( // new DummyObject(id: 6), // new DummyObject(id: 7), // new DummyObject(id: 8)) // // then: // hc != null // hc.size() == 3 // hc[0].name == "dummy object, id = 6" // hc[0].value == "" // hc[1].name == "dummy object, id = 7" // hc[1].value == "" // hc[2].name == "dummy object, id = 8" // hc[2].value == "" // // } // // [Test] // public void "multiple map arguments"() { // // when: // HeaderCollection hc = new HeaderCollection( // [ n1: "v1", n2: "v2" ], // [ n3: "v3", n4: "v4" ]) // // then: // hc != null // hc.size() == 4 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "n3" // hc[2].value == "v3" // hc[3].name == "n4" // hc[3].value == "v4" // // } // // [Test] // public void "multiple list arguments"() { // // when: // HeaderCollection hc = new HeaderCollection( // [ new Header("n1", "v1"), new Header("n2", "v2") ], // [ new Header("n3", "v3"), new Header("n4", "v4") ], // ) // // then: // hc != null // hc.size() == 4 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "n3" // hc[2].value == "v3" // hc[3].name == "n4" // hc[3].value == "v4" // // } // // [Test] // public void "multiple HeaderCollection arguments"() { // // given: // var hc1 = new HeaderCollection() // hc1.add("n1", "v1") // hc1.add("n2", "v2") // var hc2 = new HeaderCollection() // hc2.add("n3", "v3") // // when: // HeaderCollection hc = new HeaderCollection(hc1, hc2) // // then: // hc != null // hc.size() == 3 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "n3" // hc[2].value == "v3" // // } // // [Test] // public void "multiple mixed arguments"() { // // given: // var hc1 = new HeaderCollection() // hc1.add("n1", "v1") // hc1.add("n2", "v2") // DummyObject dobj = new DummyObject(id: 10) // var str = "is a" // // when: // HeaderCollection hc = new HeaderCollection( // [ new Header("n3", "v3"), new Header("n4", "v4"), "n5: v5" ], // [ n6: "v6", n7: "v7" ], // [ // [ // [ n8: "v8"], // hc1, // ], // [ n9: "v9" ], // dobj, // "Groovy: This ${str} groovy string" // ]) // // then: // hc != null // hc.size() == 11 // hc[0].name == "n3" // hc[0].value == "v3" // hc[1].name == "n4" // hc[1].value == "v4" // hc[2].name == "n5" // hc[2].value == "v5" // hc[3].name == "n6" // hc[3].value == "v6" // hc[4].name == "n7" // hc[4].value == "v7" // hc[5].name == "n8" // hc[5].value == "v8" // hc[6].name == "n1" // hc[6].value == "v1" // hc[7].name == "n2" // hc[7].value == "v2" // hc[8].name == "n9" // hc[8].value == "v9" // hc[9].name == "dummy object, id = 10" // hc[9].value == "" // hc[10].name == "Groovy" // hc[10].value == "This is a groovy string" // } // // [Test] // public void "re-use list argument"() { // // given: // var list = [ new Header("n1", "v1"), new Header("n2", "v2") ] // // when: // HeaderCollection hc = new HeaderCollection(list, "n3: v3", list) // // then: // hc != null // hc.size() == 5 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "n3" // hc[2].value == "v3" // hc[3].name == "n1" // hc[3].value == "v1" // hc[4].name == "n2" // hc[4].value == "v2" // // } // // [Test] // public void "cycle list argument"() { // // given: // var list = [ new Header("n1", "v1"), new Header("n2", "v2") ] // list.add(list) // // when: // HeaderCollection hc = new HeaderCollection(list) // // then: // hc != null // hc.size() == 2 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // // } // // [Test] // public void "re-use map argument"() { // // given: // var map = [ n1: "v1", n2: "v2" ] // // when: // HeaderCollection hc = new HeaderCollection(map, "n3: v3", map) // // then: // hc != null // hc.size() == 5 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "n3" // hc[2].value == "v3" // hc[3].name == "n1" // hc[3].value == "v1" // hc[4].name == "n2" // hc[4].value == "v2" // // } // // [Test] // public void "cycle map argument as name"() { // // given: // var map = [ n1: "v1", n2: "v2" ] // var extras = [ (map): "v3" ] // map.putAll(extras) // // when: // HeaderCollection hc = new HeaderCollection(map) // // then: // hc != null // hc.size() == 3 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "" // hc[2].value == "v3" // // } // // [Test] // public void "cycle map argument as value"() { // // given: // var map = [ n1: "v1", n2: "v2", n3: "v3" ] // map["n3"] = map // // when: // HeaderCollection hc = new HeaderCollection(map) // // then: // hc != null // hc.size() == 3 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "n3" // hc[2].value == map.toString() // // } // // [Test] // public void "re-use array argument"() { // // given: // Object[] arr = [ new Header("n1", "v1"), new Header("n2", "v2") ] // // when: // HeaderCollection hc = new HeaderCollection(arr, "n3: v3", arr) // // then: // hc != null // hc.size() == 5 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // hc[2].name == "n3" // hc[2].value == "v3" // hc[3].name == "n1" // hc[3].value == "v1" // hc[4].name == "n2" // hc[4].value == "v2" // // } // // [Test] // public void "cycle array argument"() { // // given: // Object[] arr = [ new Header("n1", "v1"), new Header("n2", "v2"), null ] // arr[2] = arr // // when: // HeaderCollection hc = new HeaderCollection(arr) // // then: // hc != null // hc.size() == 2 // hc[0].name == "n1" // hc[0].value == "v1" // hc[1].name == "n2" // hc[1].value == "v2" // } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Cassandra.Mapping.Utils; namespace Cassandra.Mapping.Statements { /// <summary> /// A utility class capable of generating CQL statements for a POCO. /// </summary> internal class CqlGenerator { private const string CannotGenerateStatementForPoco = "Cannot create {0} statement for POCO of type {1}"; private const string NoColumns = CannotGenerateStatementForPoco + " because it has no columns"; private const string MissingPkColumns = CannotGenerateStatementForPoco + " because it is missing PK columns {2}. " + "Are you missing a property/field on the POCO or did you forget to specify " + "the PK columns in the mapping?"; private static readonly Regex SelectRegex = new Regex(@"\A\s*SELECT\s", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex FromRegex = new Regex(@"\A\s*FROM\s", RegexOptions.Compiled | RegexOptions.IgnoreCase); private readonly PocoDataFactory _pocoDataFactory; private static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero); public CqlGenerator(PocoDataFactory pocoDataFactory) { if (pocoDataFactory == null) throw new ArgumentNullException("pocoDataFactory"); _pocoDataFactory = pocoDataFactory; } /// <summary> /// Adds "SELECT columnlist" and "FROM tablename" to a CQL statement if they don't already exist for a POCO of Type T. /// </summary> public void AddSelect<T>(Cql cql) { // If it's already got a SELECT clause, just bail if (SelectRegex.IsMatch(cql.Statement)) return; // Get the PocoData so we can generate a list of columns var pocoData = _pocoDataFactory.GetPocoData<T>(); var allColumns = pocoData.Columns.Select(Escape(pocoData)).ToCommaDelimitedString(); // If it's got the from clause, leave FROM intact, otherwise add it cql.SetStatement(FromRegex.IsMatch(cql.Statement) ? string.Format("SELECT {0} {1}", allColumns, cql.Statement) : string.Format("SELECT {0} FROM {1} {2}", allColumns, Escape(pocoData.TableName, pocoData), cql.Statement)); } /// <summary> /// Escapes an identier if necessary /// </summary> private static string Escape(string identifier, PocoData pocoData) { if (!pocoData.CaseSensitive) { return identifier; } return "\"" + identifier + "\""; } private static Func<PocoColumn, string> Escape(PocoData pocoData) { Func<PocoColumn, string> f = c => Escape(c.ColumnName, pocoData); return f; } private static Func<PocoColumn, string> Escape(PocoData pocoData, string format) { Func<PocoColumn, string> f = c => String.Format(format, Escape(c.ColumnName, pocoData)); return f; } /// <summary> /// Generates an "INSERT INTO tablename (columns) VALUES (?...)" statement for a POCO of Type T. /// </summary> /// <param name="insertNulls">When set to <c>true</c>, it will only generate columns which POCO members are not null</param> /// <param name="pocoValues">The parameters of this query, it will only be used if <c>insertNulls</c> is set to <c>true</c></param> /// <param name="queryParameters">The parameters for this query. When insertNulls is <c>true</c>, the <c>pocoValues</c> /// is the <c>queryParameters</c>, when set to <c>false</c> the <c>queryParameters do not include <c>null</c> values</c></param> /// <param name="ifNotExists">Determines if it should add the IF NOT EXISTS at the end of the query</param> /// <param name="ttl">Amount of seconds for the data to expire (TTL)</param> /// <param name="timestamp">Data timestamp</param> /// <param name="tableName">Table name. If null, it will use table name based on Poco Data</param> /// <returns></returns> public string GenerateInsert<T>(bool insertNulls, object[] pocoValues, out object[] queryParameters, bool ifNotExists = false, int? ttl = null, DateTimeOffset? timestamp = null, string tableName = null) { var pocoData = _pocoDataFactory.GetPocoData<T>(); if (pocoData.Columns.Count == 0) { throw new InvalidOperationException(string.Format(NoColumns, "INSERT", typeof(T).Name)); } string columns; string placeholders; var parameterList = new List<object>(); if (!insertNulls) { if (pocoValues == null) { throw new ArgumentNullException("pocoValues"); } if (pocoValues.Length != pocoData.Columns.Count) { throw new ArgumentException("Values array should contain the same amount of items as POCO columns"); } //only include columns which value is not null var columnsBuilder = new StringBuilder(); var placeholdersBuilder = new StringBuilder(); for (var i = 0; i < pocoData.Columns.Count; i++) { var value = pocoValues[i]; if (value == null) { continue; } if (i > 0) { columnsBuilder.Append(", "); placeholdersBuilder.Append(", "); } columnsBuilder.Append(Escape(pocoData)(pocoData.Columns[i])); placeholdersBuilder.Append("?"); parameterList.Add(value); } columns = columnsBuilder.ToString(); placeholders = placeholdersBuilder.ToString(); } else { //Include all columns defined in the Poco columns = pocoData.Columns.Select(Escape(pocoData)).ToCommaDelimitedString(); placeholders = Enumerable.Repeat("?", pocoData.Columns.Count).ToCommaDelimitedString(); parameterList.AddRange(pocoValues); } var queryBuilder = new StringBuilder(); queryBuilder.Append("INSERT INTO "); queryBuilder.Append(tableName ?? Escape(pocoData.TableName, pocoData)); queryBuilder.Append(" ("); queryBuilder.Append(columns); queryBuilder.Append(") VALUES ("); queryBuilder.Append(placeholders); queryBuilder.Append(")"); if (ifNotExists) { queryBuilder.Append(" IF NOT EXISTS"); } if (ttl != null || timestamp != null) { queryBuilder.Append(" USING"); if (ttl != null) { queryBuilder.Append(" TTL ?"); parameterList.Add(ttl.Value); if (timestamp != null) { queryBuilder.Append(" AND"); } } if (timestamp != null) { queryBuilder.Append(" TIMESTAMP ?"); parameterList.Add((timestamp.Value - UnixEpoch).Ticks / 10); } } queryParameters = parameterList.ToArray(); return queryBuilder.ToString(); } /// <summary> /// Generates an "UPDATE tablename SET columns = ? WHERE pkColumns = ?" statement for a POCO of Type T. /// </summary> public string GenerateUpdate<T>() { var pocoData = _pocoDataFactory.GetPocoData<T>(); if (pocoData.Columns.Count == 0) throw new InvalidOperationException(string.Format(NoColumns, "UPDATE", typeof(T).Name)); if (pocoData.MissingPrimaryKeyColumns.Count > 0) { throw new InvalidOperationException(string.Format(MissingPkColumns, "UPDATE", typeof(T).Name, pocoData.MissingPrimaryKeyColumns.ToCommaDelimitedString())); } var nonPkColumns = pocoData.GetNonPrimaryKeyColumns().Select(Escape(pocoData, "{0} = ?")).ToCommaDelimitedString(); var pkColumns = string.Join(" AND ", pocoData.GetPrimaryKeyColumns().Select(Escape(pocoData, "{0} = ?"))); return string.Format("UPDATE {0} SET {1} WHERE {2}", Escape(pocoData.TableName, pocoData), nonPkColumns, pkColumns); } /// <summary> /// Prepends the CQL statement specified with "UPDATE tablename " for a POCO of Type T. /// </summary> public void PrependUpdate<T>(Cql cql) { var pocoData = _pocoDataFactory.GetPocoData<T>(); cql.SetStatement(string.Format("UPDATE {0} {1}", Escape(pocoData.TableName, pocoData), cql.Statement)); } /// <summary> /// Generates a "DELETE FROM tablename WHERE pkcolumns = ?" statement for a POCO of Type T. /// </summary> public string GenerateDelete<T>() { var pocoData = _pocoDataFactory.GetPocoData<T>(); if (pocoData.Columns.Count == 0) { throw new InvalidOperationException(string.Format(NoColumns, "DELETE", typeof(T).Name)); } if (pocoData.MissingPrimaryKeyColumns.Count > 0) { throw new InvalidOperationException(string.Format(MissingPkColumns, "DELETE", typeof(T).Name, pocoData.MissingPrimaryKeyColumns.ToCommaDelimitedString())); } var pkColumns = String.Join(" AND ", pocoData.GetPrimaryKeyColumns().Select(Escape(pocoData, "{0} = ?"))); return string.Format("DELETE FROM {0} WHERE {1}", Escape(pocoData.TableName, pocoData), pkColumns); } /// <summary> /// Prepends the CQL statement specified with "DELETE FROM tablename " for a POCO of Type T. /// </summary> public void PrependDelete<T>(Cql cql) { PocoData pocoData = _pocoDataFactory.GetPocoData<T>(); cql.SetStatement(string.Format("DELETE FROM {0} {1}", pocoData.TableName, cql.Statement)); } private static string GetTypeString(PocoColumn column) { if (column.IsCounter) { return "counter"; } IColumnInfo typeInfo; var typeCode = TypeCodec.GetColumnTypeCodeInfo(column.ColumnType, out typeInfo); var typeName = GetTypeString(column, typeCode, typeInfo); if (column.IsStatic) { return typeName + " static"; } return typeName; } /// <summary> /// Gets the CQL queries involved in a table creation (CREATE TABLE, CREATE INDEX) /// </summary> public static List<string> GetCreate(PocoData pocoData, string tableName, string keyspaceName, bool ifNotExists) { if (pocoData == null) { throw new ArgumentNullException("pocoData"); } if (pocoData.MissingPrimaryKeyColumns.Count > 0) { throw new InvalidOperationException(string.Format(MissingPkColumns, "CREATE", pocoData.PocoType.Name, pocoData.MissingPrimaryKeyColumns.ToCommaDelimitedString())); } var commands = new List<string>(); var secondaryIndexes = new List<string>(); var createTable = new StringBuilder("CREATE TABLE "); tableName = Escape(tableName, pocoData); if (keyspaceName != null) { //Use keyspace.tablename notation tableName = Escape(keyspaceName, pocoData) + "." + tableName; } createTable.Append(tableName); createTable.Append(" ("); foreach (var column in pocoData.Columns) { var columnName = Escape(column.ColumnName, pocoData); createTable .Append(columnName) .Append(" "); var columnType = GetTypeString(column); createTable .Append(columnType); createTable .Append(", "); if (column.SecondaryIndex) { secondaryIndexes.Add(columnName); } } createTable.Append("PRIMARY KEY ("); if (pocoData.PartitionKeys.Count == 0) { throw new InvalidOperationException("No partition key defined"); } if (pocoData.PartitionKeys.Count == 1) { createTable.Append(Escape(pocoData.PartitionKeys[0].ColumnName, pocoData)); } else { //tupled partition keys createTable .Append("(") .Append(String.Join(", ", pocoData.PartitionKeys.Select(Escape(pocoData)))) .Append(")"); } if (pocoData.ClusteringKeys.Count > 0) { createTable.Append(", "); createTable.Append(String.Join(", ", pocoData.ClusteringKeys.Select(k => Escape(k.Item1.ColumnName, pocoData)))); } //close primary keys createTable.Append(")"); //close table column definition createTable.Append(")"); var clusteringOrder = String.Join(", ", pocoData.ClusteringKeys .Where(k => k.Item2 != SortOrder.Unspecified) .Select(k => Escape(k.Item1.ColumnName, pocoData) + " " + (k.Item2 == SortOrder.Ascending ? "ASC" : "DESC"))); if (!String.IsNullOrEmpty(clusteringOrder)) { createTable .Append(" WITH CLUSTERING ORDER BY (") .Append(clusteringOrder) .Append(")"); } if (pocoData.CompactStorage) { createTable.Append(" WITH COMPACT STORAGE"); } commands.Add(createTable.ToString()); //Secondary index definitions commands.AddRange(secondaryIndexes.Select(name => "CREATE INDEX ON " + tableName + " (" + name + ")")); return commands; } private static string GetTypeString(PocoColumn column, ColumnTypeCode typeCode, IColumnInfo typeInfo) { if (typeInfo == null) { //Is a single type return typeCode.ToString().ToLower(); } string typeName = null; var frozenKey = column != null && column.HasFrozenKey; var frozenValue = column != null && column.HasFrozenValue; if (typeInfo is MapColumnInfo) { var mapInfo = (MapColumnInfo) typeInfo; typeName = "map<" + WrapFrozen(frozenKey, GetTypeString(null, mapInfo.KeyTypeCode, mapInfo.KeyTypeInfo)) + ", " + WrapFrozen(frozenValue, GetTypeString(null, mapInfo.ValueTypeCode, mapInfo.ValueTypeInfo)) + ">"; } else if (typeInfo is SetColumnInfo) { var setInfo = (SetColumnInfo) typeInfo; typeName = "set<" + WrapFrozen(frozenKey, GetTypeString(null, setInfo.KeyTypeCode, setInfo.KeyTypeInfo)) + ">"; } else if (typeInfo is ListColumnInfo) { var setInfo = (ListColumnInfo) typeInfo; typeName = "list<" + WrapFrozen(frozenValue, GetTypeString(null, setInfo.ValueTypeCode, setInfo.ValueTypeInfo)) + ">"; } else if (typeInfo is TupleColumnInfo) { var tupleInfo = (TupleColumnInfo) typeInfo; typeName = "tuple<" + string.Join(", ", tupleInfo.Elements.Select(e => GetTypeString(null, e.TypeCode, e.TypeInfo))) + ">"; } else if (typeInfo is UdtColumnInfo) { var udtInfo = (UdtColumnInfo) typeInfo; typeName = udtInfo.Name; } if (typeName == null) { throw new NotSupportedException(string.Format("Type {0} is not supported", typeCode)); } return WrapFrozen(column != null && column.IsFrozen, typeName); } private static string WrapFrozen(bool condition, string typeName) { if (condition) { return "frozen<" + typeName + ">"; } return typeName; } } }
/* * PROPRIETARY INFORMATION. This software is proprietary to * Side Effects Software Inc., and is not to be reproduced, * transmitted, or disclosed in any way without written permission. * * Produced by: * Side Effects Software Inc * 123 Front Street West, Suite 1401 * Toronto, Ontario * Canada M5J 2M2 * 416-504-9876 * * COMMENTS: * Contains main HAPI API constants and structures. * */ using UnityEngine; using System; using System.Collections; using System.Runtime.InteropServices; // Typedefs using HAPI_SessionId = System.Int64; using HAPI_StringHandle = System.Int32; using HAPI_AssetLibraryId = System.Int32; using HAPI_AssetId = System.Int32; using HAPI_NodeId = System.Int32; using HAPI_ParmId = System.Int32; using HAPI_ObjectId = System.Int32; using HAPI_GeoId = System.Int32; using HAPI_PartId = System.Int32; using HAPI_MaterialId = System.Int32; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Defines public struct HoudiniConstants { // Unity-Only Constants --------------------------------------------- // // You may change these values if you wish. Nothing should break terribly. public const string HAPI_PRODUCT_NAME = "Houdini Engine"; // Used for things like window titles that have limited space. public const string HAPI_PRODUCT_SHORT_NAME = "Houdini"; public static string HAPI_TEXTURES_PATH = Application.dataPath + "/Textures"; public static string HAPI_BAKED_ASSETS_PATH = Application.dataPath + "/Baked Assets"; public const int HAPI_MAX_PAGE_SIZE = 20000; public const int HAPI_SEC_BEFORE_PROGRESS_BAR_SHOW = 3; public const int HAPI_MIN_VERTICES_PER_FACE = 3; public const int HAPI_MAX_VERTICES_PER_FACE = 3; public const bool HAPI_CURVE_REFINE_TO_LINEAR = true; public const float HAPI_CURVE_LOD = 8.0f; public const float HAPI_VOLUME_POSITION_MULT = 2.0f; public const float HAPI_VOLUME_SURFACE_MAX_PT_PER_C = 64000; // Max points per container. 65000 is Unity max. public const float HAPI_VOLUME_SURFACE_DELTA_MULT = 1.2f; public const float HAPI_VOLUME_SURFACE_PT_SIZE_MULT = 1800.0f; // Shared Constants ------------------------------------------------- // // IMPORTANT: Changes to these constants will not change the behavior of the // underlying Houdini Engine. These are here to serve as C# duplicates of the // constants defined in the HAPI_Common.h C++ header. In fact, if you // change any of these you will most likely break the Unity plugin. public const int HAPI_POSITION_VECTOR_SIZE = 3; public const int HAPI_SCALE_VECTOR_SIZE = 3; public const int HAPI_NORMAL_VECTOR_SIZE = 3; public const int HAPI_QUATERNION_VECTOR_SIZE = 4; public const int HAPI_EULER_VECTOR_SIZE = 3; public const int HAPI_UV_VECTOR_SIZE = 2; public const int HAPI_COLOR_VECTOR_SIZE = 4; public const int HAPI_CV_VECTOR_SIZE = 4; public const int HAPI_PRIM_MIN_VERTEX_COUNT = 1; public const int HAPI_PRIM_MAX_VERTEX_COUNT = 16; public const int HAPI_INVALID_PARM_ID = -1; // Default Attributes' Names public const string HAPI_ATTRIB_POSITION = "P"; public const string HAPI_ATTRIB_UV = "uv"; public const string HAPI_ATTRIB_UV2 = "uv2"; public const string HAPI_ATTRIB_UV3 = "uv3"; public const string HAPI_ATTRIB_NORMAL = "N"; public const string HAPI_ATTRIB_TANGENT = "tangentu"; public const string HAPI_ATTRIB_COLOR = "Cd"; public const string HAPI_UNGROUPED_GROUP_NAME = "__ungrouped_group"; // Common image file format names (to use with the material extract APIs). // Note that you may still want to check if they are supported via // HAPI_GetSupportedImageFileFormats() since all formats are loaded // dynamically by Houdini on-demand so just because these formats are defined // here doesn't mean they are supported in your instance. public const string HAPI_RAW_FORMAT_NAME = "HAPI_RAW"; // HAPI-only Raw Format public const string HAPI_PNG_FORMAT_NAME = "PNG"; public const string HAPI_JPEG_FORMAT_NAME = "JPEG"; public const string HAPI_BMP_FORMAT_NAME = "Bitmap"; public const string HAPI_TIFF_FORMAT_NAME = "TIFF"; public const string HAPI_TGA_FORMAT_NAME = "Targa"; // Default image file format's name - used when the image generated and has // no "original" file format and the user does not specify a format to // convert to. public const string HAPI_DEFAULT_IMAGE_FORMAT_NAME = HAPI_PNG_FORMAT_NAME; /// Name of subnet OBJ node containing the global nodes. public const string HAPI_GLOBAL_NODES_NODE_NAME = "GlobalNodes"; /// Common cache names. You can see these same cache names in the /// Cache Manager window in Houdini (Windows > Cache Manager). public const string HAPI_CACHE_COP_COOK = "COP Cook Cache"; public const string HAPI_CACHE_COP_FLIPBOOK = "COP Flipbook Cache"; public const string HAPI_CACHE_IMAGE = "Image Cache"; public const string HAPI_CACHE_OBJ = "Object Transform Cache"; public const string HAPI_CACHE_GL_TEXTURE = "OpenGL Texture Cache"; public const string HAPI_CACHE_GL_VERTEX = "OpenGL Vertex Cache"; public const string HAPI_CACHE_SOP = "SOP Cache"; public const string HAPI_CACHE_VEX = "VEX File Cache"; public const string HAPI_UNSUPPORTED_PLATFORM_MSG = "Houdini Plugin for Unity currently only supports the Standalone Windows and Mac OS X platforms in Editor.\n" + "\n" + "To switch to the Standalone Windows platform go to File > Build Settings... and under 'Platform' " + "choose 'PC, Mac & Linux Standalone' and click 'Switch Platform'. Afterwards, on the right hand side, " + "under 'Target Platform' choose 'Windows' or 'Mac OS X'.\n" + "\n" + "When you switch back to the Standalone Windows or Mac platform you might need to Rebuild each asset to get back " + "the controls. Just click on the 'Rebuild' button in the Houdini Asset's Inspector."; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Enums public enum HAPI_License { HAPI_LICENSE_NONE, HAPI_LICENSE_HOUDINI_ENGINE, HAPI_LICENSE_HOUDINI, HAPI_LICENSE_HOUDINI_FX, HAPI_LICENSE_HOUDINI_ENGINE_INDIE, HAPI_LICENSE_HOUDINI_INDIE, HAPI_LICENSE_MAX }; public enum HAPI_StatusType { HAPI_STATUS_CALL_RESULT, HAPI_STATUS_COOK_RESULT, HAPI_STATUS_COOK_STATE, HAPI_STATUS_MAX }; public enum HAPI_StatusVerbosity { HAPI_STATUSVERBOSITY_0, HAPI_STATUSVERBOSITY_1, HAPI_STATUSVERBOSITY_2, HAPI_STATUSVERBOSITY_ALL = HAPI_STATUSVERBOSITY_2, /// Used for Results. /// @{ HAPI_STATUSVERBOSITY_ERRORS = HAPI_STATUSVERBOSITY_0, HAPI_STATUSVERBOSITY_WARNINGS = HAPI_STATUSVERBOSITY_1, HAPI_STATUSVERBOSITY_MESSAGES = HAPI_STATUSVERBOSITY_2 /// @} }; public enum HAPI_Result { HAPI_RESULT_SUCCESS = 0, HAPI_RESULT_FAILURE = 1, HAPI_RESULT_ALREADY_INITIALIZED = 2, HAPI_RESULT_NOT_INITIALIZED = 3, HAPI_RESULT_CANT_LOADFILE = 4, HAPI_RESULT_PARM_SET_FAILED = 5, HAPI_RESULT_INVALID_ARGUMENT = 6, HAPI_RESULT_CANT_LOAD_GEO = 7, HAPI_RESULT_CANT_GENERATE_PRESET = 8, HAPI_RESULT_CANT_LOAD_PRESET = 9, HAPI_RESULT_ASSET_DEF_ALREADY_LOADED = 10, HAPI_RESULT_NO_LICENSE_FOUND = 110, HAPI_RESULT_DISALLOWED_NC_LICENSE_FOUND = 120, HAPI_RESULT_DISALLOWED_NC_ASSET_WITH_C_LICENSE = 130, HAPI_RESULT_DISALLOWED_NC_ASSET_WITH_LC_LICENSE = 140, HAPI_RESULT_DISALLOWED_LC_ASSET_WITH_C_LICENSE = 150, HAPI_RESULT_DISALLOWED_HENGINEINDIE_W_3PARTY_PLUGIN = 160, HAPI_RESULT_ASSET_INVALID = 200, HAPI_RESULT_NODE_INVALID = 210, HAPI_RESULT_USER_INTERRUPTED = 300, HAPI_RESULT_INVALID_SESSION = 400 }; public enum HAPI_SessionType { HAPI_SESSION_INPROCESS, HAPI_SESSION_THRIFT, HAPI_SESSION_CUSTOM1, HAPI_SESSION_CUSTOM2, HAPI_SESSION_CUSTOM3, HAPI_SESSION_MAX }; public enum HAPI_State { HAPI_STATE_READY, HAPI_STATE_READY_WITH_FATAL_ERRORS, HAPI_STATE_READY_WITH_COOK_ERRORS, HAPI_STATE_STARTING_COOK, HAPI_STATE_COOKING, HAPI_STATE_STARTING_LOAD, HAPI_STATE_LOADING, HAPI_STATE_MAX, HAPI_STATE_MAX_READY_STATE = HAPI_STATE_READY_WITH_COOK_ERRORS }; public enum HAPI_PackedPrimInstancingMode { HAPI_PACKEDPRIM_INSTANCING_MODE_INVALID = -1, HAPI_PACKEDPRIM_INSTANCING_MODE_DISABLED, HAPI_PACKEDPRIM_INSTANCING_MODE_HIERARCHY, HAPI_PACKEDPRIM_INSTANCING_MODE_FLAT, HAPI_PACKEDPRIM_INSTANCING_MODE_MAX }; public enum HAPI_Permissions { HAPI_PERMISSIONS_NON_APPLICABLE, HAPI_PERMISSIONS_READ_WRITE, HAPI_PERMISSIONS_READ_ONLY, HAPI_PERMISSIONS_WRITE_ONLY, HAPI_PERMISSIONS_MAX }; public enum HAPI_RampType { HAPI_RAMPTYPE_INVALID = -1, HAPI_RAMPTYPE_FLOAT = 0, HAPI_RAMPTYPE_COLOR, HAPI_RAMPTYPE_MAX }; public enum HAPI_ParmType { HAPI_PARMTYPE_INT = 0, HAPI_PARMTYPE_MULTIPARMLIST, HAPI_PARMTYPE_TOGGLE, HAPI_PARMTYPE_BUTTON, HAPI_PARMTYPE_FLOAT, HAPI_PARMTYPE_COLOR, HAPI_PARMTYPE_STRING, HAPI_PARMTYPE_PATH_FILE, HAPI_PARMTYPE_PATH_FILE_GEO, HAPI_PARMTYPE_PATH_FILE_IMAGE, HAPI_PARMTYPE_PATH_NODE, HAPI_PARMTYPE_FOLDERLIST, HAPI_PARMTYPE_FOLDER, HAPI_PARMTYPE_LABEL, HAPI_PARMTYPE_SEPARATOR, // Helpers HAPI_PARMTYPE_MAX, // Total number of supported parameter types. HAPI_PARMTYPE_INT_START = HAPI_PARMTYPE_INT, HAPI_PARMTYPE_INT_END = HAPI_PARMTYPE_BUTTON, HAPI_PARMTYPE_FLOAT_START = HAPI_PARMTYPE_FLOAT, HAPI_PARMTYPE_FLOAT_END = HAPI_PARMTYPE_COLOR, HAPI_PARMTYPE_STRING_START = HAPI_PARMTYPE_STRING, HAPI_PARMTYPE_STRING_END = HAPI_PARMTYPE_PATH_NODE, HAPI_PARMTYPE_PATH_START = HAPI_PARMTYPE_PATH_FILE, HAPI_PARMTYPE_PATH_END = HAPI_PARMTYPE_PATH_NODE, HAPI_PARMTYPE_PATH_FILE_START = HAPI_PARMTYPE_PATH_FILE, HAPI_PARMTYPE_PATH_FILE_END = HAPI_PARMTYPE_PATH_FILE_IMAGE, HAPI_PARMTYPE_PATH_NODE_START = HAPI_PARMTYPE_PATH_NODE, HAPI_PARMTYPE_PATH_NODE_END = HAPI_PARMTYPE_PATH_NODE, HAPI_PARMTYPE_CONTAINER_START = HAPI_PARMTYPE_FOLDERLIST, HAPI_PARMTYPE_CONTAINER_END = HAPI_PARMTYPE_FOLDERLIST, HAPI_PARMTYPE_NONVALUE_START = HAPI_PARMTYPE_FOLDER, HAPI_PARMTYPE_NONVALUE_END = HAPI_PARMTYPE_SEPARATOR } public enum HAPI_ChoiceListType { HAPI_CHOICELISTTYPE_NONE, HAPI_CHOICELISTTYPE_NORMAL, HAPI_CHOICELISTTYPE_MINI, HAPI_CHOICELISTTYPE_REPLACE, HAPI_CHOICELISTTYPE_TOGGLE }; public enum HAPI_PresetType { HAPI_PRESETTYPE_INVALID = -1, HAPI_PRESETTYPE_BINARY = 0, HAPI_PRESETTYPE_IDX, HAPI_PRESETTYPE_MAX }; public enum HAPI_AssetType { HAPI_ASSETTYPE_INVALID = -1, HAPI_ASSETTYPE_OBJ = 0, HAPI_ASSETTYPE_SOP, HAPI_ASSETTYPE_POPNET, HAPI_ASSETTYPE_POP, HAPI_ASSETTYPE_CHOPNET, HAPI_ASSETTYPE_CHOP, HAPI_ASSETTYPE_ROP, HAPI_ASSETTYPE_SHOP, HAPI_ASSETTYPE_COP2, HAPI_ASSETTYPE_COPNET, HAPI_ASSETTYPE_VOP, HAPI_ASSETTYPE_VOPNET, HAPI_ASSETTYPE_DOP, HAPI_ASSETTYPE_MGR, HAPI_ASSETTYPE_DIR, HAPI_ASSETTYPE_MAX } public enum HAPI_AssetSubType { HAPI_ASSETSUBTYPE_INVALID = -1, HAPI_ASSETSUBTYPE_DEFAULT, HAPI_ASSETSUBTYPE_CURVE, HAPI_ASSETSUBTYPE_INPUT, HAPI_ASSETSUBTYPE_MAX } public enum HAPI_GroupType { HAPI_GROUPTYPE_INVALID = -1, HAPI_GROUPTYPE_POINT, HAPI_GROUPTYPE_PRIM, HAPI_GROUPTYPE_MAX } public enum HAPI_AttributeOwner { HAPI_ATTROWNER_INVALID = -1, HAPI_ATTROWNER_VERTEX, HAPI_ATTROWNER_POINT, HAPI_ATTROWNER_PRIM, HAPI_ATTROWNER_DETAIL, HAPI_ATTROWNER_MAX } public enum HAPI_CurveType { HAPI_CURVETYPE_INVALID = -1, HAPI_CURVETYPE_LINEAR, HAPI_CURVETYPE_NURBS, HAPI_CURVETYPE_BEZIER, HAPI_CURVETYPE_MAX } public enum HAPI_VolumeType { HAPI_VOLUMETYPE_INVALID = -1, HAPI_VOLUMETYPE_HOUDINI, HAPI_VOLUMETYPE_VDB, HAPI_VOLUMETYPE_MAX } public enum HAPI_StorageType { HAPI_STORAGETYPE_INVALID = -1, HAPI_STORAGETYPE_INT, HAPI_STORAGETYPE_FLOAT, HAPI_STORAGETYPE_STRING, HAPI_STORAGETYPE_MAX } public enum HAPI_GeoType { HAPI_GEOTYPE_INVALID = -1, HAPI_GEOTYPE_DEFAULT, HAPI_GEOTYPE_INTERMEDIATE, HAPI_GEOTYPE_INPUT, HAPI_GEOTYPE_CURVE, HAPI_GEOTYPE_MAX }; public enum HAPI_PartType { HAPI_PARTTYPE_INVALID = -1, HAPI_PARTTYPE_MESH, HAPI_PARTTYPE_CURVE, HAPI_PARTTYPE_VOLUME, HAPI_PARTTYPE_INSTANCER, HAPI_PARTTYPE_MAX }; public enum HAPI_InputType { HAPI_INPUT_INVALID = -1, HAPI_INPUT_TRANSFORM, HAPI_INPUT_GEOMETRY, HAPI_INPUT_MAX }; public enum HAPI_CurveOrders { HAPI_CURVE_ORDER_VARYING = 0, HAPI_CURVE_ORDER_INVALID = 1, HAPI_CURVE_ORDER_LINEAR = 2, HAPI_CURVE_ORDER_QUADRATIC = 3, HAPI_CURVE_ORDER_CUBIC = 4, } public enum HAPI_TransformComponent { HAPI_TRANSFORM_TX = 0, HAPI_TRANSFORM_TY, HAPI_TRANSFORM_TZ, HAPI_TRANSFORM_RX, HAPI_TRANSFORM_RY, HAPI_TRANSFORM_RZ, HAPI_TRANSFORM_QX, HAPI_TRANSFORM_QY, HAPI_TRANSFORM_QZ, HAPI_TRANSFORM_QW, HAPI_TRANSFORM_SX, HAPI_TRANSFORM_SY, HAPI_TRANSFORM_SZ }; public enum HAPI_RSTOrder { HAPI_TRS = 0, HAPI_TSR, HAPI_RTS, HAPI_RST, HAPI_STR, HAPI_SRT, HAPI_RSTORDER_DEFAULT = HAPI_SRT } public enum HAPI_XYZOrder { HAPI_XYZ = 0, HAPI_XZY, HAPI_YXZ, HAPI_YZX, HAPI_ZXY, HAPI_ZYX, HAPI_XYZORDER_DEFAULT = HAPI_XYZ } public enum HAPI_ImageDataFormat { HAPI_IMAGE_DATA_UNKNOWN = -1, HAPI_IMAGE_DATA_INT8, HAPI_IMAGE_DATA_INT16, HAPI_IMAGE_DATA_INT32, HAPI_IMAGE_DATA_FLOAT16, HAPI_IMAGE_DATA_FLOAT32, HAPI_IMAGE_DATA_MAX }; public enum HAPI_ImagePacking { HAPI_IMAGE_PACKING_UNKNOWN = -1, HAPI_IMAGE_PACKING_SINGLE, // Single Channel HAPI_IMAGE_PACKING_DUAL, // Dual Channel HAPI_IMAGE_PACKING_RGB, // RGB HAPI_IMAGE_PACKING_BGR, // RGB Reveresed HAPI_IMAGE_PACKING_RGBA, // RGBA HAPI_IMAGE_PACKING_ABGR, // RGBA Reversed HAPI_IMAGE_PACKING_MAX, HAPI_IMAGE_PACKING_DEFAULT3 = HAPI_IMAGE_PACKING_RGB, HAPI_IMAGE_PACKING_DEFAULT4 = HAPI_IMAGE_PACKING_RGBA }; public enum HAPI_EnvIntType { HAPI_ENVINT_INVALID = -1, // The three components of the Houdini version that HAPI is // expecting to compile against. HAPI_ENVINT_VERSION_HOUDINI_MAJOR = 100, HAPI_ENVINT_VERSION_HOUDINI_MINOR = 110, HAPI_ENVINT_VERSION_HOUDINI_BUILD = 120, HAPI_ENVINT_VERSION_HOUDINI_PATCH = 130, // The two components of the Houdini Engine (marketed) version. HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MAJOR = 200, HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MINOR = 210, // This is a monotonously increasing API version number that can be used // to lock against a certain API for compatibility purposes. Basically, // when this number changes code compiled against the h methods // might no longer compile. Semantic changes to the methods will also // cause this version to increase. This number will be reset to 0 // every time the Houdini Engine version is bumped. HAPI_ENVINT_VERSION_HOUDINI_ENGINE_API = 220, HAPI_ENVINT_MAX, }; public enum HAPI_SessionEnvIntType { HAPI_SESSIONENVINT_INVALID = -1, /// License Type. See ::HAPI_License. HAPI_SESSIONENVINT_LICENSE = 100, HAPI_SESSIONENVINT_MAX, }; public enum HAPI_CacheProperty { /// Current memory usage in MB. Setting this to 0 invokes /// a cache clear. HAPI_CACHEPROP_CURRENT, HAPI_CACHEPROP_HAS_MIN, // True if it actually has a minimum size. HAPI_CACHEPROP_MIN, // Min cache memory limit in MB. HAPI_CACHEPROP_HAS_MAX, // True if it actually has a maximum size. HAPI_CACHEPROP_MAX, // Max cache memory limit in MB. /// How aggressive to cull memory. This only works for: /// - ::HAPI_CACHE_COP_COOK where: /// 0 -> Never reduce inactive cache. /// 1 -> Always reduce inactive cache. /// - ::HAPI_CACHE_OBJ where: /// 0 -> Never enforce the max memory limit. /// 1 -> Always enforce the max memory limit. /// - ::HAPI_CACHE_SOP where: /// 0 -> When to Unload = Never /// When to Limit Max Memory = Never /// 1-2 -> When to Unload = Based on Flag /// When to Limit Max Memory = Never /// 3-4 -> When to Unload = Based on Flag /// When to Limit Max Memory = Always /// 5 -> When to Unload = Always /// When to Limit Max Memory = Always HAPI_CACHEPROP_CULL_LEVEL, }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Main API Structs // GENERICS ----------------------------------------------------------------------------------------------------- [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_Transform { public HAPI_Transform( bool initialize_fields ) { position = new float[ HoudiniConstants.HAPI_POSITION_VECTOR_SIZE ]; rotationQuaternion = new float[ HoudiniConstants.HAPI_QUATERNION_VECTOR_SIZE ]; scale = new float[ HoudiniConstants.HAPI_SCALE_VECTOR_SIZE ]; rstOrder = HAPI_RSTOrder.HAPI_SRT; } [ MarshalAs( UnmanagedType.ByValArray, SizeConst = HoudiniConstants.HAPI_POSITION_VECTOR_SIZE, ArraySubType = UnmanagedType.R4 ) ] public float[] position; [ MarshalAs( UnmanagedType.ByValArray, SizeConst = HoudiniConstants.HAPI_QUATERNION_VECTOR_SIZE, ArraySubType = UnmanagedType.R4 ) ] public float[] rotationQuaternion; [ MarshalAs( UnmanagedType.ByValArray, SizeConst = HoudiniConstants.HAPI_SCALE_VECTOR_SIZE, ArraySubType = UnmanagedType.R4 ) ] public float[] scale; public HAPI_RSTOrder rstOrder; } [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_TransformEuler { public HAPI_TransformEuler( bool initialize_fields ) { position = new float[ HoudiniConstants.HAPI_POSITION_VECTOR_SIZE ]; rotationEuler = new float[ HoudiniConstants.HAPI_EULER_VECTOR_SIZE ]; scale = new float[ HoudiniConstants.HAPI_SCALE_VECTOR_SIZE ]; rotationOrder = 0; rstOrder = 0; } [ MarshalAs( UnmanagedType.ByValArray, SizeConst = HoudiniConstants.HAPI_POSITION_VECTOR_SIZE, ArraySubType = UnmanagedType.R4 ) ] public float[] position; [ MarshalAs( UnmanagedType.ByValArray, SizeConst = HoudiniConstants.HAPI_EULER_VECTOR_SIZE, ArraySubType = UnmanagedType.R4 ) ] public float[] rotationEuler; [ MarshalAs( UnmanagedType.ByValArray, SizeConst = HoudiniConstants.HAPI_SCALE_VECTOR_SIZE, ArraySubType = UnmanagedType.R4 ) ] public float[] scale; public HAPI_XYZOrder rotationOrder; public HAPI_RSTOrder rstOrder; } // SESSIONS ----------------------------------------------------------------------------------------------------- [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_Session { /// The type of session detemines the which implementation will be /// used to communicate with the Houdini Engine library. public HAPI_SessionType type; /// Some session types support multiple simultanous sessions. This means /// that each session needs to have a unique identified. public HAPI_SessionId id; }; // TIME --------------------------------------------------------------------------------------------------------- [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_TimelineOptions { public float fps; public float startTime; public float endTime; } // ASSETS ------------------------------------------------------------------------------------------------------- [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_AssetInfo { public HAPI_AssetId id; public HAPI_AssetType type; public HAPI_AssetSubType subType; // This id is primarily used to check whether the asset still exists // within the Houdini scene running inside the runtime. The asset id // alone is not enough as asset ids are re-used between sessions. // We use this id to determine whether we need to re-instatiate an asset // we have on the client side so that Houdini also knows about it - // which is different from the case where a new asset is being loaded // for the first time. public int validationId; // Use the node id to get the asset's parameters. public HAPI_NodeId nodeId; // The objectNodeId differs from the regular nodeId in that for // geometry based assets (SOPs) it will be the node id of the dummy // object (OBJ) node instead of the asset node. For object based assets // the objectNodeId will equal the nodeId. The reason the distinction // exists is because transforms are always stored on the object node // but the asset parameters may not be on the asset node if the asset // is a geometry asset so we need both. public HAPI_NodeId objectNodeId; [ MarshalAs( UnmanagedType.U1 ) ] public bool hasEverCooked; private HAPI_StringHandle nameSH; // Instance name (the label + a number). private HAPI_StringHandle labelSH; private HAPI_StringHandle filePathSH; // Path to the .otl file for this asset. private HAPI_StringHandle versionSH; // User-defined asset version. private HAPI_StringHandle fullOpNameSH; // Full asset name and namespace. private HAPI_StringHandle helpTextSH; // Asset help marked-up text. public int objectCount; public int handleCount; public int editableNodeNetworkCount; public int transformInputCount; public int geoInputCount; [ MarshalAs( UnmanagedType.U1 ) ] public bool haveObjectsChanged; [ MarshalAs( UnmanagedType.U1 ) ] public bool haveMaterialsChanged; // Accessors public string name { get { return HoudiniHost.getString( nameSH ); } private set {} } public string label { get { return HoudiniHost.getString( labelSH ); } private set {} } public string filePath { get { return HoudiniHost.getString( filePathSH ); } private set {} } public string version { get { return HoudiniHost.getString( versionSH ); } private set {} } public string fullOpName { get { return HoudiniHost.getString( fullOpNameSH ); } private set {} } public string helpText { get { return HoudiniHost.getString( helpTextSH ); } private set {} } } [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_CookOptions { /// Normally, geos are split into parts in two different ways. First it /// is split by group and within each group it is split by primitive type. /// /// For example, if you have a geo with group1 covering half of the mesh /// and volume1 and group2 covering the other half of the mesh, all of /// curve1, and volume2 you will end up with 5 parts. First two parts /// will be for the half-mesh of group1 and volume1, and the last three /// will cover group2. /// /// This toggle lets you disable the splitting by group and just have /// the geo be split by primitive type alone. By default, this is true /// and therefore geos will be split by group and primitive type. If /// set to false, geos will only be split by primtive type. [ MarshalAs( UnmanagedType.U1 ) ] public bool splitGeosByGroup; /// For meshes only, this is enforced by convexing the mesh. Use -1 /// to avoid convexing at all and get some performance boost. public int maxVerticesPerPrimitive; // Curves [ MarshalAs( UnmanagedType.U1 ) ] public bool refineCurveToLinear; public float curveRefineLOD; /// If this option is turned on, then we will recursively clear the /// errors and warnings (and messages) of all nodes before performing /// the cook. [ MarshalAs( UnmanagedType.U1 ) ] public bool clearErrorsAndWarnings; /// Decide whether to recursively cook all templated geos or not. [ MarshalAs( UnmanagedType.U1 ) ] public bool cookTemplatedGeos; /// Choose how you want the cook to handle packed primitives. public HAPI_PackedPrimInstancingMode packedPrimInstancingMode; } // NODES -------------------------------------------------------------------------------------------------------- [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_NodeInfo { public HAPI_NodeId id; public HAPI_AssetId assetId; public HAPI_StringHandle nameSH; [ MarshalAs( UnmanagedType.U1 ) ] public bool isValid; public int totalCookCount; public int uniqueHoudiniNodeId; private HAPI_StringHandle internalNodePathSH; public int parmCount; public int parmIntValueCount; public int parmFloatValueCount; public int parmStringValueCount; public int parmChoiceCount; public int childNodeCount; public int inputCount; [ MarshalAs( UnmanagedType.U1 ) ] public bool createdPostAssetLoad; public string name { get { return HoudiniHost.getString( nameSH ); } private set {} } public string internalNodePath { get { return HoudiniHost.getString( internalNodePathSH ); } private set {} } } // PARAMETERS --------------------------------------------------------------------------------------------------- [ Serializable ] [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_ParmInfo { public bool isInt() { return ( type >= HAPI_ParmType.HAPI_PARMTYPE_INT_START && type <= HAPI_ParmType.HAPI_PARMTYPE_INT_END ) || type == HAPI_ParmType.HAPI_PARMTYPE_MULTIPARMLIST; } public bool isFloat() { return ( type >= HAPI_ParmType.HAPI_PARMTYPE_FLOAT_START && type <= HAPI_ParmType.HAPI_PARMTYPE_FLOAT_END ); } public bool isString() { return ( type >= HAPI_ParmType.HAPI_PARMTYPE_STRING_START && type <= HAPI_ParmType.HAPI_PARMTYPE_STRING_END ); } public bool isPath() { return ( type >= HAPI_ParmType.HAPI_PARMTYPE_PATH_START && type <= HAPI_ParmType.HAPI_PARMTYPE_PATH_END ); } public bool isFilePath() { return ( type >= HAPI_ParmType.HAPI_PARMTYPE_PATH_FILE_START && type <= HAPI_ParmType.HAPI_PARMTYPE_PATH_FILE_END ); } public bool isNodePath() { return ( type >= HAPI_ParmType.HAPI_PARMTYPE_PATH_NODE_START && type <= HAPI_ParmType.HAPI_PARMTYPE_PATH_NODE_END ); } public bool isNonValue() { return ( type >= HAPI_ParmType.HAPI_PARMTYPE_NONVALUE_START && type <= HAPI_ParmType.HAPI_PARMTYPE_NONVALUE_END ); } // The parent id points to the id of the parent parm // of this parm. The parent parm is something like a folder. public HAPI_ParmId id; public HAPI_ParmId parentId; public int childIndex; public HAPI_ParmType type; public HAPI_StringHandle typeInfoSH; public HAPI_Permissions permissions; public int size; // Tuple Size HAPI_ChoiceListType choiceListType; public int choiceCount; // Note that folders are not real parameters in Houdini so they do not // have names. The folder names given here are generated from the name // of the folderlist (or switcher) parameter which is a parameter. The // folderlist parameter simply defines how many of the "next" parameters // belong to the first folder, how many of the parameters after that // belong to the next folder, and so on. This means that folder names // can change just by reordering the folders around so don't rely on // them too much. The only guarantee here is that the folder names will // be unique among all other parameter names. private HAPI_StringHandle nameSH; private HAPI_StringHandle labelSH; // If this parameter is a multiparm instance than the templateNameSH // will be the hash-templated parm name, containing #'s for the // parts of the name that use the instance number. Compared to the // nameSH, the nameSH will be the templateNameSH but with the #'s // replaced by the instance number. For regular parms, the templateNameSH // is identical to the nameSH. private HAPI_StringHandle templateNameSH; private HAPI_StringHandle helpSH; [ MarshalAs( UnmanagedType.U1 ) ] public bool hasMin; [ MarshalAs( UnmanagedType.U1 ) ] public bool hasMax; [ MarshalAs( UnmanagedType.U1 ) ] public bool hasUIMin; [ MarshalAs( UnmanagedType.U1 ) ] public bool hasUIMax; [ MarshalAs( UnmanagedType.R4 ) ] public float min; [ MarshalAs( UnmanagedType.R4 ) ] public float max; [ MarshalAs( UnmanagedType.R4 ) ] public float UIMin; [ MarshalAs( UnmanagedType.R4 ) ] public float UIMax; [ MarshalAs( UnmanagedType.U1 ) ] public bool invisible; [ MarshalAs( UnmanagedType.U1 ) ] public bool disabled; [ MarshalAs( UnmanagedType.U1 ) ] public bool spare; // Whether this parm should be on the same line as the next parm. [ MarshalAs( UnmanagedType.U1 ) ] public bool joinNext; [ MarshalAs( UnmanagedType.U1 ) ] public bool labelNone; public int intValuesIndex; public int floatValuesIndex; public int stringValuesIndex; public int choiceIndex; [ MarshalAs( UnmanagedType.U1 ) ] public bool isChildOfMultiParm; public int instanceNum; // The index of the instance in the multiparm. public int instanceLength; // The number of parms in a multiparm instance. public int instanceCount; // The number of instances in a multiparm. public int instanceStartOffset; // First instanceNum either 0 or 1. public HAPI_RampType rampType; // Accessors public int getTypeInfoSH() { return typeInfoSH; } public int getNameSH() { return nameSH; } public int getLabelSH() { return labelSH; } public string typeInfo { get { return HoudiniHost.getString( typeInfoSH ); } private set {} } public string name { get { return HoudiniHost.getString( nameSH ); } private set {} } public string label { get { return HoudiniHost.getString( labelSH ); } private set {} } public string templateName { get { return HoudiniHost.getString( templateNameSH ); } private set {} } public string help { get { return HoudiniHost.getString( helpSH ); } private set {} } } // Used for caching HAPI_ParmInfo strings. [ Serializable ] public struct HAPI_ParmInfoStrings { public void cacheStrings( HAPI_ParmInfo parm_info ) { typeInfo = parm_info.typeInfo; name = parm_info.name; label = parm_info.label; templateName = parm_info.templateName; help = parm_info.help; } public string typeInfo; public string name; public string label; public string templateName; public string help; } [ Serializable ] [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_ParmChoiceInfo { public HAPI_ParmId parentParmId; private HAPI_StringHandle labelSH; private HAPI_StringHandle valueSH; // Accessors public string label { get { return HoudiniHost.getString( labelSH ); } private set {} } public string value { get { return HoudiniHost.getString( valueSH ); } private set {} } } // Used for caching HAPI_ParmChoiceInfo strings. [ Serializable ] public struct HAPI_ParmChoiceInfoStrings { public void cacheStrings( HAPI_ParmChoiceInfo choice_info ) { label = choice_info.label; value = choice_info.value; } public string label; public string value; } // HANDLES ------------------------------------------------------------------------------------------------------ [ Serializable ] [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_HandleInfo { private HAPI_StringHandle nameSH; private HAPI_StringHandle typeNameSH; public int bindingsCount; // Accessors public string name { get { return HoudiniHost.getString( nameSH ); } private set {} } public string typeName { get { return HoudiniHost.getString( typeNameSH ); } private set {} } } [ Serializable ] [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_HandleBindingInfo { private HAPI_StringHandle handleParmNameSH; private HAPI_StringHandle assetParmNameSH; public HAPI_ParmId assetParmId; // Accessors public string handleParmName { get { return HoudiniHost.getString( handleParmNameSH ); } private set {} } public string assetParmName { get { return HoudiniHost.getString( assetParmNameSH ); } private set {} } }; // OBJECTS ------------------------------------------------------------------------------------------------------ [ Serializable ] [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_ObjectInfo { public HAPI_ObjectId id; private HAPI_StringHandle nameSH; private HAPI_StringHandle objectInstancePathSH; [ MarshalAs( UnmanagedType.U1 ) ] public bool hasTransformChanged; [ MarshalAs( UnmanagedType.U1 ) ] public bool haveGeosChanged; [ MarshalAs( UnmanagedType.U1 ) ] public bool isVisible; [ MarshalAs( UnmanagedType.U1 ) ] public bool isInstancer; public int geoCount; // Use the node id to get the node's parameters. public HAPI_NodeId nodeId; public HAPI_ObjectId objectToInstanceId; // Accessors public string name { get { return HoudiniHost.getString( nameSH ); } private set {} } public string objectInstancePath { get { return HoudiniHost.getString( objectInstancePathSH ); } private set {} } } // GEOMETRY ----------------------------------------------------------------------------------------------------- [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_GeoInfo { public int getGroupCountByType( HAPI_GroupType type ) { switch ( type ) { case HAPI_GroupType.HAPI_GROUPTYPE_POINT: return pointGroupCount; case HAPI_GroupType.HAPI_GROUPTYPE_PRIM: return primitiveGroupCount; default: return 0; } } public HAPI_GeoId id; public HAPI_GeoType type; private HAPI_StringHandle nameSH; // Use the node id to get the node's parameters. public HAPI_NodeId nodeId; [ MarshalAs( UnmanagedType.U1 ) ] public bool isEditable; [ MarshalAs( UnmanagedType.U1 ) ] public bool isTemplated; [ MarshalAs( UnmanagedType.U1 ) ] public bool isDisplayGeo; // Final Result (Display SOP) [ MarshalAs( UnmanagedType.U1 ) ] public bool hasGeoChanged; [ MarshalAs( UnmanagedType.U1 ) ] public bool hasMaterialChanged; public int pointGroupCount; public int primitiveGroupCount; public int partCount; // Accessors public string name { get { return HoudiniHost.getString( nameSH ); } private set {} } } [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_GeoInputInfo { public HAPI_ObjectId objectId; public HAPI_GeoId geoId; public HAPI_NodeId objectNodeId; } [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_PartInfo { public int getElementCountByAttributeOwner( HAPI_AttributeOwner owner ) { switch ( owner ) { case HAPI_AttributeOwner.HAPI_ATTROWNER_VERTEX: return vertexCount; case HAPI_AttributeOwner.HAPI_ATTROWNER_POINT: return pointCount; case HAPI_AttributeOwner.HAPI_ATTROWNER_PRIM: return faceCount; case HAPI_AttributeOwner.HAPI_ATTROWNER_DETAIL: return 1; default: return 0; } } public int getElementCountByGroupType( HAPI_GroupType type ) { switch ( type ) { case HAPI_GroupType.HAPI_GROUPTYPE_POINT: return pointCount; case HAPI_GroupType.HAPI_GROUPTYPE_PRIM: return faceCount; default: return 0; } } public int getAttributeCountByOwner( HAPI_AttributeOwner owner ) { switch ( owner ) { case HAPI_AttributeOwner.HAPI_ATTROWNER_VERTEX: return vertexAttributeCount; case HAPI_AttributeOwner.HAPI_ATTROWNER_POINT: return pointAttributeCount; case HAPI_AttributeOwner.HAPI_ATTROWNER_PRIM: return faceAttributeCount; case HAPI_AttributeOwner.HAPI_ATTROWNER_DETAIL: return detailAttributeCount; default: return 0; } } public HAPI_PartId id; private HAPI_StringHandle nameSH; public HAPI_PartType type; public int faceCount; public int vertexCount; public int pointCount; public int pointAttributeCount; public int faceAttributeCount; public int vertexAttributeCount; public int detailAttributeCount; [ MarshalAs( UnmanagedType.U1 ) ] public bool isInstanced; public int instancedPartCount; public int instanceCount; // Accessors public string name { get { return HoudiniHost.getString( nameSH ); } private set {} } } [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_AttributeInfo { public HAPI_AttributeInfo( string attr_name ) { exists = false; owner = HAPI_AttributeOwner.HAPI_ATTROWNER_INVALID; storage = HAPI_StorageType.HAPI_STORAGETYPE_INVALID; originalOwner = HAPI_AttributeOwner.HAPI_ATTROWNER_INVALID; count = 0; tupleSize = 0; } [ MarshalAs( UnmanagedType.U1 ) ] public bool exists; public HAPI_AttributeOwner owner; public HAPI_StorageType storage; public HAPI_AttributeOwner originalOwner; public int count; public int tupleSize; } // MATERIALS ---------------------------------------------------------------------------------------------------- [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_MaterialInfo { public HAPI_MaterialId id; public HAPI_AssetId assetId; public HAPI_NodeId nodeId; [ MarshalAs( UnmanagedType.U1 ) ] public bool exists; [ MarshalAs( UnmanagedType.U1 ) ] public bool hasChanged; } [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_ImageFileFormat { public HAPI_StringHandle nameSH; public HAPI_StringHandle descriptionSH; public HAPI_StringHandle defaultExtensionSH; // Accessors public string name { get { return HoudiniHost.getString( nameSH ); } private set {} } public string description { get { return HoudiniHost.getString( descriptionSH ); } private set {} } public string defaultExtension { get { return HoudiniHost.getString( defaultExtensionSH ); } private set {} } }; [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_ImageInfo { // Unlike the other members of this struct changing imageFileFormatNameSH and // giving this struct back to HAPI_Host.setImageInfo() nothing will happen. // Use this member variable to derive which image file format will be used // by the HAPI_Host.extractImageTo...() functions if called with image_file_format_name // set to (null). This way, you can decide whether to ask for a file format // conversion (slower) or not (faster). public HAPI_StringHandle imageFileFormatNameSH; // Readonly public int xRes; public int yRes; public HAPI_ImageDataFormat dataFormat; [ MarshalAs( UnmanagedType.U1 ) ] public bool interleaved; // ex: true = RGBRGBRGB, false = RRRGGGBBB public HAPI_ImagePacking packing; [ MarshalAs( UnmanagedType.R8 ) ] public double gamma; // Accessors public string imageFileFormatName { get { return HoudiniHost.getString( imageFileFormatNameSH ); } private set {} } // Utility public bool isImageFileFormat( string image_file_format_name ) { return ( imageFileFormatName == image_file_format_name ); } } // ANIMATION ---------------------------------------------------------------------------------------------------- [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_Keyframe { HAPI_Keyframe( float t, float v, float in_tangent, float out_tangent ) { time = t; value = v; inTangent = in_tangent; outTangent = out_tangent; } [ MarshalAs( UnmanagedType.R4 ) ] public float time; [ MarshalAs( UnmanagedType.R4 ) ] public float value; [ MarshalAs( UnmanagedType.R4 ) ] public float inTangent; [ MarshalAs( UnmanagedType.R4 ) ] public float outTangent; } // VOLUMES ------------------------------------------------------------------------------------------------------ /// This represents a volume primitive--sans the actual voxel values, /// which can be retrieved on a per-tile basis [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_VolumeInfo { public HAPI_StringHandle nameSH; public HAPI_VolumeType type; // Each voxel is identified with an index. The indices will range between: // [ ( minX, minY, minZ ), ( minX+xLength, minY+yLength, minZ+zLength ) ) public int xLength; public int yLength; public int zLength; public int minX; public int minY; public int minZ; // Number of values per voxel. public int tupleSize; public HAPI_StorageType storage; // The dimensions of each tile. public int tileSize; // The transform of the volume with respect to the above lengths. [ MarshalAs( UnmanagedType.Struct ) ] public HAPI_Transform transform; [ MarshalAs( UnmanagedType.U1 ) ] public bool hasTaper; [ MarshalAs( UnmanagedType.R4 ) ] public float xTaper; [ MarshalAs( UnmanagedType.R4 ) ] public float yTaper; }; /// A HAPI_VolumeTileInfo represents an 8x8x8 section of a volume with /// bbox [(minX, minY, minZ), (minX+8, minY+8, minZ+8)) [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_VolumeTileInfo { public int minX; public int minY; public int minZ; [ MarshalAs( UnmanagedType.U1 ) ] public bool isValid; }; // CURVES ------------------------------------------------------------------------------------------------------- [ StructLayout( LayoutKind.Sequential ) ] public struct HAPI_CurveInfo { public HAPI_CurveType curveType; public int curveCount; public int vertexCount; public int knotCount; [ MarshalAs( UnmanagedType.U1 ) ] public bool isPeriodic; [ MarshalAs( UnmanagedType.U1 ) ] public bool isRational; public int order; // Order of 1 is invalid. 0 means there is a varying order. [ MarshalAs( UnmanagedType.U1 ) ] public bool hasKnots; };
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Marten.Linq; using Marten.Services; using Marten.Testing.Documents; using Marten.Testing.Harness; using Shouldly; using Xunit; namespace Marten.Testing.Linq.Compiled { public class compiled_query_Tests: IntegrationContext { private readonly User _user1; private readonly User _user5; public compiled_query_Tests(DefaultStoreFixture fixture) : base(fixture) { _user1 = new User { FirstName = "Jeremy", UserName = "jdm", LastName = "Miller" }; var user2 = new User { FirstName = "Jens" }; var user3 = new User { FirstName = "Jeff" }; var user4 = new User { FirstName = "Corey", UserName = "myusername", LastName = "Kaylor" }; _user5 = new User { FirstName = "Jeremy", UserName = "shadetreedev", LastName = "Miller" }; theSession.Store(_user1, user2, user3, user4, _user5); theSession.SaveChanges(); } [Fact] public void can_preview_command_for_a_compiled_query() { var cmd = theStore.Diagnostics.PreviewCommand(new UserByUsername { UserName = "hank" }); cmd.CommandText.ShouldBe("select d.data, d.id, d.mt_version from public.mt_doc_user as d where d.data ->> 'UserName' = :p0 LIMIT :p1"); cmd.Parameters.First().Value.ShouldBe("hank"); } [Fact] public void can_explain_the_plan_for_a_compiled_query() { var query = new UserByUsername { UserName = "hank" }; var plan = theStore.Diagnostics.ExplainPlan(query); SpecificationExtensions.ShouldNotBeNull(plan); } [Fact] public void a_single_item_compiled_query() { var user = theSession.Query(new UserByUsername { UserName = "myusername" }); user.ShouldNotBeNull(); var differentUser = theSession.Query(new UserByUsername { UserName = "jdm" }); differentUser.UserName.ShouldBe("jdm"); } [Fact] public void a_single_item_compiled_query_with_fields() { var user = theSession.Query(new UserByUsernameWithFields { UserName = "myusername" }); SpecificationExtensions.ShouldNotBeNull(user); var differentUser = theSession.Query(new UserByUsernameWithFields { UserName = "jdm" }); differentUser.UserName.ShouldBe("jdm"); } [Fact] public void a_single_item_compiled_query_SingleOrDefault() { var user = theSession.Query(new UserByUsernameSingleOrDefault() { UserName = "myusername" }); user.ShouldNotBeNull(); theSession.Query(new UserByUsernameSingleOrDefault() { UserName = "nonexistent" }).ShouldBeNull(); } // SAMPLE: FindJsonUserByUsername [Fact] public void a_single_item_compiled_query_AsJson() { var user = theSession.Query(new FindJsonUserByUsername() { Username = "jdm" }); SpecificationExtensions.ShouldNotBeNull(user); user.ShouldBe(_user1.ToJson()); } // ENDSAMPLE // SAMPLE: FindJsonOrderedUsersByUsername [Fact] public void a_sorted_list_compiled_query_AsJson() { var user = theSession.Query(new FindJsonOrderedUsersByUsername() { FirstName = "Jeremy" }); user.ShouldNotBeNull(); user.ShouldBe($"[{_user1.ToJson()},{_user5.ToJson()}]"); } // ENDSAMPLE [Fact] public void a_filtered_list_compiled_query_AsJson() { var user = theSession.Query(new FindJsonUsersByUsername() { FirstName = "Jeremy" }); SpecificationExtensions.ShouldNotBeNull(user); user.ShouldNotBeEmpty(); } [Fact] public async Task a_filtered_list_compiled_query_AsJson_async() { var user = await theSession.QueryAsync(new FindJsonUsersByUsername() { FirstName = "Jeremy" }).ConfigureAwait(false); SpecificationExtensions.ShouldNotBeNull(user); user.ShouldNotBeEmpty(); } [Fact] public void several_parameters_for_compiled_query() { var user = theSession.Query(new FindUserByAllTheThings { Username = "jdm", FirstName = "Jeremy", LastName = "Miller" }); SpecificationExtensions.ShouldNotBeNull(user); user.UserName.ShouldBe("jdm"); user = theSession.Query(new FindUserByAllTheThings { Username = "shadetreedev", FirstName = "Jeremy", LastName = "Miller" }); SpecificationExtensions.ShouldNotBeNull(user); user.UserName.ShouldBe("shadetreedev"); } [Fact] public async Task a_single_item_compiled_query_async() { var user = await theSession.QueryAsync(new UserByUsername { UserName = "myusername" }).ConfigureAwait(false); SpecificationExtensions.ShouldNotBeNull(user); var differentUser = await theSession.QueryAsync(new UserByUsername { UserName = "jdm" }); differentUser.UserName.ShouldBe("jdm"); } [Fact] public void a_list_query_compiled() { var users = theSession.Query(new UsersByFirstName { FirstName = "Jeremy" }).ToList(); users.Count.ShouldBe(2); users.ElementAt(0).UserName.ShouldBe("jdm"); users.ElementAt(1).UserName.ShouldBe("shadetreedev"); var differentUsers = theSession.Query(new UsersByFirstName { FirstName = "Jeremy" }); differentUsers.Count().ShouldBe(2); } [Fact] public void a_list_query_with_fields_compiled() { var users = theSession.Query(new UsersByFirstNameWithFields { FirstName = "Jeremy" }).ToList(); users.Count.ShouldBe(2); users.ElementAt(0).UserName.ShouldBe("jdm"); users.ElementAt(1).UserName.ShouldBe("shadetreedev"); var differentUsers = theSession.Query(new UsersByFirstNameWithFields { FirstName = "Jeremy" }); differentUsers.Count().ShouldBe(2); } [Fact] public async Task a_list_query_compiled_async() { var users = await theSession.QueryAsync(new UsersByFirstName { FirstName = "Jeremy" }).ConfigureAwait(false); users.Count().ShouldBe(2); users.ElementAt(0).UserName.ShouldBe("jdm"); users.ElementAt(1).UserName.ShouldBe("shadetreedev"); var differentUsers = await theSession.QueryAsync(new UsersByFirstName { FirstName = "Jeremy" }); differentUsers.Count().ShouldBe(2); } [Fact] public void count_query_compiled() { var userCount = theSession.Query(new UserCountByFirstName { FirstName = "Jeremy" }); userCount.ShouldBe(2); userCount = theSession.Query(new UserCountByFirstName { FirstName = "Corey" }); userCount.ShouldBe(1); } [Fact] public void projection_query_compiled() { var user = theSession.Query(new UserProjectionToLoginPayload { UserName = "jdm" }); user.ShouldNotBeNull(); user.Username.ShouldBe("jdm"); user = theSession.Query(new UserProjectionToLoginPayload { UserName = "shadetreedev" }); user.ShouldNotBeNull(); user.Username.ShouldBe("shadetreedev"); } } // SAMPLE: FindUserByAllTheThings public class FindUserByAllTheThings: ICompiledQuery<User> { public string Username { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Expression<Func<IMartenQueryable<User>, User>> QueryIs() { return query => query.Where(x => x.FirstName == FirstName && Username == x.UserName) .Where(x => x.LastName == LastName) .Single(); } } // ENDSAMPLE // SAMPLE: CompiledAsJson public class FindJsonUserByUsername: ICompiledQuery<User, string> { public string Username { get; set; } public Expression<Func<IMartenQueryable<User>, string>> QueryIs() { return query => query.Where(x => Username == x.UserName) .AsJson().Single(); } } // ENDSAMPLE // SAMPLE: CompiledToJsonArray public class FindJsonOrderedUsersByUsername: ICompiledQuery<User, string> { public string FirstName { get; set; } public Expression<Func<IMartenQueryable<User>, string>> QueryIs() { return query => query.Where(x => FirstName == x.FirstName) .OrderBy(x => x.UserName) .ToJsonArray(); } } // ENDSAMPLE public class FindJsonUsersByUsername: ICompiledQuery<User, string> { public string FirstName { get; set; } public Expression<Func<IMartenQueryable<User>, string>> QueryIs() { return query => query.Where(x => FirstName == x.FirstName) .ToJsonArray(); } } public class UserProjectionToLoginPayload: ICompiledQuery<User, LoginPayload> { public string UserName { get; set; } public Expression<Func<IMartenQueryable<User>, LoginPayload>> QueryIs() { return query => query.Where(x => x.UserName == UserName) .Select(x => new LoginPayload { Username = x.UserName }).Single(); } } public class LoginPayload { public string Username { get; set; } } public class UserCountByFirstName: ICompiledQuery<User, int> { public string FirstName { get; set; } public Expression<Func<IMartenQueryable<User>, int>> QueryIs() { return query => query.Count(x => x.FirstName == FirstName); } } public class UserByUsername: ICompiledQuery<User> { public string UserName { get; set; } public Expression<Func<IMartenQueryable<User>, User>> QueryIs() { return query => query .FirstOrDefault(x => x.UserName == UserName); } } public class UserByUsernameWithFields: ICompiledQuery<User> { public string UserName; public Expression<Func<IMartenQueryable<User>, User>> QueryIs() { return query => Queryable.FirstOrDefault(query.Where(x => x.UserName == UserName)); } } public class UserByUsernameSingleOrDefault: ICompiledQuery<User> { public static int Count; public string UserName { get; set; } public Expression<Func<IMartenQueryable<User>, User>> QueryIs() { Count++; return query => query.Where(x => x.UserName == UserName) .SingleOrDefault(); } } // SAMPLE: UsersByFirstName-Query public class UsersByFirstName: ICompiledListQuery<User> { public static int Count; public string FirstName { get; set; } public Expression<Func<IMartenQueryable<User>, IEnumerable<User>>> QueryIs() { return query => query.Where(x => x.FirstName == FirstName); } } // ENDSAMPLE public class UsersByFirstNameWithFields: ICompiledListQuery<User> { public string FirstName; public Expression<Func<IMartenQueryable<User>, IEnumerable<User>>> QueryIs() { return query => query.Where(x => x.FirstName == FirstName); } } // SAMPLE: UserNamesForFirstName public class UserNamesForFirstName: ICompiledListQuery<User, string> { public Expression<Func<IMartenQueryable<User>, IEnumerable<string>>> QueryIs() { return q => q .Where(x => x.FirstName == FirstName) .Select(x => x.UserName); } public string FirstName { get; set; } } // ENDSAMPLE }
// 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.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Net.Sockets; using System.Runtime.ExceptionServices; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.WebSockets { internal sealed class WebSocketHandle { /// <summary>GUID appended by the server as part of the security key response. Defined in the RFC.</summary> private const string WSServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private readonly CancellationTokenSource _abortSource = new CancellationTokenSource(); private WebSocketState _state = WebSocketState.Connecting; private WebSocket _webSocket; public static WebSocketHandle Create() => new WebSocketHandle(); public static bool IsValid(WebSocketHandle handle) => handle != null; public WebSocketCloseStatus? CloseStatus => _webSocket?.CloseStatus; public string CloseStatusDescription => _webSocket?.CloseStatusDescription; public WebSocketState State => _webSocket?.State ?? _state; public string SubProtocol => _webSocket?.SubProtocol; public static void CheckPlatformSupport() { /* nop */ } public void Dispose() { _state = WebSocketState.Closed; _webSocket?.Dispose(); } public void Abort() { _abortSource.Cancel(); _webSocket?.Abort(); } public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => _webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) => _webSocket.ReceiveAsync(buffer, cancellationToken); public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) => _webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken); public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) => _webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken); private sealed class DirectManagedHttpClientHandler : HttpClientHandler { private const string ManagedHandlerEnvVar = "COMPlus_UseManagedHttpClientHandler"; private static readonly LocalDataStoreSlot s_managedHandlerSlot = GetSlot(); private static readonly object s_true = true; private static LocalDataStoreSlot GetSlot() { LocalDataStoreSlot slot = Thread.GetNamedDataSlot(ManagedHandlerEnvVar); if (slot != null) { return slot; } try { return Thread.AllocateNamedDataSlot(ManagedHandlerEnvVar); } catch (ArgumentException) // in case of a race condition where multiple threads all try to allocate the slot concurrently { return Thread.GetNamedDataSlot(ManagedHandlerEnvVar); } } public static DirectManagedHttpClientHandler CreateHandler() { Thread.SetData(s_managedHandlerSlot, s_true); try { return new DirectManagedHttpClientHandler(); } finally { Thread.SetData(s_managedHandlerSlot, null); } } public new Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) => base.SendAsync(request, cancellationToken); } public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { try { // Create the request message, including a uri with ws{s} switched to http{s}. uri = new UriBuilder(uri) { Scheme = (uri.Scheme == UriScheme.Ws) ? UriScheme.Http : UriScheme.Https }.Uri; var request = new HttpRequestMessage(HttpMethod.Get, uri); if (options._requestHeaders?.Count > 0) // use field to avoid lazily initializing the collection { foreach (string key in options.RequestHeaders) { request.Headers.Add(key, options.RequestHeaders[key]); } } // Create the security key and expected response, then build all of the request headers KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept(); AddWebSocketHeaders(request, secKeyAndSecWebSocketAccept.Key, options); // Create the handler for this request and populate it with all of the options. DirectManagedHttpClientHandler handler = DirectManagedHttpClientHandler.CreateHandler(); handler.UseDefaultCredentials = options.UseDefaultCredentials; handler.Credentials = options.Credentials; handler.Proxy = options.Proxy; handler.CookieContainer = options.Cookies; if (options._clientCertificates?.Count > 0) // use field to avoid lazily initializing the collection { handler.ClientCertificateOptions = ClientCertificateOption.Manual; handler.ClientCertificates.AddRange(options.ClientCertificates); } // Issue the request. The response must be status code 101. HttpResponseMessage response = await handler.SendAsync(request, cancellationToken).ConfigureAwait(false); if (response.StatusCode != HttpStatusCode.SwitchingProtocols) { throw new WebSocketException(SR.net_webstatus_ConnectFailure); } // The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values. ValidateHeader(response.Headers, HttpKnownHeaderNames.Connection, "Upgrade"); ValidateHeader(response.Headers, HttpKnownHeaderNames.Upgrade, "websocket"); ValidateHeader(response.Headers, HttpKnownHeaderNames.SecWebSocketAccept, secKeyAndSecWebSocketAccept.Value); // The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols, // and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we // already got one in a previous header), fail. Otherwise, track which one we got. string subprotocol = null; IEnumerable<string> subprotocolEnumerableValues; if (response.Headers.TryGetValues(HttpKnownHeaderNames.SecWebSocketProtocol, out subprotocolEnumerableValues)) { Debug.Assert(subprotocolEnumerableValues is string[]); string[] subprotocolArray = (string[])subprotocolEnumerableValues; if (subprotocolArray.Length != 1 || (subprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, subprotocolArray[0], StringComparison.OrdinalIgnoreCase))) == null) { throw new WebSocketException( WebSocketError.UnsupportedProtocol, SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), subprotocol)); } } // Get the response stream and wrap it in a web socket. Stream connectedStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); Debug.Assert(connectedStream.CanWrite); Debug.Assert(connectedStream.CanRead); _webSocket = WebSocket.CreateClientWebSocket( // TODO https://github.com/dotnet/corefx/issues/21537: Use new API when available connectedStream, subprotocol, options.ReceiveBufferSize, options.SendBufferSize, options.KeepAliveInterval, useZeroMaskingKey: false, internalBuffer:options.Buffer.GetValueOrDefault()); } catch (Exception exc) { if (_state < WebSocketState.Closed) { _state = WebSocketState.Closed; } Abort(); if (exc is WebSocketException) { throw; } throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc); } } /// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param> private static void AddWebSocketHeaders(HttpRequestMessage request, string secKey, ClientWebSocketOptions options) { request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade); request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Upgrade, "websocket"); request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketVersion, "13"); request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketKey, secKey); if (options._requestedSubProtocols?.Count > 0) { request.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, string.Join(", ", options.RequestedSubProtocols)); } } /// <summary> /// Creates a pair of a security key for sending in the Sec-WebSocket-Key header and /// the associated response we expect to receive as the Sec-WebSocket-Accept header value. /// </summary> /// <returns>A key-value pair of the request header security key and expected response header value.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "Required by RFC6455")] private static KeyValuePair<string, string> CreateSecKeyAndSecWebSocketAccept() { string secKey = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); using (SHA1 sha = SHA1.Create()) { return new KeyValuePair<string, string>( secKey, Convert.ToBase64String(sha.ComputeHash(Encoding.ASCII.GetBytes(secKey + WSServerGuid)))); } } private static void ValidateHeader(HttpHeaders headers, string name, string expectedValue) { if (!headers.TryGetValues(name, out IEnumerable<string> values)) { ThrowConnectFailure(); } Debug.Assert(values is string[]); string[] array = (string[])values; if (array.Length != 1 || !string.Equals(array[0], expectedValue, StringComparison.OrdinalIgnoreCase)) { throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, name, string.Join(", ", array))); } } private static void ThrowConnectFailure() => throw new WebSocketException(SR.net_webstatus_ConnectFailure); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Xunit.Performance; using System; using System.Runtime.CompilerServices; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] namespace Benchstone.BenchF { public static class MatInv4 { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 60; #endif private static float s_det; private struct X { public float[] A; public X(int size) { A = new float[size]; } } [MethodImpl(MethodImplOptions.NoInlining)] private static bool Bench() { X a = new X(Iterations * Iterations); float[] b = new float[Iterations * Iterations]; float[] c = new float[Iterations * Iterations]; float[] d = new float[Iterations * Iterations]; float[] l1 = new float[Iterations]; float[] l2 = new float[Iterations]; int i, k, n, nsq; n = Iterations; nsq = n * n; for (i = 0; i < n; ++i) { for (k = 0; k < n; ++k) { if (i == k) { a.A[i * n + k] = 40.0F; } else { a.A[i * n + k] = 0.0F; } } } for (i = 0; i < n; ++i) { for (k = i; k < nsq; k += n) { b[k] = a.A[k]; } } /*** second(&t1); ***/ MinV1(b, ref n, out s_det, l1, l2); if (s_det == 0.0F) { goto L990; } /*** second(&tx); ***/ MProd(b, a.A, c, ref n); for (k = 1; k <= nsq; ++k) { b[k - 1] = a.A[k - 1]; } /*** second(&tx); ***/ MinV2(b, ref n, out s_det, l1, l2); if (s_det == 0.0F) { goto L990; } /*** second(&ty); ***/ MProd(b, a.A, d, ref n); CompM(c, d, ref n); /*** second(&t2); ***/ return true; L990: { } return true; } private static void MinV1(float[] a, ref int n, out float d, float[] l, float[] m) { float biga, hold; int i, j, k, ij, ik, ji, jk, nk, ki, kj, kk, iz, jp, jq, jr; d = 1.0F; ji = 0; hold = 0.0F; nk = -n; for (k = 1; k <= n; ++k) { nk = nk + n; l[k - 1] = k; m[k - 1] = k; kk = nk + k; biga = a[kk - 1]; for (j = k; j <= n; ++j) { // j <= n, so iz <= n^2 - n iz = n * (j - 1); for (i = k; i <= n; ++i) { // iz <= n^2 - n and i <= n, so ij <= n^2 ij = iz + i; if (System.Math.Abs(biga) >= System.Math.Abs(a[ij - 1])) { continue; } // accessing up to n^2 - 1 biga = a[ij - 1]; l[k - 1] = i; m[k - 1] = j; } } j = (int)l[k - 1]; if (j <= k) { goto L35; } // -n < ki <= 0 ki = k - n; for (i = 1; i <= n; ++i) { // i <= n, ki <= n + n + ... + n (n times) i.e. k <= n * n (when ki = 0 initially) ki = ki + n; // Accessing upto n^2 -1 hold = -a[ki - 1]; // ji <= n^2 - n + n (for ki = 0 initially when k = n and 0 < j <= n) // Therefore ji <= n^2 ji = ki - k + j; a[ki - 1] = a[ji - 1]; a[ji - 1] = hold; } L35: i = (int)m[k - 1]; if (i <= k) { goto L45; } // 0 <= jp <= n^2 - n jp = n * (i - 1); for (j = 1; j <= n; ++j) { // 0 < nk <= n * (n-1) // jk <= n^2 - n + n // jk <= n^2 jk = nk + j; // jp <= n^2 - n // ji <= n^2 - n + n or ji <= n^2 (since 0 < j <= n) ji = jp + j; hold = -a[jk - 1]; a[jk - 1] = a[ji - 1]; a[ji - 1] = hold; } L45: if (biga != 0.0F) { goto L48; } d = 0.0F; return; L48: for (i = 1; i <= n; ++i) { if (i == k) { break; } // 0 < nk <= n * (n-1) // 0 < ik <= n^2 ik = nk + i; a[ik - 1] = a[ik - 1] / (-biga); } for (i = 1; i <= n; ++i) { if (i == k) { continue; } // 0 < nk <= n * (n-1) // 0 < ik <= n^2 ik = nk + i; hold = a[ik - 1]; // -n < ij <= 0 ij = i - n; for (j = 1; j <= n; ++j) { // i <= n, ij <= n + n + ... + n (n times) or ij <= n * n ij = ij + n; if (j == k) { continue; } // if i=1, kj = (1 + (n-1) * n) - 1 + n ==> ij = n^2 // if i=n, kj = (n * n) - n + n ==> ij = n ^2 // So j <= n^2 kj = ij - i + k; a[ij - 1] = hold * a[kj - 1] + a[ij - 1]; } } kj = k - n; for (j = 1; j <= n; ++j) { // k <= n, kj <= n + n + ... + n (n times) or kj <= n * n kj = kj + n; if (j == k) { continue; } // Accessing upto n^2 - 1 a[kj - 1] = a[kj - 1] / biga; } d = d * biga; a[kk - 1] = 1.0F / biga; } k = n; L100: k = k - 1; if (k < 1) { return; } i = (int)l[k - 1]; if (i <= k) { goto L120; } // 0 <= jq <= n^2 - n // 0 <= jr <= n^2 - n jq = n * (k - 1); jr = n * (i - 1); for (j = 1; j <= n; ++j) { // jk <= n^2 - n + n // jk <= n^2 jk = jq + j; hold = a[jk - 1]; // ji <= n^2 - n + n // ji <= n^2 ji = jr + j; a[jk - 1] = -a[ji - 1]; a[ji - 1] = hold; } L120: j = (int)m[k - 1]; if (j <= k) { goto L100; } // 0 <= jr <= n^2 - n ki = k - n; for (i = 1; i <= n; ++i) { // ki <= n + n + ... + n (n times) or ki <= n * n ki = ki + n; hold = a[ki - 1]; // if i=1, ji = (1 + (n-1) * n) - 1 + n ==> ij = n^2 // if i=n, ji = (n * n) - n + n ==> ij = n ^2 // Therefore ji <= n^2 ji = ki - k + j; a[ki - 1] = -a[ji - 1]; } a[ji - 1] = hold; goto L100; } private static void MinV2(float[] a, ref int n, out float d, float[] l, float[] m) { float biga, hold; int i, j, k; d = 1.0F; for (k = 1; k <= n; ++k) { l[k - 1] = k; m[k - 1] = k; biga = a[(k - 1) * n + (k - 1)]; for (j = k; j <= n; ++j) { for (i = k; i <= n; ++i) { // Accessing upto n^2 - n + n - 1 ==> n^2 - 1 if (System.Math.Abs(biga) >= System.Math.Abs(a[(i - 1) * n + (j - 1)])) { continue; } biga = a[(i - 1) * n + (j - 1)]; l[k - 1] = i; m[k - 1] = j; } } j = (int)l[k - 1]; if (l[k - 1] <= k) { goto L200; } for (i = 1; i <= n; ++i) { // Accessing upto n^2 - n + n - 1 ==> n^2 - 1 hold = -a[(k - 1) * n + (i - 1)]; a[(k - 1) * n + (i - 1)] = a[(j - 1) * n + (i - 1)]; a[(j - 1) * n + (i - 1)] = hold; } L200: i = (int)m[k - 1]; if (m[k - 1] <= k) { goto L250; } for (j = 1; j <= n; ++j) { // Accessing upto n^2 - n + n - 1 ==> n^2 - 1 hold = -a[(j - 1) * n + (k - 1)]; a[(j - 1) * n + (k - 1)] = a[(j - 1) * n + (i - 1)]; a[(j - 1) * n + (i - 1)] = hold; } L250: if (biga != 0.0F) { goto L300; } d = 0.0F; return; L300: for (i = 1; i <= n; ++i) { if (i != k) { // Accessing upto n^2 - n + n - 1 ==> n^2 - 1 a[(i - 1) * n + (k - 1)] = a[(i - 1) * n + (k - 1)] / (-biga); } } for (i = 1; i <= n; ++i) { if (i == k) { continue; } for (j = 1; j <= n; ++j) { if (j != k) { // Accessing upto n^2 - n + n - 1 ==> n^2 - 1 a[(i - 1) * n + (j - 1)] = a[(i - 1) * n + (k - 1)] * a[(k - 1) * n + (j - 1)] + a[(i - 1) * n + (j - 1)]; } } } for (j = 1; j < n; ++j) { if (j != k) { // Accessing upto n^2 - n + n - 1 ==> n^2 - 1 a[(k - 1) * n + (j - 1)] = a[(k - 1) * n + (j - 1)] / biga; } } d = d * biga; a[(k - 1) * n + (k - 1)] = 1.0F / biga; } k = n; L400: k = k - 1; if (k < 1) { return; } i = (int)l[k - 1]; if (i <= k) { goto L450; } for (j = 1; j <= n; ++j) { // Accessing upto n^2 - n + n - 1 ==> n^2 - 1 hold = a[(j - 1) * n + (k - 1)]; a[(j - 1) * n + (k - 1)] = -a[(j - 1) * n + (i - 1)]; a[(j - 1) * n + (i - 1)] = hold; } L450: j = (int)m[k - 1]; if (j <= k) { goto L400; } for (i = 1; i <= n; ++i) { // Accessing upto n^2 - n + n - 1 ==> n^2 - 1 hold = a[(k - 1) * n + (i - 1)]; a[(k - 1) * n + (i - 1)] = -a[(j - 1) * n + (i - 1)]; a[(j - 1) * n + (i - 1)] = hold; } goto L400; } private static void MProd(float[] a, float[] b, float[] c, ref int n) { int i, j, k; for (i = 1; i <= n; ++i) { for (j = 1; j <= n; ++j) { // Accessing upto n^2 - n + n - 1 ==> n^2 - 1 c[(i - 1) * n + (j - 1)] = 0.0F; for (k = 1; k <= n; ++k) { c[(i - 1) * n + (j - 1)] = c[(i - 1) * n + (j - 1)] + a[(i - 1) * n + (k - 1)] * b[(k - 1) * n + (j - 1)]; } } } return; } private static void CompM(float[] a, float[] b, ref int n) { int i, j; float x, sum = 0.0F; //(starting compare.) for (i = 1; i <= n; ++i) { for (j = 1; j <= n; ++j) { x = 0.0F; if (i == j) { x = 1.0F; } sum = sum + System.Math.Abs(System.Math.Abs(a[(i - 1) * n + (j - 1)]) - x); } } return; } [Benchmark] public static void Test() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { Bench(); } } } private static bool TestBase() { bool result = Bench(); return result; } public static int Main() { bool result = TestBase(); return (result ? 100 : -1); } } }
// //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public //License along with this library; if not, write to the Free Software //Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //============================================================================= using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Windows.Forms; using System.Threading; using System.Drawing.Imaging; using System.IO; using System.Text; using System.Runtime.InteropServices; //using System.Diagnostics; namespace ZedGraph { partial class ZedGraphControl { #region ContextMenu // Revision: JCarpenter 10/06 /// <summary> /// Public enumeration that specifies the type of /// object present at the Context Menu's mouse location /// </summary> public enum ContextMenuObjectState { /// <summary> /// The object is an Inactive Curve Item at the Context Menu's mouse position /// </summary> InactiveSelection, /// <summary> /// The object is an active Curve Item at the Context Menu's mouse position /// </summary> ActiveSelection, /// <summary> /// There is no selectable object present at the Context Menu's mouse position /// </summary> Background } //Revision: JCarpenter 10/06 /// <summary> /// Find the object currently under the mouse cursor, and return its state. /// </summary> private ContextMenuObjectState GetObjectState() { ContextMenuObjectState objState = ContextMenuObjectState.Background; // Determine object state Point mousePt = this.PointToClient( Control.MousePosition ); int iPt; GraphPane pane; object nearestObj; using ( Graphics g = this.CreateGraphics() ) { if ( this.MasterPane.FindNearestPaneObject( mousePt, g, out pane, out nearestObj, out iPt ) ) { CurveItem item = nearestObj as CurveItem; if ( item != null && iPt >= 0 ) { if ( item.IsSelected ) objState = ContextMenuObjectState.ActiveSelection; else objState = ContextMenuObjectState.InactiveSelection; } } } return objState; } /// <summary> /// protected method to handle the popup context menu in the <see cref="ZedGraphControl"/>. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void contextMenuStrip1_Opening( object sender, CancelEventArgs e ) { // disable context menu by default e.Cancel = true; ContextMenuStrip menuStrip = sender as ContextMenuStrip; //Revision: JCarpenter 10/06 ContextMenuObjectState objState = GetObjectState(); if ( _masterPane != null && menuStrip != null ) { menuStrip.Items.Clear(); _isZooming = false; _isPanning = false; Cursor.Current = Cursors.Default; _menuClickPt = this.PointToClient( Control.MousePosition ); GraphPane pane = _masterPane.FindPane( _menuClickPt ); if ( _isShowContextMenu ) { string menuStr = string.Empty; ToolStripMenuItem item = new ToolStripMenuItem(); item.Name = "copy"; item.Tag = "copy"; item.Text = _resourceManager.GetString( "copy" ); item.Click += new System.EventHandler( this.MenuClick_Copy ); menuStrip.Items.Add( item ); item = new ToolStripMenuItem(); item.Name = "save_as"; item.Tag = "save_as"; item.Text = _resourceManager.GetString( "save_as" ); item.Click += new System.EventHandler( this.MenuClick_SaveAs ); menuStrip.Items.Add( item ); item = new ToolStripMenuItem(); item.Name = "page_setup"; item.Tag = "page_setup"; item.Text = _resourceManager.GetString( "page_setup" ); item.Click += new System.EventHandler( this.MenuClick_PageSetup ); menuStrip.Items.Add( item ); item = new ToolStripMenuItem(); item.Name = "print"; item.Tag = "print"; item.Text = _resourceManager.GetString( "print" ); item.Click += new System.EventHandler( this.MenuClick_Print ); menuStrip.Items.Add( item ); item = new ToolStripMenuItem(); item.Name = "show_val"; item.Tag = "show_val"; item.Text = _resourceManager.GetString( "show_val" ); item.Click += new System.EventHandler( this.MenuClick_ShowValues ); item.Checked = this.IsShowPointValues; menuStrip.Items.Add( item ); item = new ToolStripMenuItem(); item.Name = "unzoom"; item.Tag = "unzoom"; if ( pane == null || pane.ZoomStack.IsEmpty ) menuStr = _resourceManager.GetString( "unzoom" ); else { switch ( pane.ZoomStack.Top.Type ) { case ZoomState.StateType.Zoom: case ZoomState.StateType.WheelZoom: menuStr = _resourceManager.GetString( "unzoom" ); break; case ZoomState.StateType.Pan: menuStr = _resourceManager.GetString( "unpan" ); break; case ZoomState.StateType.Scroll: menuStr = _resourceManager.GetString( "unscroll" ); break; } } //menuItem.Text = "Un-" + ( ( pane == null || pane.zoomStack.IsEmpty ) ? // "Zoom" : pane.zoomStack.Top.TypeString ); item.Text = menuStr; item.Click += new EventHandler( this.MenuClick_ZoomOut ); if ( pane == null || pane.ZoomStack.IsEmpty ) item.Enabled = false; menuStrip.Items.Add( item ); item = new ToolStripMenuItem(); item.Name = "undo_all"; item.Tag = "undo_all"; menuStr = _resourceManager.GetString( "undo_all" ); item.Text = menuStr; item.Click += new EventHandler( this.MenuClick_ZoomOutAll ); if ( pane == null || pane.ZoomStack.IsEmpty ) item.Enabled = false; menuStrip.Items.Add( item ); item = new ToolStripMenuItem(); item.Name = "set_default"; item.Tag = "set_default"; menuStr = _resourceManager.GetString( "set_default" ); item.Text = menuStr; item.Click += new EventHandler( this.MenuClick_RestoreScale ); if ( pane == null ) item.Enabled = false; menuStrip.Items.Add( item ); // if e.Cancel is set to false, the context menu does not display // it is initially set to false because the context menu has no items e.Cancel = false; // Provide Callback for User to edit the context menu //Revision: JCarpenter 10/06 - add ContextMenuObjectState objState if ( this.ContextMenuBuilder != null ) this.ContextMenuBuilder( this, menuStrip, _menuClickPt, objState ); } } } /// <summary> /// Handler for the "Copy" context menu item. Copies the current image to a bitmap on the /// clipboard. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void MenuClick_Copy( System.Object sender, System.EventArgs e ) { Copy( _isShowCopyMessage ); } /// <summary> /// Handler for the "Copy" context menu item. Copies the current image to a bitmap on the /// clipboard. /// </summary> /// <param name="isShowMessage">boolean value that determines whether or not a prompt will be /// displayed. true to show a message of "Image Copied to ClipBoard".</param> public void Copy( bool isShowMessage ) { if ( _masterPane != null ) { ClipboardCopyThread(); if ( isShowMessage ) { string str = _resourceManager.GetString( "copied_to_clip" ); //MessageBox.Show( "Image Copied to ClipBoard" ); MessageBox.Show( str ); } } } /// <summary> /// A threaded version of the copy method to avoid crash with MTA /// </summary> private void ClipboardCopyThread() { Clipboard.SetDataObject( ImageRender(), true ); } // /// <summary> /// Setup for creation of a new image, applying appropriate anti-alias properties and /// returning the resultant image file /// </summary> /// <returns></returns> private Image ImageRender() { return _masterPane.GetImage( _masterPane.IsAntiAlias ); } /// <summary> /// Special handler that copies the current image to an Emf file on the clipboard. /// </summary> /// <remarks>This version is similar to the regular <see cref="Copy" /> method, except that /// it will place an Emf image (vector) on the ClipBoard instead of the regular bitmap.</remarks> /// <param name="isShowMessage">boolean value that determines whether or not a prompt will be /// displayed. true to show a message of "Image Copied to ClipBoard".</param> public void CopyEmf(bool isShowMessage) { if (_masterPane != null) { ClipboardCopyThreadEmf(); if (isShowMessage) { string str = _resourceManager.GetString("copied_to_clip"); MessageBox.Show(str); } } } /// <summary> /// A threaded version of the copy method to avoid crash with MTA /// </summary> private void ClipboardCopyThreadEmf() { using (Graphics g = this.CreateGraphics()) { IntPtr hdc = g.GetHdc(); Metafile metaFile = new Metafile(hdc, EmfType.EmfPlusDual); g.ReleaseHdc(hdc); using (Graphics gMeta = Graphics.FromImage(metaFile)) { this._masterPane.Draw( gMeta ); } //IntPtr hMeta = metaFile.GetHenhmetafile(); ClipboardMetafileHelper.PutEnhMetafileOnClipboard( this.Handle, metaFile ); //System.Windows.Forms.Clipboard.SetDataObject(hMeta, true); //g.Dispose(); } } /// <summary> /// Handler for the "Save Image As" context menu item. Copies the current image to the selected /// file. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void MenuClick_SaveAs( System.Object sender, System.EventArgs e ) { SaveAs(); } /// <summary> /// Handler for the "Save Image As" context menu item. Copies the current image to the selected /// file in either the Emf (vector), or a variety of Bitmap formats. /// </summary> /// <remarks> /// Note that <see cref="SaveAsBitmap" /> and <see cref="SaveAsEmf" /> methods are provided /// which allow for Bitmap-only or Emf-only handling of the "Save As" context menu item. /// </remarks> public void SaveAs() { SaveAs( null ); } /// <summary> /// Copies the current image to the selected file in /// Emf (vector), or a variety of Bitmap formats. /// </summary> /// <param name="DefaultFileName"> /// Accepts a default file name for the file dialog (if "" or null, default is not used) /// </param> /// <returns> /// The file name saved, or "" if cancelled. /// </returns> /// <remarks> /// Note that <see cref="SaveAsBitmap" /> and <see cref="SaveAsEmf" /> methods are provided /// which allow for Bitmap-only or Emf-only handling of the "Save As" context menu item. /// </remarks> public String SaveAs( String DefaultFileName ) { if ( _masterPane != null ) { _saveFileDialog.Filter = "Emf Format (*.emf)|*.emf|" + "PNG Format (*.png)|*.png|" + "Gif Format (*.gif)|*.gif|" + "Jpeg Format (*.jpg)|*.jpg|" + "Tiff Format (*.tif)|*.tif|" + "Bmp Format (*.bmp)|*.bmp"; if ( DefaultFileName != null && DefaultFileName.Length > 0 ) { String ext = System.IO.Path.GetExtension( DefaultFileName ).ToLower(); switch (ext) { case ".emf": _saveFileDialog.FilterIndex = 1; break; case ".png": _saveFileDialog.FilterIndex = 2; break; case ".gif": _saveFileDialog.FilterIndex = 3; break; case ".jpeg": case ".jpg": _saveFileDialog.FilterIndex = 4; break; case ".tiff": case ".tif": _saveFileDialog.FilterIndex = 5; break; case ".bmp": _saveFileDialog.FilterIndex = 6; break; } //If we were passed a file name, not just an extension, use it if ( DefaultFileName.Length > ext.Length ) { _saveFileDialog.FileName = DefaultFileName; } } if ( _saveFileDialog.ShowDialog() == DialogResult.OK ) { Stream myStream = _saveFileDialog.OpenFile(); if ( myStream != null ) { if ( _saveFileDialog.FilterIndex == 1 ) { myStream.Close(); SaveEmfFile( _saveFileDialog.FileName ); } else { ImageFormat format = ImageFormat.Png; switch (_saveFileDialog.FilterIndex) { case 2: format = ImageFormat.Png; break; case 3: format = ImageFormat.Gif; break; case 4: format = ImageFormat.Jpeg; break; case 5: format = ImageFormat.Tiff; break; case 6: format = ImageFormat.Bmp; break; } ImageRender().Save( myStream, format ); //_masterPane.GetImage().Save( myStream, format ); myStream.Close(); } return _saveFileDialog.FileName; } } } return ""; } /// <summary> /// Handler for the "Save Image As" context menu item. Copies the current image to the selected /// Bitmap file. /// </summary> /// <remarks> /// Note that this handler saves as a bitmap only. The default handler is /// <see cref="SaveAs()" />, which allows for Bitmap or EMF formats /// </remarks> public void SaveAsBitmap() { if ( _masterPane != null ) { _saveFileDialog.Filter = "PNG Format (*.png)|*.png|" + "Gif Format (*.gif)|*.gif|" + "Jpeg Format (*.jpg)|*.jpg|" + "Tiff Format (*.tif)|*.tif|" + "Bmp Format (*.bmp)|*.bmp"; if ( _saveFileDialog.ShowDialog() == DialogResult.OK ) { ImageFormat format = ImageFormat.Png; if ( _saveFileDialog.FilterIndex == 2 ) format = ImageFormat.Gif; else if ( _saveFileDialog.FilterIndex == 3 ) format = ImageFormat.Jpeg; else if ( _saveFileDialog.FilterIndex == 4 ) format = ImageFormat.Tiff; else if ( _saveFileDialog.FilterIndex == 5 ) format = ImageFormat.Bmp; Stream myStream = _saveFileDialog.OpenFile(); if ( myStream != null ) { //_masterPane.GetImage().Save( myStream, format ); ImageRender().Save( myStream, format ); myStream.Close(); } } } } /// <summary> /// Handler for the "Save Image As" context menu item. Copies the current image to the selected /// Emf format file. /// </summary> /// <remarks> /// Note that this handler saves as an Emf format only. The default handler is /// <see cref="SaveAs()" />, which allows for Bitmap or EMF formats. /// </remarks> public void SaveAsEmf() { if ( _masterPane != null ) { _saveFileDialog.Filter = "Emf Format (*.emf)|*.emf"; if ( _saveFileDialog.ShowDialog() == DialogResult.OK ) { Stream myStream = _saveFileDialog.OpenFile(); if ( myStream != null ) { myStream.Close(); //_masterPane.GetMetafile().Save( _saveFileDialog.FileName ); SaveEmfFile(_saveFileDialog.FileName); } } } } /// <summary> /// Save the current Graph to the specified filename in EMF (vector) format. /// See <see cref="SaveAsEmf()" /> for public access. /// </summary> /// <remarks> /// Note that this handler saves as an Emf format only. The default handler is /// <see cref="SaveAs()" />, which allows for Bitmap or EMF formats. /// </remarks> internal void SaveEmfFile( string fileName ) { using (Graphics g = this.CreateGraphics()) { IntPtr hdc = g.GetHdc(); Metafile metaFile = this._masterPane.GetMetafile(); ClipboardMetafileHelper.SaveEnhMetafileToFile(metaFile, fileName ); g.ReleaseHdc(hdc); //g.Dispose(); } } internal class ClipboardMetafileHelper { [DllImport("user32.dll")] static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll")] static extern bool EmptyClipboard(); [DllImport("user32.dll")] static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem); [DllImport("user32.dll")] static extern bool CloseClipboard(); [DllImport("gdi32.dll")] static extern IntPtr CopyEnhMetaFile(IntPtr hemfSrc, System.Text.StringBuilder hNULL); [DllImport("gdi32.dll")] static extern bool DeleteEnhMetaFile(IntPtr hemf); static internal bool SaveEnhMetafileToFile( Metafile mf, string fileName ) { bool bResult = false; IntPtr hEMF; hEMF = mf.GetHenhmetafile(); // invalidates mf if (!hEMF.Equals(new IntPtr(0))) { StringBuilder tempName = new StringBuilder(fileName); IntPtr hEMF2 = CopyEnhMetaFile(hEMF, tempName); DeleteEnhMetaFile(hEMF2); DeleteEnhMetaFile(hEMF); } return bResult; } static internal bool SaveEnhMetafileToFile(Metafile mf) { bool bResult = false; IntPtr hEMF; hEMF = mf.GetHenhmetafile(); // invalidates mf if (!hEMF.Equals(new IntPtr(0))) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Extended Metafile (*.emf)|*.emf"; sfd.DefaultExt = ".emf"; if (sfd.ShowDialog() == DialogResult.OK) { StringBuilder temp = new StringBuilder(sfd.FileName); CopyEnhMetaFile(hEMF, temp); } DeleteEnhMetaFile(hEMF); } return bResult; } // Metafile mf is set to a state that is not valid inside this function. static internal bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile mf) { bool bResult = false; IntPtr hEMF, hEMF2; hEMF = mf.GetHenhmetafile(); // invalidates mf if (!hEMF.Equals(new IntPtr(0))) { hEMF2 = CopyEnhMetaFile(hEMF, null); if (!hEMF2.Equals(new IntPtr(0))) { if (OpenClipboard(hWnd)) { if (EmptyClipboard()) { IntPtr hRes = SetClipboardData(14 /*CF_ENHMETAFILE*/, hEMF2); bResult = hRes.Equals(hEMF2); CloseClipboard(); } } } DeleteEnhMetaFile(hEMF); } return bResult; } } /// <summary> /// Handler for the "Show Values" context menu item. Toggles the <see cref="IsShowPointValues"/> /// property, which activates the point value tooltips. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void MenuClick_ShowValues( object sender, System.EventArgs e ) { ToolStripMenuItem item = sender as ToolStripMenuItem; if ( item != null ) this.IsShowPointValues = !item.Checked; } /// <summary> /// Handler for the "Set Scale to Default" context menu item. Sets the scale ranging to /// full auto mode for all axes. /// </summary> /// <remarks> /// This method differs from the <see cref="ZoomOutAll" /> method in that it sets the scales /// to full auto mode. The <see cref="ZoomOutAll" /> method sets the scales to their initial /// setting prior to any user actions (which may or may not be full auto mode). /// </remarks> /// <param name="sender"></param> /// <param name="e"></param> protected void MenuClick_RestoreScale( object sender, EventArgs e ) { if ( _masterPane != null ) { GraphPane pane = _masterPane.FindPane( _menuClickPt ); RestoreScale( pane ); } } /// <summary> /// Handler for the "Set Scale to Default" context menu item. Sets the scale ranging to /// full auto mode for all axes. /// </summary> /// <remarks> /// This method differs from the <see cref="ZoomOutAll" /> method in that it sets the scales /// to full auto mode. The <see cref="ZoomOutAll" /> method sets the scales to their initial /// setting prior to any user actions (which may or may not be full auto mode). /// </remarks> /// <param name="primaryPane">The <see cref="GraphPane" /> object which is to have the /// scale restored</param> public void RestoreScale( GraphPane primaryPane ) { if ( primaryPane != null ) { //Go ahead and save the old zoomstates, which provides an "undo"-like capability //ZoomState oldState = primaryPane.ZoomStack.Push( primaryPane, ZoomState.StateType.Zoom ); ZoomState oldState = new ZoomState( primaryPane, ZoomState.StateType.Zoom ); using ( Graphics g = this.CreateGraphics() ) { if ( _isSynchronizeXAxes || _isSynchronizeYAxes ) { foreach ( GraphPane pane in _masterPane._paneList ) { pane.ZoomStack.Push( pane, ZoomState.StateType.Zoom ); ResetAutoScale( pane, g ); } } else { primaryPane.ZoomStack.Push( primaryPane, ZoomState.StateType.Zoom ); ResetAutoScale( primaryPane, g ); } // Provide Callback to notify the user of zoom events if ( this.ZoomEvent != null ) this.ZoomEvent(this, oldState, new ZoomState(primaryPane, ZoomState.StateType.Zoom), primaryPane.CenterPoint); //g.Dispose(); } Refresh(); } } private void ResetAutoScale( GraphPane pane, Graphics g ) { pane.XAxis.ResetAutoScale( pane, g ); pane.X2Axis.ResetAutoScale( pane, g ); foreach ( YAxis axis in pane.YAxisList ) axis.ResetAutoScale( pane, g ); foreach ( Y2Axis axis in pane.Y2AxisList ) axis.ResetAutoScale( pane, g ); } /* public void RestoreScale( GraphPane primaryPane ) { if ( primaryPane != null ) { Graphics g = this.CreateGraphics(); ZoomState oldState = new ZoomState( primaryPane, ZoomState.StateType.Zoom ); //ZoomState newState = null; if ( _isSynchronizeXAxes || _isSynchronizeYAxes ) { foreach ( GraphPane pane in _masterPane._paneList ) { if ( pane == primaryPane ) { pane.XAxis.ResetAutoScale( pane, g ); foreach ( YAxis axis in pane.YAxisList ) axis.ResetAutoScale( pane, g ); foreach ( Y2Axis axis in pane.Y2AxisList ) axis.ResetAutoScale( pane, g ); } } } else { primaryPane.XAxis.ResetAutoScale( primaryPane, g ); foreach ( YAxis axis in primaryPane.YAxisList ) axis.ResetAutoScale( primaryPane, g ); foreach ( Y2Axis axis in primaryPane.Y2AxisList ) axis.ResetAutoScale( primaryPane, g ); } // Provide Callback to notify the user of zoom events if ( this.ZoomEvent != null ) this.ZoomEvent( this, oldState, new ZoomState( primaryPane, ZoomState.StateType.Zoom ) ); g.Dispose(); Refresh(); } } */ /* public void ZoomOutAll( GraphPane primaryPane ) { if ( primaryPane != null && !primaryPane.ZoomStack.IsEmpty ) { ZoomState.StateType type = primaryPane.ZoomStack.Top.Type; ZoomState oldState = new ZoomState( primaryPane, type ); //ZoomState newState = pane.ZoomStack.PopAll( pane ); ZoomState newState = null; if ( _isSynchronizeXAxes || _isSynchronizeYAxes ) { foreach ( GraphPane pane in _masterPane._paneList ) { ZoomState state = pane.ZoomStack.PopAll( pane ); if ( pane == primaryPane ) newState = state; } } else newState = primaryPane.ZoomStack.PopAll( primaryPane ); // Provide Callback to notify the user of zoom events if ( this.ZoomEvent != null ) this.ZoomEvent( this, oldState, newState ); Refresh(); } } */ /// <summary> /// Handler for the "UnZoom/UnPan" context menu item. Restores the scale ranges to the values /// before the last zoom or pan operation. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void MenuClick_ZoomOut( System.Object sender, System.EventArgs e ) { if ( _masterPane != null ) { GraphPane pane = _masterPane.FindPane( _menuClickPt ); ZoomOut( pane ); } } /// <summary> /// Handler for the "UnZoom/UnPan" context menu item. Restores the scale ranges to the values /// before the last zoom, pan, or scroll operation. /// </summary> /// <remarks> /// Triggers a <see cref="ZoomEvent" /> for any type of undo (including pan, scroll, zoom, and /// wheelzoom). This method will affect all the /// <see cref="GraphPane" /> objects in the <see cref="MasterPane" /> if /// <see cref="IsSynchronizeXAxes" /> or <see cref="IsSynchronizeYAxes" /> is true. /// </remarks> /// <param name="primaryPane">The primary <see cref="GraphPane" /> object which is to be /// zoomed out</param> public void ZoomOut( GraphPane primaryPane ) { if ( primaryPane != null && !primaryPane.ZoomStack.IsEmpty ) { ZoomState.StateType type = primaryPane.ZoomStack.Top.Type; ZoomState oldState = new ZoomState( primaryPane, type ); ZoomState newState = null; if ( _isSynchronizeXAxes || _isSynchronizeYAxes ) { foreach ( GraphPane pane in _masterPane._paneList ) { ZoomState state = pane.ZoomStack.Pop( pane ); if ( pane == primaryPane ) newState = state; } } else newState = primaryPane.ZoomStack.Pop( primaryPane ); // Provide Callback to notify the user of zoom events if ( this.ZoomEvent != null ) this.ZoomEvent(this, oldState, newState, primaryPane.CenterPoint); Refresh(); } } /// <summary> /// Handler for the "Undo All Zoom/Pan" context menu item. Restores the scale ranges to the values /// before all zoom and pan operations /// </summary> /// <remarks> /// This method differs from the <see cref="RestoreScale" /> method in that it sets the scales /// to their initial setting prior to any user actions. The <see cref="RestoreScale" /> method /// sets the scales to full auto mode (regardless of what the initial setting may have been). /// </remarks> /// <param name="sender"></param> /// <param name="e"></param> protected void MenuClick_ZoomOutAll( System.Object sender, System.EventArgs e ) { if ( _masterPane != null ) { GraphPane pane = _masterPane.FindPane( _menuClickPt ); ZoomOutAll( pane ); } } /// <summary> /// Handler for the "Undo All Zoom/Pan" context menu item. Restores the scale ranges to the values /// before all zoom and pan operations /// </summary> /// <remarks> /// This method differs from the <see cref="RestoreScale" /> method in that it sets the scales /// to their initial setting prior to any user actions. The <see cref="RestoreScale" /> method /// sets the scales to full auto mode (regardless of what the initial setting may have been). /// </remarks> /// <param name="primaryPane">The <see cref="GraphPane" /> object which is to be zoomed out</param> public void ZoomOutAll( GraphPane primaryPane ) { if ( primaryPane != null && !primaryPane.ZoomStack.IsEmpty ) { ZoomState.StateType type = primaryPane.ZoomStack.Top.Type; ZoomState oldState = new ZoomState( primaryPane, type ); //ZoomState newState = pane.ZoomStack.PopAll( pane ); ZoomState newState = null; if ( _isSynchronizeXAxes || _isSynchronizeYAxes ) { foreach ( GraphPane pane in _masterPane._paneList ) { ZoomState state = pane.ZoomStack.PopAll( pane ); if ( pane == primaryPane ) newState = state; } } else newState = primaryPane.ZoomStack.PopAll( primaryPane ); // Provide Callback to notify the user of zoom events if ( this.ZoomEvent != null ) this.ZoomEvent(this, oldState, newState, primaryPane.CenterPoint); Refresh(); } } #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.Runtime.InteropServices; using System.Diagnostics; using System.ComponentModel; using System.Drawing.Internal; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing.Drawing2D { public sealed class PathGradientBrush : Brush { public PathGradientBrush(PointF[] points) : this(points, WrapMode.Clamp) { } public unsafe PathGradientBrush(PointF[] points, WrapMode wrapMode) { if (points == null) throw new ArgumentNullException(nameof(points)); if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp) throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); // GdipCreatePathGradient returns InsufficientBuffer for less than 3 points, which we turn into // OutOfMemoryException(). We used to copy nothing into an empty native buffer for zero points, // which gives a valid pointer. Fixing an empty array gives a null pointer, which causes an // InvalidParameter result, which we turn into an ArgumentException. Matching the old throw. if (points.Length == 0) throw new OutOfMemoryException(); fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipCreatePathGradient( p, points.Length, wrapMode, out IntPtr nativeBrush)); SetNativeBrushInternal(nativeBrush); } } public PathGradientBrush(Point[] points) : this(points, WrapMode.Clamp) { } public unsafe PathGradientBrush(Point[] points, WrapMode wrapMode) { if (points == null) throw new ArgumentNullException(nameof(points)); if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp) throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); // GdipCreatePathGradient returns InsufficientBuffer for less than 3 points, which we turn into // OutOfMemoryException(). We used to copy nothing into an empty native buffer for zero points, // which gives a valid pointer. Fixing an empty array gives a null pointer, which causes an // InvalidParameter result, which we turn into an ArgumentException. Matching the old throw. if (points.Length == 0) throw new OutOfMemoryException(); fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipCreatePathGradientI( p, points.Length, wrapMode, out IntPtr nativeBrush)); SetNativeBrushInternal(nativeBrush); } } public PathGradientBrush(GraphicsPath path) { if (path == null) throw new ArgumentNullException(nameof(path)); Gdip.CheckStatus(Gdip.GdipCreatePathGradientFromPath(new HandleRef(path, path._nativePath), out IntPtr nativeBrush)); SetNativeBrushInternal(nativeBrush); } internal PathGradientBrush(IntPtr nativeBrush) { Debug.Assert(nativeBrush != IntPtr.Zero, "Initializing native brush with null."); SetNativeBrushInternal(nativeBrush); } public override object Clone() { Gdip.CheckStatus(Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out IntPtr clonedBrush)); return new PathGradientBrush(clonedBrush); } public Color CenterColor { get { Gdip.CheckStatus(Gdip.GdipGetPathGradientCenterColor(new HandleRef(this, NativeBrush), out int argb)); return Color.FromArgb(argb); } set { Gdip.CheckStatus(Gdip.GdipSetPathGradientCenterColor(new HandleRef(this, NativeBrush), value.ToArgb())); } } public Color[] SurroundColors { get { Gdip.CheckStatus(Gdip.GdipGetPathGradientSurroundColorCount( new HandleRef(this, NativeBrush), out int count)); int[] argbs = new int[count]; Gdip.CheckStatus(Gdip.GdipGetPathGradientSurroundColorsWithCount( new HandleRef(this, NativeBrush), argbs, ref count)); Color[] colors = new Color[count]; for (int i = 0; i < count; i++) colors[i] = Color.FromArgb(argbs[i]); return colors; } set { int count = value.Length; int[] argbs = new int[count]; for (int i = 0; i < value.Length; i++) argbs[i] = value[i].ToArgb(); Gdip.CheckStatus(Gdip.GdipSetPathGradientSurroundColorsWithCount( new HandleRef(this, NativeBrush), argbs, ref count)); } } public PointF CenterPoint { get { Gdip.CheckStatus(Gdip.GdipGetPathGradientCenterPoint(new HandleRef(this, NativeBrush), out PointF point)); return point; } set { Gdip.CheckStatus(Gdip.GdipSetPathGradientCenterPoint(new HandleRef(this, NativeBrush), ref value)); } } public RectangleF Rectangle { get { Gdip.CheckStatus(Gdip.GdipGetPathGradientRect(new HandleRef(this, NativeBrush), out RectangleF rect)); return rect; } } public Blend Blend { get { // Figure out the size of blend factor array Gdip.CheckStatus(Gdip.GdipGetPathGradientBlendCount(new HandleRef(this, NativeBrush), out int retval)); // Allocate temporary native memory buffer int count = retval; var factors = new float[count]; var positions = new float[count]; // Retrieve horizontal blend factors Gdip.CheckStatus(Gdip.GdipGetPathGradientBlend(new HandleRef(this, NativeBrush), factors, positions, count)); // Return the result in a managed array Blend blend = new Blend(count) { Factors = factors, Positions = positions }; return blend; } set { // This is the behavior on Desktop if (value == null || value.Factors == null) throw new NullReferenceException(); // The Desktop implementation throws ArgumentNullException("source") because it never validates the value of value.Positions, and then passes it // on to Marshal.Copy(value.Positions, 0, positions, count);. The first argument of Marshal.Copy is source, hence this exception. if (value.Positions == null) throw new ArgumentNullException("source"); int count = value.Factors.Length; // Explicit argument validation, because libgdiplus does not correctly validate all parameters. if (count == 0 || value.Positions.Length == 0) throw new ArgumentException(SR.BlendObjectMustHaveTwoElements); if (count >= 2 && count != value.Positions.Length) throw new ArgumentOutOfRangeException(); if (count >= 2 && value.Positions[0] != 0.0F) throw new ArgumentException(SR.BlendObjectFirstElementInvalid); if (count >= 2 && value.Positions[count - 1] != 1.0F) throw new ArgumentException(SR.BlendObjectLastElementInvalid); // Allocate temporary native memory buffer // and copy input blend factors into it. IntPtr factors = IntPtr.Zero; IntPtr positions = IntPtr.Zero; try { int size = checked(4 * count); factors = Marshal.AllocHGlobal(size); positions = Marshal.AllocHGlobal(size); Marshal.Copy(value.Factors, 0, factors, count); Marshal.Copy(value.Positions, 0, positions, count); // Set blend factors Gdip.CheckStatus(Gdip.GdipSetPathGradientBlend(new HandleRef(this, NativeBrush), new HandleRef(null, factors), new HandleRef(null, positions), count)); } finally { if (factors != IntPtr.Zero) { Marshal.FreeHGlobal(factors); } if (positions != IntPtr.Zero) { Marshal.FreeHGlobal(positions); } } } } public void SetSigmaBellShape(float focus) => SetSigmaBellShape(focus, (float)1.0); public void SetSigmaBellShape(float focus, float scale) { if (focus < 0 || focus > 1) throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus)); if (scale < 0 || scale > 1) throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale)); Gdip.CheckStatus(Gdip.GdipSetPathGradientSigmaBlend(new HandleRef(this, NativeBrush), focus, scale)); } public void SetBlendTriangularShape(float focus) => SetBlendTriangularShape(focus, (float)1.0); public void SetBlendTriangularShape(float focus, float scale) { if (focus < 0 || focus > 1) throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus)); if (scale < 0 || scale > 1) throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale)); Gdip.CheckStatus(Gdip.GdipSetPathGradientLinearBlend(new HandleRef(this, NativeBrush), focus, scale)); } public ColorBlend InterpolationColors { get { // Figure out the size of blend factor array Gdip.CheckStatus(Gdip.GdipGetPathGradientPresetBlendCount(new HandleRef(this, NativeBrush), out int count)); // If count is 0, then there is nothing to marshal. // In this case, we'll return an empty ColorBlend... if (count == 0) return new ColorBlend(); int[] colors = new int[count]; float[] positions = new float[count]; ColorBlend blend = new ColorBlend(count); // status would fail if we ask points or types with a < 2 count if (count < 2) return blend; // Retrieve horizontal blend factors Gdip.CheckStatus(Gdip.GdipGetPathGradientPresetBlend(new HandleRef(this, NativeBrush), colors, positions, count)); // Return the result in a managed array blend.Positions = positions; // copy ARGB values into Color array of ColorBlend blend.Colors = new Color[count]; for (int i = 0; i < count; i++) { blend.Colors[i] = Color.FromArgb(colors[i]); } return blend; } set { // The Desktop implementation will throw various exceptions - ranging from NullReferenceExceptions to Argument(OutOfRange)Exceptions // depending on how sane the input is. These checks exist to replicate the exact Desktop behavior. int count = value.Colors.Length; if (value.Positions == null) throw new ArgumentNullException("source"); if (value.Colors.Length > value.Positions.Length) throw new ArgumentOutOfRangeException(); if (value.Colors.Length < value.Positions.Length) throw new ArgumentException(); float[] positions = value.Positions; int[] argbs = new int[count]; for (int i = 0; i < count; i++) { argbs[i] = value.Colors[i].ToArgb(); } // Set blend factors Gdip.CheckStatus(Gdip.GdipSetPathGradientPresetBlend(new HandleRef(this, NativeBrush), argbs, positions, count)); } } public Matrix Transform { get { Matrix matrix = new Matrix(); Gdip.CheckStatus(Gdip.GdipGetPathGradientTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.NativeMatrix))); return matrix; } set { if (value == null) throw new ArgumentNullException(nameof(value)); Gdip.CheckStatus(Gdip.GdipSetPathGradientTransform(new HandleRef(this, NativeBrush), new HandleRef(value, value.NativeMatrix))); } } public void ResetTransform() { Gdip.CheckStatus(Gdip.GdipResetPathGradientTransform(new HandleRef(this, NativeBrush))); } public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend); public void MultiplyTransform(Matrix matrix, MatrixOrder order) { if (matrix == null) throw new ArgumentNullException(nameof(matrix)); // Multiplying the transform by a disposed matrix is a nop in GDI+, but throws // with the libgdiplus backend. Simulate a nop for compatability with GDI+. if (matrix.NativeMatrix == IntPtr.Zero) return; Gdip.CheckStatus(Gdip.GdipMultiplyPathGradientTransform( new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.NativeMatrix), order)); } public void TranslateTransform(float dx, float dy) => TranslateTransform(dx, dy, MatrixOrder.Prepend); public void TranslateTransform(float dx, float dy, MatrixOrder order) { Gdip.CheckStatus(Gdip.GdipTranslatePathGradientTransform(new HandleRef(this, NativeBrush), dx, dy, order)); } public void ScaleTransform(float sx, float sy) => ScaleTransform(sx, sy, MatrixOrder.Prepend); public void ScaleTransform(float sx, float sy, MatrixOrder order) { Gdip.CheckStatus(Gdip.GdipScalePathGradientTransform(new HandleRef(this, NativeBrush), sx, sy, order)); } public void RotateTransform(float angle) => RotateTransform(angle, MatrixOrder.Prepend); public void RotateTransform(float angle, MatrixOrder order) { Gdip.CheckStatus(Gdip.GdipRotatePathGradientTransform(new HandleRef(this, NativeBrush), angle, order)); } public PointF FocusScales { get { float[] scaleX = new float[] { 0.0f }; float[] scaleY = new float[] { 0.0f }; Gdip.CheckStatus(Gdip.GdipGetPathGradientFocusScales(new HandleRef(this, NativeBrush), scaleX, scaleY)); return new PointF(scaleX[0], scaleY[0]); } set { Gdip.CheckStatus(Gdip.GdipSetPathGradientFocusScales(new HandleRef(this, NativeBrush), value.X, value.Y)); } } public WrapMode WrapMode { get { Gdip.CheckStatus(Gdip.GdipGetPathGradientWrapMode(new HandleRef(this, NativeBrush), out int mode)); return (WrapMode)mode; } set { if (value < WrapMode.Tile || value > WrapMode.Clamp) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(WrapMode)); Gdip.CheckStatus(Gdip.GdipSetPathGradientWrapMode(new HandleRef(this, NativeBrush), unchecked((int)value))); } } } }
// // Histogram.cs // // Author: // Ruben Vermeersch <ruben@savanne.be> // Larry Ewing <lewing@novell.com> // // Copyright (C) 2004-2010 Novell, Inc. // Copyright (C) 2008, 2010 Ruben Vermeersch // Copyright (C) 2004-2006 Larry Ewing // // 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; namespace FSpot { public class Histogram { #region Color hints private byte [] colors = new byte [] {0x00, 0x00, 0x00, 0xff}; public byte RedColorHint { set { colors [0] = value; } } public byte GreenColorHint { set { colors [1] = value; } } public byte BlueColorHint { set { colors [2] = value; } } public byte BackgroundColorHint { set { colors [3] = value; } } private int [,] values = new int [256, 3]; #endregion public Histogram (Gdk.Pixbuf src) { FillValues (src); } public Histogram () {} private void FillValues (Gdk.Pixbuf src) { values = new int [256, 3]; if (src.BitsPerSample != 8) throw new System.Exception ("Invalid bits per sample"); unsafe { byte * srcb = (byte *)src.Pixels; byte * pixels = srcb; bool alpha = src.HasAlpha; int rowstride = src.Rowstride; int width = src.Width; int height = src.Height; // FIXME array bounds checks slow this down a lot // so we use a pointer. It is sad but I want fastness fixed (int * v = &values [0,0]) { for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { v [*(srcb++) * 3 + 0]++; v [*(srcb++) * 3 + 1]++; v [*(srcb++) * 3 + 2]++; if (alpha) srcb++; } srcb = ((byte *) pixels) + j * rowstride; } } } } private int ChannelSum (int channel) { int sum = 0; for (int i = 0; i < values.GetLength (0); i++) { sum += values [i, channel]; } return sum; } public void GetHighLow (int channel, out int high, out int low) { double total = ChannelSum (channel); double current = 0.0; double percentage; double next_percentage; low = 0; high = 0; for (int i = 0; i < values.GetLength (0) - 1; i++) { current += values [i, channel]; percentage = current / total; next_percentage = (current + values [i + 1, channel]) / total; if (Math.Abs (percentage - 0.006) < Math.Abs (next_percentage - 0.006)) { low = i + 1; break; } } for (int i = values.GetLength (0) - 1; i > 0; i--) { current += values [i, channel]; percentage = current / total; next_percentage = (current + values [i - 1, channel]) / total; if (Math.Abs (percentage - 0.006) < Math.Abs (next_percentage - 0.006)) { high = i - 1; break; } } } private void Draw (Gdk.Pixbuf image) { int max = 0; for (int i = 0; i < values.GetLength (0); i++) { for (int j = 0; j < values.GetLength (1); j++) { max = System.Math.Max (max, values [i, j]); } } unsafe { int height = image.Height; int rowstride = image.Rowstride; int r = 0; int b = 0; int g = 0; for (int i = 0; i < image.Width; i++) { byte * pixels = (byte *)image.Pixels + i * 4; if (max > 0) { r = values [i, 0] * height / max; g = values [i, 1] * height / max; b = values [i, 2] * height / max; } else r = g = b = 0; int top = Math.Max (r, Math.Max (g, b)); int j = 0; for (; j < height - top; j++) { pixels [0] = colors [0]; pixels [1] = colors [1]; pixels [2] = colors [2]; pixels [3] = colors [3]; pixels += rowstride; } for (; j < height; j++) { pixels [0] = (byte) ((j >= height - r) ? 0xff : 0x00); pixels [1] = (byte) ((j >= height - g) ? 0xff : 0x00); pixels [2] = (byte) ((j >= height - b) ? 0xff : 0x00); pixels [3] = 0xff; pixels += rowstride; } } } } public Gdk.Pixbuf Generate (Gdk.Pixbuf input, int max_width) { Gdk.Pixbuf scaled; using (Gdk.Pixbuf pixbuf = Generate (input)) scaled = PixbufUtils.ScaleToMaxSize (pixbuf, max_width, 128); return scaled; } public Gdk.Pixbuf Generate (Gdk.Pixbuf input) { FillValues (input); int height = 128; Gdk.Pixbuf pixbuf = new Gdk.Pixbuf (Gdk.Colorspace.Rgb, true, 8, values.GetLength (0), height); Draw (pixbuf); return pixbuf; } #if FSPOT_HISTOGRAM_MAIN public static void Main (string [] args) { Gtk.Application.Init (); Gdk.Pixbuf pixbuf = new Gdk.Pixbuf (args [0]); Log.DebugFormat ("loaded {0}", args [0]); Histogram hist = new Histogram (); Log.DebugFormat ("loaded histgram", args [0]); Gtk.Window win = new Gtk.Window ("display"); Gtk.Image image = new Gtk.Image (); Gdk.Pixbuf img = hist.Generate (pixbuf); image.Pixbuf = img; win.Add (image); win.ShowAll (); Gtk.Application.Run (); } #endif } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using EventStore.Common.Log; using EventStore.Common.Utils; using EventStore.Core.Data; using EventStore.Core.Exceptions; using EventStore.Core.Index; using EventStore.Core.Index.Hashes; using EventStore.Core.Services; using EventStore.Core.Services.Storage.ReaderIndex; using EventStore.Core.TransactionLog.Chunks.TFChunk; using EventStore.Core.TransactionLog.LogRecords; namespace EventStore.Core.TransactionLog.Chunks { public class TFChunkScavenger { private static readonly ILogger Log = LogManager.GetLoggerFor<TFChunkScavenger>(); private readonly TFChunkDb _db; private readonly ITableIndex _tableIndex; private readonly IHasher _hasher; private readonly IReadIndex _readIndex; private readonly long _maxChunkDataSize; public TFChunkScavenger(TFChunkDb db, ITableIndex tableIndex, IHasher hasher, IReadIndex readIndex, long? maxChunkDataSize = null) { Ensure.NotNull(db, "db"); Ensure.NotNull(tableIndex, "tableIndex"); Ensure.NotNull(hasher, "hasher"); Ensure.NotNull(readIndex, "readIndex"); _db = db; _tableIndex = tableIndex; _hasher = hasher; _readIndex = readIndex; _maxChunkDataSize = maxChunkDataSize ?? db.Config.ChunkSize; } public long Scavenge(bool alwaysKeepScavenged, bool mergeChunks) { var totalSw = Stopwatch.StartNew(); var sw = Stopwatch.StartNew(); long spaceSaved = 0; Log.Trace("SCAVENGING: started scavenging of DB. Chunks count at start: {0}. Options: alwaysKeepScavenged = {1}, mergeChunks = {2}", _db.Manager.ChunksCount, alwaysKeepScavenged, mergeChunks); for (long scavengePos = 0; scavengePos < _db.Config.ChaserCheckpoint.Read(); ) { var chunk = _db.Manager.GetChunkFor(scavengePos); if (!chunk.IsReadOnly) { Log.Trace("SCAVENGING: stopping scavenging pass due to non-completed TFChunk for position {0}.", scavengePos); break; } long saved; ScavengeChunks(alwaysKeepScavenged, new[] {chunk}, out saved); spaceSaved += saved; scavengePos = chunk.ChunkHeader.ChunkEndPosition; } Log.Trace("SCAVENGING: initial pass completed in {0}.", sw.Elapsed); if (mergeChunks) { bool mergedSomething; int passNum = 0; do { mergedSomething = false; passNum += 1; sw.Restart(); var chunks = new List<TFChunk.TFChunk>(); long totalDataSize = 0; for (long scavengePos = 0; scavengePos < _db.Config.ChaserCheckpoint.Read();) { var chunk = _db.Manager.GetChunkFor(scavengePos); if (!chunk.IsReadOnly) { Log.Trace("SCAVENGING: stopping scavenging pass due to non-completed TFChunk for position {0}.", scavengePos); break; } if (totalDataSize + chunk.PhysicalDataSize > _maxChunkDataSize) { if (chunks.Count == 0) throw new Exception("SCAVENGING: no chunks to merge, unexpectedly..."); long saved; if (chunks.Count > 1 && ScavengeChunks(alwaysKeepScavenged, chunks, out saved)) { spaceSaved += saved; mergedSomething = true; } chunks.Clear(); totalDataSize = 0; } chunks.Add(chunk); totalDataSize += chunk.PhysicalDataSize; scavengePos = chunk.ChunkHeader.ChunkEndPosition; } if (chunks.Count > 1) { long saved; if (ScavengeChunks(alwaysKeepScavenged, chunks, out saved)) { spaceSaved += saved; mergedSomething = true; } } Log.Trace("SCAVENGING: merge pass #{0} completed in {1}. {2} merged.", passNum, sw.Elapsed, mergedSomething ? "Some chunks" : "Nothing"); } while (mergedSomething); } Log.Trace("SCAVENGING: total time taken: {0}, total space saved: {1}.", totalSw.Elapsed, spaceSaved); return spaceSaved; } private bool ScavengeChunks(bool alwaysKeepScavenged, IList<TFChunk.TFChunk> oldChunks, out long spaceSaved) { spaceSaved = 0; if (oldChunks.IsEmpty()) throw new ArgumentException("Provided list of chunks to scavenge and merge is empty."); var sw = Stopwatch.StartNew(); int chunkStartNumber = oldChunks.First().ChunkHeader.ChunkStartNumber; long chunkStartPos = oldChunks.First().ChunkHeader.ChunkStartPosition; int chunkEndNumber = oldChunks.Last().ChunkHeader.ChunkEndNumber; long chunkEndPos = oldChunks.Last().ChunkHeader.ChunkEndPosition; var tmpChunkPath = Path.Combine(_db.Config.Path, Guid.NewGuid() + ".scavenge.tmp"); var oldChunksList = string.Join("\n", oldChunks); Log.Trace("SCAVENGING: started to scavenge & merge chunks: {0}\nResulting temp chunk file: {1}.", oldChunksList, Path.GetFileName(tmpChunkPath)); TFChunk.TFChunk newChunk; try { newChunk = TFChunk.TFChunk.CreateNew(tmpChunkPath, _db.Config.ChunkSize, chunkStartNumber, chunkEndNumber, isScavenged: true, inMem: _db.Config.InMemDb); } catch (IOException exc) { Log.ErrorException(exc, "IOException during creating new chunk for scavenging purposes. Stopping scavenging process..."); return false; } try { var commits = new Dictionary<long, CommitInfo>(); foreach (var oldChunk in oldChunks) { TraverseChunk(oldChunk, prepare => { /* NOOP */ }, commit => { if (commit.TransactionPosition >= chunkStartPos) commits.Add(commit.TransactionPosition, new CommitInfo(commit)); }, system => { /* NOOP */ }); } var positionMapping = new List<PosMap>(); foreach (var oldChunk in oldChunks) { TraverseChunk(oldChunk, prepare => { if (ShouldKeepPrepare(prepare, commits, chunkStartPos, chunkEndPos)) positionMapping.Add(WriteRecord(newChunk, prepare)); }, commit => { if (ShouldKeepCommit(commit, commits)) positionMapping.Add(WriteRecord(newChunk, commit)); }, // we always keep system log records for now system => positionMapping.Add(WriteRecord(newChunk, system))); } newChunk.CompleteScavenge(positionMapping); var oldSize = oldChunks.Sum(x => (long)x.PhysicalDataSize + x.ChunkFooter.MapSize + ChunkHeader.Size + ChunkFooter.Size); var newSize = (long)newChunk.PhysicalDataSize + PosMap.FullSize * positionMapping.Count + ChunkHeader.Size + ChunkFooter.Size; if (oldSize <= newSize && !alwaysKeepScavenged) { Log.Trace("Scavenging of chunks:\n{0}\n" + "completed in {1}.\n" + "Old chunks' versions are kept as they are smaller.\n" + "Old chunk total size: {2}, scavenged chunk size: {3}.\n" + "Scavenged chunk removed.", oldChunksList, sw.Elapsed, oldSize, newSize); newChunk.MarkForDeletion(); return false; } var chunk = _db.Manager.SwitchChunk(newChunk, verifyHash: false, removeChunksWithGreaterNumbers: false); if (chunk != null) { Log.Trace("Scavenging of chunks:\n{0}\n" + "completed in {1}.\n" + "New chunk: {2} --> #{3}-{4} ({5}).\n" + "Old chunks total size: {6}, scavenged chunk size: {7}.", oldChunksList, sw.Elapsed, Path.GetFileName(tmpChunkPath), chunkStartNumber, chunkEndNumber, Path.GetFileName(chunk.FileName), oldSize, newSize); spaceSaved = oldSize - newSize; return true; } else { Log.Trace("Scavenging of chunks:\n{0}\n" + "completed in {1}.\n" + "But switching was prevented for new chunk: #{2}-{3} ({4}).\n" + "Old chunks total size: {5}, scavenged chunk size: {6}.", oldChunksList, sw.Elapsed, chunkStartNumber, chunkEndNumber, Path.GetFileName(tmpChunkPath), oldSize, newSize); return false; } } catch (FileBeingDeletedException exc) { Log.Info("Got FileBeingDeletedException exception during scavenging, that probably means some chunks were re-replicated.\n" + "Scavenging of following chunks will be skipped:\n{0}\n" + "Stopping scavenging and removing temp chunk '{1}'...\n" + "Exception message: {2}.", oldChunksList, tmpChunkPath, exc.Message); Helper.EatException(() => { File.SetAttributes(tmpChunkPath, FileAttributes.Normal); File.Delete(tmpChunkPath); }); return false; } } private bool ShouldKeepPrepare(PrepareLogRecord prepare, Dictionary<long, CommitInfo> commits, long chunkStart, long chunkEnd) { CommitInfo commitInfo; bool isCommitted = commits.TryGetValue(prepare.TransactionPosition, out commitInfo) || prepare.Flags.HasAnyOf(PrepareFlags.IsCommitted); if (prepare.Flags.HasAnyOf(PrepareFlags.StreamDelete)) { // We should always keep delete tombstone. commitInfo.ForciblyKeep(); return true; } if (!isCommitted && prepare.Flags.HasAnyOf(PrepareFlags.TransactionBegin)) { // So here we have prepare which commit is in the following chunks or prepare is not committed at all. // Now, whatever heuristic on prepare scavenge we use, we should never delete the very first prepare // in transaction, as in some circumstances we need it. // For instance, this prepare could be part of ongoing transaction and though we sometimes can determine // that prepare wouldn't ever be needed (e.g., stream was deleted, $maxAge or $maxCount rule it out) // we still need the first prepare to find out StreamId for possible commit in StorageWriterService.WriteCommit method. // There could be other reasons where it is needed, so we just safely filter it out to not bother further. return true; } var lastEventNumber = _readIndex.GetStreamLastEventNumber(prepare.EventStreamId); if (lastEventNumber == EventNumber.DeletedStream) { // When all prepares and commit of transaction belong to single chunk and the stream is deleted, // we can safely delete both prepares and commit. // Even if this prepare is not committed, but its stream is deleted, then as long as it is // not TransactionBegin prepare we can remove it, because any transaction should fail either way on commit stage. commitInfo.TryNotToKeep(); return false; } if (!isCommitted) { // If we could somehow figure out (from read index) the event number of this prepare // (if it is actually committed, but commit is in another chunk) then we can apply same scavenging logic. // Unfortunately, if it is not committed prepare we can say nothing for now, so should conservatively keep it. return true; } if (prepare.Flags.HasNoneOf(PrepareFlags.Data)) { // We encountered system prepare with no data. As of now it can appear only in explicit // transactions so we can safely remove it. The performance shouldn't hurt, because // TransactionBegin prepare is never needed either way and TransactionEnd should be in most // circumstances close to commit, so shouldn't hurt performance too much. // The advantage of getting rid of system prepares is ability to completely eliminate transaction // prepares and commit, if transaction events are completely ruled out by $maxAge/$maxCount. // Otherwise we'd have to either keep prepare not requiring to keep commit, which could leave // this prepare as never discoverable garbage, or we could insist on keeping commit forever // even if all events in transaction are scavenged. commitInfo.TryNotToKeep(); return false; } if (IsSoftDeletedTempStreamWithinSameChunk(prepare.EventStreamId, chunkStart, chunkEnd)) { commitInfo.TryNotToKeep(); return false; } var eventNumber = prepare.Flags.HasAnyOf(PrepareFlags.IsCommitted) ? prepare.ExpectedVersion + 1 // IsCommitted prepares always have explicit expected version : commitInfo.EventNumber + prepare.TransactionOffset; // We should always physically keep the very last prepare in the stream. // Otherwise we get into trouble when trying to resolve LastStreamEventNumber, for instance. // That is because our TableIndex doesn't keep EventStreamId, only hash of it, so on doing some operations // that needs TableIndex, we have to make sure we have prepare records in TFChunks when we need them. if (eventNumber >= lastEventNumber) { // Definitely keep commit, otherwise current prepare wouldn't be discoverable. commitInfo.ForciblyKeep(); return true; } var meta = _readIndex.GetStreamMetadata(prepare.EventStreamId); bool canRemove = (meta.MaxCount.HasValue && eventNumber < lastEventNumber - meta.MaxCount.Value + 1) || (meta.TruncateBefore.HasValue && eventNumber < meta.TruncateBefore.Value) || (meta.MaxAge.HasValue && prepare.TimeStamp < DateTime.UtcNow - meta.MaxAge.Value); if (canRemove) commitInfo.TryNotToKeep(); else commitInfo.ForciblyKeep(); return !canRemove; } private bool IsSoftDeletedTempStreamWithinSameChunk(string eventStreamId, long chunkStart, long chunkEnd) { uint sh; uint msh; if (SystemStreams.IsMetastream(eventStreamId)) { var originalStreamId = SystemStreams.OriginalStreamOf(eventStreamId); var meta = _readIndex.GetStreamMetadata(originalStreamId); if (meta.TruncateBefore != EventNumber.DeletedStream || meta.TempStream != true) return false; sh = _hasher.Hash(originalStreamId); msh = _hasher.Hash(eventStreamId); } else { var meta = _readIndex.GetStreamMetadata(eventStreamId); if (meta.TruncateBefore != EventNumber.DeletedStream || meta.TempStream != true) return false; sh = _hasher.Hash(eventStreamId); msh = _hasher.Hash(SystemStreams.MetastreamOf(eventStreamId)); } IndexEntry e; var allInChunk = _tableIndex.TryGetOldestEntry(sh, out e) && e.Position >= chunkStart && e.Position < chunkEnd && _tableIndex.TryGetLatestEntry(sh, out e) && e.Position >= chunkStart && e.Position < chunkEnd && _tableIndex.TryGetOldestEntry(msh, out e) && e.Position >= chunkStart && e.Position < chunkEnd && _tableIndex.TryGetLatestEntry(msh, out e) && e.Position >= chunkStart && e.Position < chunkEnd; return allInChunk; } private bool ShouldKeepCommit(CommitLogRecord commit, Dictionary<long, CommitInfo> commits) { CommitInfo commitInfo; if (commits.TryGetValue(commit.TransactionPosition, out commitInfo)) return commitInfo.KeepCommit != false; return true; } private void TraverseChunk(TFChunk.TFChunk chunk, Action<PrepareLogRecord> processPrepare, Action<CommitLogRecord> processCommit, Action<SystemLogRecord> processSystem) { var result = chunk.TryReadFirst(); while (result.Success) { var record = result.LogRecord; switch (record.RecordType) { case LogRecordType.Prepare: { var prepare = (PrepareLogRecord)record; processPrepare(prepare); break; } case LogRecordType.Commit: { var commit = (CommitLogRecord)record; processCommit(commit); break; } case LogRecordType.System: { var system = (SystemLogRecord)record; processSystem(system); break; } default: throw new ArgumentOutOfRangeException(); } result = chunk.TryReadClosestForward((int)result.NextPosition); } } private static PosMap WriteRecord(TFChunk.TFChunk newChunk, LogRecord record) { var writeResult = newChunk.TryAppend(record); if (!writeResult.Success) { throw new Exception(string.Format( "Unable to append record during scavenging. Scavenge position: {0}, Record: {1}.", writeResult.OldPosition, record)); } long logPos = newChunk.ChunkHeader.GetLocalLogPosition(record.LogPosition); int actualPos = (int) writeResult.OldPosition; return new PosMap(logPos, actualPos); } internal class CommitInfo { public readonly int EventNumber; //public string StreamId; public bool? KeepCommit; public CommitInfo(CommitLogRecord commitRecord) { EventNumber = commitRecord.FirstEventNumber; } public override string ToString() { return string.Format("EventNumber: {0}, KeepCommit: {1}", EventNumber, KeepCommit); } } } internal static class CommitInfoExtensions { public static void ForciblyKeep(this TFChunkScavenger.CommitInfo commitInfo) { if (commitInfo != null) commitInfo.KeepCommit = true; } public static void TryNotToKeep(this TFChunkScavenger.CommitInfo commitInfo) { // If someone decided definitely to keep corresponding commit then we shouldn't interfere. // Otherwise we should point that yes, you can remove commit for this prepare. if (commitInfo != null) commitInfo.KeepCommit = commitInfo.KeepCommit ?? false; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Streams; namespace Orleans { /// <summary> /// Client runtime for connecting to Orleans system /// </summary> /// TODO: Make this class non-static and inject it where it is needed. public static class GrainClient { /// <summary> /// Whether the client runtime has already been initialized /// </summary> /// <returns><c>true</c> if client runtime is already initialized</returns> public static bool IsInitialized { get { return isFullyInitialized && RuntimeClient.Current != null; } } internal static ClientConfiguration CurrentConfig { get; private set; } internal static bool TestOnlyNoConnect { get; set; } private static bool isFullyInitialized = false; private static OutsideRuntimeClient outsideRuntimeClient; private static readonly object initLock = new Object(); // RuntimeClient.Current is set to something different than OutsideRuntimeClient - it can only be set to InsideRuntimeClient, since we only have 2. // That means we are running in side a silo. private static bool IsRunningInsideSilo { get { return RuntimeClient.Current != null && !(RuntimeClient.Current is OutsideRuntimeClient); } } //TODO: prevent client code from using this from inside a Grain or provider public static IGrainFactory GrainFactory { get { return GetGrainFactory(); } } private static IGrainFactory GetGrainFactory() { if (IsRunningInsideSilo) { // just in case, make sure we don't get NullRefExc when checking RuntimeContext. bool runningInsideGrain = RuntimeContext.Current != null && RuntimeContext.CurrentActivationContext != null && RuntimeContext.CurrentActivationContext.ContextType == SchedulingContextType.Activation; if (runningInsideGrain) { throw new OrleansException("You are running inside a grain. GrainClient.GrainFactory should only be used on the client side. " + "Inside a grain use GrainFactory property of the Grain base class (use this.GrainFactory)."); } else // running inside provider or else where { throw new OrleansException("You are running inside the provider code, on the silo. GrainClient.GrainFactory should only be used on the client side. " + "Inside the provider code use GrainFactory that is passed via IProviderRuntime (use providerRuntime.GrainFactory)."); } } if (!IsInitialized) { throw new OrleansException("You must initialize the Grain Client before accessing the GrainFactory"); } return outsideRuntimeClient.InternalGrainFactory; } internal static IInternalGrainFactory InternalGrainFactory { get { if (!IsInitialized) { throw new OrleansException("You must initialize the Grain Client before accessing the InternalGrainFactory"); } return outsideRuntimeClient.InternalGrainFactory; } } internal static IServiceProvider ServiceProvider { get { CheckInitialized(); return outsideRuntimeClient.ServiceProvider; } } /// <summary> /// Initializes the client runtime from the standard client configuration file. /// </summary> public static void Initialize() { ClientConfiguration config = ClientConfiguration.StandardLoad(); if (config == null) { Console.WriteLine("Error loading standard client configuration file."); throw new ArgumentException("Error loading standard client configuration file"); } InternalInitialize(config); } /// <summary> /// Initializes the client runtime from the provided client configuration file. /// If an error occurs reading the specified configuration file, the initialization fails. /// </summary> /// <param name="configFilePath">A relative or absolute pathname for the client configuration file.</param> public static void Initialize(string configFilePath) { Initialize(new FileInfo(configFilePath)); } /// <summary> /// Initializes the client runtime from the provided client configuration file. /// If an error occurs reading the specified configuration file, the initialization fails. /// </summary> /// <param name="configFile">The client configuration file.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static void Initialize(FileInfo configFile) { ClientConfiguration config; try { config = ClientConfiguration.LoadFromFile(configFile.FullName); } catch (Exception ex) { Console.WriteLine("Error loading client configuration file {0}: {1}", configFile.FullName, ex); throw; } if (config == null) { Console.WriteLine("Error loading client configuration file {0}:", configFile.FullName); throw new ArgumentException(String.Format("Error loading client configuration file {0}:", configFile.FullName), "configFile"); } InternalInitialize(config); } /// <summary> /// Initializes the client runtime from the provided client configuration object. /// If the configuration object is null, the initialization fails. /// </summary> /// <param name="config">A ClientConfiguration object.</param> public static void Initialize(ClientConfiguration config) { if (config == null) { Console.WriteLine("Initialize was called with null ClientConfiguration object."); throw new ArgumentException("Initialize was called with null ClientConfiguration object.", "config"); } InternalInitialize(config); } /// <summary> /// Initializes the client runtime from the standard client configuration file using the provided gateway address. /// Any gateway addresses specified in the config file will be ignored and the provided gateway address wil be used instead. /// </summary> /// <param name="gatewayAddress">IP address and port of the gateway silo</param> /// <param name="overrideConfig">Whether the specified gateway endpoint should override / replace the values from config file, or be additive</param> public static void Initialize(IPEndPoint gatewayAddress, bool overrideConfig = true) { var config = ClientConfiguration.StandardLoad(); if (config == null) { Console.WriteLine("Error loading standard client configuration file."); throw new ArgumentException("Error loading standard client configuration file"); } if (overrideConfig) { config.Gateways = new List<IPEndPoint>(new[] { gatewayAddress }); } else if (!config.Gateways.Contains(gatewayAddress)) { config.Gateways.Add(gatewayAddress); } config.PreferedGatewayIndex = config.Gateways.IndexOf(gatewayAddress); InternalInitialize(config); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static void InternalInitialize(ClientConfiguration config) { // We deliberately want to run this initialization code on .NET thread pool thread to escape any // TPL execution environment and avoid any conflicts with client's synchronization context var tcs = new TaskCompletionSource<ClientConfiguration>(); WaitCallback doInit = state => { try { if (TestOnlyNoConnect) { Trace.TraceInformation("TestOnlyNoConnect - Returning before connecting to cluster."); } else { // Finish initializing this client connection to the Orleans cluster DoInternalInitialize(config); } tcs.SetResult(config); // Resolve promise } catch (Exception exc) { tcs.SetException(exc); // Break promise } }; // Queue Init call to thread pool thread ThreadPool.QueueUserWorkItem(doInit, null); try { CurrentConfig = tcs.Task.Result; // Wait for Init to finish } catch (AggregateException ae) { // Flatten the aggregate exception, which can be deeply nested. ae = ae.Flatten(); // If there is just one exception in the aggregate exception, throw that, otherwise throw the entire // flattened aggregate exception. var innerExceptions = ae.InnerExceptions; var exceptionToThrow = innerExceptions.Count == 1 ? innerExceptions[0] : ae; ExceptionDispatchInfo.Capture(exceptionToThrow).Throw(); } } /// <summary> /// Initializes client runtime from client configuration object. /// </summary> private static void DoInternalInitialize(ClientConfiguration config) { if (IsInitialized) return; lock (initLock) { if (!IsInitialized) { try { // this is probably overkill, but this ensures isFullyInitialized false // before we make a call that makes RuntimeClient.Current not null isFullyInitialized = false; outsideRuntimeClient = new OutsideRuntimeClient(config); // Keep reference, to avoid GC problems outsideRuntimeClient.Start(); // this needs to be the last successful step inside the lock so // IsInitialized doesn't return true until we're fully initialized isFullyInitialized = true; } catch (Exception exc) { // just make sure to fully Uninitialize what we managed to partially initialize, so we don't end up in inconsistent state and can later on re-initialize. Console.WriteLine("Initialization failed. {0}", exc); InternalUninitialize(); throw; } } } } /// <summary> /// Uninitializes client runtime. /// </summary> public static void Uninitialize() { lock (initLock) { InternalUninitialize(); } } /// <summary> /// Test hook to uninitialize client without cleanup /// </summary> public static void HardKill() { lock (initLock) { InternalUninitialize(false); } } /// <summary> /// This is the lock free version of uninitilize so we can share /// it between the public method and error paths inside initialize. /// This should only be called inside a lock(initLock) block. /// </summary> private static void InternalUninitialize(bool cleanup = true) { // Update this first so IsInitialized immediately begins returning // false. Since this method should be protected externally by // a lock(initLock) we should be able to reset everything else // before the next init attempt. isFullyInitialized = false; if (RuntimeClient.Current != null) { try { RuntimeClient.Current.Reset(cleanup); } catch (Exception) { } RuntimeClient.Current = null; } outsideRuntimeClient = null; ClientInvokeCallback = null; } /// <summary> /// Check that the runtime is intialized correctly, and throw InvalidOperationException if not /// </summary> /// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception> private static void CheckInitialized() { if (!IsInitialized) throw new InvalidOperationException("Runtime is not initialized. Call Client.Initialize method to initialize the runtime."); } /// <summary> /// Provides logging facility for applications. /// </summary> /// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception> public static Logger Logger { get { CheckInitialized(); return RuntimeClient.Current.AppLogger; } } /// <summary> /// Set a timeout for responses on this Orleans client. /// </summary> /// <param name="timeout"></param> /// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception> public static void SetResponseTimeout(TimeSpan timeout) { CheckInitialized(); RuntimeClient.Current.SetResponseTimeout(timeout); } /// <summary> /// Get a timeout of responses on this Orleans client. /// </summary> /// <returns>The response timeout.</returns> /// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception> public static TimeSpan GetResponseTimeout() { CheckInitialized(); return RuntimeClient.Current.GetResponseTimeout(); } /// <summary> /// Global pre-call interceptor function /// Synchronous callback made just before a message is about to be constructed and sent by a client to a grain. /// This call will be made from the same thread that constructs the message to be sent, so any thread-local settings /// such as <c>Orleans.RequestContext</c> will be picked up. /// The action receives an <see cref="InvokeMethodRequest"/> with details of the method to be invoked, including InterfaceId and MethodId, /// and a <see cref="IGrain"/> which is the GrainReference this request is being sent through /// </summary> /// <remarks>This callback method should return promptly and do a minimum of work, to avoid blocking calling thread or impacting throughput.</remarks> public static Action<InvokeMethodRequest, IGrain> ClientInvokeCallback { get; set; } public static IEnumerable<Streams.IStreamProvider> GetStreamProviders() { return RuntimeClient.Current.CurrentStreamProviderManager.GetStreamProviders(); } internal static IStreamProviderRuntime CurrentStreamProviderRuntime { get { return RuntimeClient.Current.CurrentStreamProviderRuntime; } } public static Streams.IStreamProvider GetStreamProvider(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); return RuntimeClient.Current.CurrentStreamProviderManager.GetProvider(name) as Streams.IStreamProvider; } public delegate void ConnectionToClusterLostHandler(object sender, EventArgs e); public static event ConnectionToClusterLostHandler ClusterConnectionLost; internal static void NotifyClusterConnectionLost() { try { // TODO: first argument should be 'this' when this class will no longer be static ClusterConnectionLost?.Invoke(null, EventArgs.Empty); } catch (Exception ex) { Logger.Error(ErrorCode.ClientError, "Error when sending cluster disconnection notification", ex); } } internal static IList<Uri> Gateways { get { CheckInitialized(); return outsideRuntimeClient.Gateways; } } } }
/* * TypeConverter.cs - Implementation of the * "System.ComponentModel.ComponentModel.TypeConverter" class. * * Copyright (C) 2002, 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.ComponentModel { #if CONFIG_COMPONENT_MODEL using System; using System.Collections; using System.Globalization; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; [ComVisible(true)] public class TypeConverter { // Constructor. public TypeConverter() { // Nothing to do here. } // Determine if we can convert from a specific type to this one. public bool CanConvertFrom(Type sourceType) { return CanConvertFrom(null, sourceType); } public virtual bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType) { #if CONFIG_COMPONENT_MODEL_DESIGN // By default, we can always convert instance descriptors. return (sourceType == typeof(InstanceDescriptor)); #else return false; #endif } // Determine if we can convert from this type to a specific type. public bool CanConvertTo(Type destinationType) { return CanConvertTo(null, destinationType); } public virtual bool CanConvertTo (ITypeDescriptorContext context, Type destinationType) { // By default, we can always convert to the string type. return (destinationType == typeof(String)); } // Convert from another type to the one represented by this class. public Object ConvertFrom(Object value) { return ConvertFrom(null, CultureInfo.CurrentCulture, value); } public virtual Object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) { #if CONFIG_COMPONENT_MODEL_DESIGN if(value is InstanceDescriptor) { return ((InstanceDescriptor)value).Invoke(); } #endif throw GetConvertFromException(value); } // Convert a string into this type using the invariant culture. public Object ConvertFromInvariantString(String text) { return ConvertFromString (null, CultureInfo.InvariantCulture, text); } public Object ConvertFromInvariantString (ITypeDescriptorContext context, String text) { return ConvertFromString (context, CultureInfo.InvariantCulture, text); } // Convert a string into this type. public Object ConvertFromString(String text) { return ConvertFrom(null, CultureInfo.CurrentCulture, text); } public Object ConvertFromString (ITypeDescriptorContext context, String text) { return ConvertFrom(context, CultureInfo.CurrentCulture, text); } public Object ConvertFromString (ITypeDescriptorContext context, CultureInfo culture, String text) { return ConvertFrom(context, culture, text); } // Convert this object into another type. public Object ConvertTo(Object value, Type destinationType) { return ConvertTo(null, null, value, destinationType); } public virtual Object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType) { if(destinationType == null) { throw new ArgumentNullException("destinationType"); } if(destinationType == typeof(String)) { if(value != null) { return value.ToString(); } else { return String.Empty; } } else { throw GetConvertToException(value, destinationType); } } // Convert an object to a culture-invariant string. public String ConvertToInvariantString(Object value) { return ConvertToString (null, CultureInfo.InvariantCulture, value); } public String ConvertToInvariantString (ITypeDescriptorContext context, Object value) { return ConvertToString (context, CultureInfo.InvariantCulture, value); } // Convert an object into a string. public String ConvertToString(Object value) { return (String)ConvertTo(null, CultureInfo.CurrentCulture, value, typeof(String)); } public String ConvertToString (ITypeDescriptorContext context, Object value) { return (String)ConvertTo(context, CultureInfo.CurrentCulture, value, typeof(String)); } public String ConvertToString (ITypeDescriptorContext context, CultureInfo culture, Object value) { return (String)ConvertTo(context, culture, value, typeof(String)); } // Create an instance of this type of object. public Object CreateInstance(IDictionary propertyValues) { return CreateInstance(null, propertyValues); } public virtual Object CreateInstance (ITypeDescriptorContext context, IDictionary propertyValues) { return null; } // Determine if creating new instances is supported. public bool GetCreateInstanceSupported() { return GetCreateInstanceSupported(null); } public virtual bool GetCreateInstanceSupported (ITypeDescriptorContext context) { return false; } // Get the properties for an object. public PropertyDescriptorCollection GetProperties(Object value) { return GetProperties(null, value, null); } public PropertyDescriptorCollection GetProperties (ITypeDescriptorContext context, Object value) { return GetProperties(context, value, null); } public virtual PropertyDescriptorCollection GetProperties (ITypeDescriptorContext context, Object value, Attribute[] attributes) { return null; } // Determine if the "GetProperties" method is supported. public bool GetPropertiesSupported() { return GetPropertiesSupported(null); } public virtual bool GetPropertiesSupported (ITypeDescriptorContext context) { return false; } // Return a collection of standard values for this data type. public ICollection GetStandardValues() { return GetStandardValues(null); } public virtual StandardValuesCollection GetStandardValues (ITypeDescriptorContext context) { return null; } // Determine if the list of standard values is an exclusive list. public bool GetStandardValuesExclusive() { return GetStandardValuesExclusive(null); } public virtual bool GetStandardValuesExclusive (ITypeDescriptorContext context) { return false; } // Determine if "GetStandardValues" is supported. public bool GetStandardValuesSupported() { return GetStandardValuesSupported(null); } public virtual bool GetStandardValuesSupported (ITypeDescriptorContext context) { return false; } // Determine if an object is valid for this type. public bool IsValid(Object value) { return IsValid(null, value); } public virtual bool IsValid(ITypeDescriptorContext context, Object value) { return true; } // Get the exception to use when "ConvertFrom" cannot be performed. protected Exception GetConvertFromException(Object value) { return new NotSupportedException(S._("NotSupp_Conversion")); } // Get the exception to use when "ConvertTo" cannot be performed. protected Exception GetConvertToException (Object value, Type destinationType) { return new NotSupportedException(S._("NotSupp_Conversion")); } // Sort a collection of properties. protected PropertyDescriptorCollection SortProperties (PropertyDescriptorCollection props, String[] names) { props.Sort(names); return props; } // Wrap a collection to make it indexable. public class StandardValuesCollection : ICollection, IEnumerable { // Internal state. private ICollection values; // Constructor. public StandardValuesCollection(ICollection values) { if(values != null) { this.values = values; } else { this.values = new Object[0]; } } // Get the number of elements in this collection. public int Count { get { return values.Count; } } // Copy the elements of this collection into an array. public void CopyTo(Array array, int index) { values.CopyTo(array, index); } // Get an enumerator for this collection. public IEnumerator GetEnumerator() { return values.GetEnumerator(); } // Implement the ICollection interface. void ICollection.CopyTo(Array array, int index) { values.CopyTo(array, index); } int ICollection.Count { get { return values.Count; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return null; } } // Implement the IEnumerable interface. IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } // Get an item from this collection. public Object this[int index] { get { if(values is IList) { return ((IList)values)[index]; } else { if(index < 0 || index >= values.Count) { throw new IndexOutOfRangeException (S._("Arg_InvalidArrayIndex")); } IEnumerator e = values.GetEnumerator(); while(e.MoveNext()) { if(index == 0) { return e.Current; } --index; } throw new IndexOutOfRangeException (S._("Arg_InvalidArrayIndex")); } } } }; // class StandardValuesCollection // Simple property descriptor for objects that don't have properties. protected abstract class SimplePropertyDescriptor : PropertyDescriptor { // Internal state. private Type componentType; private Type propertyType; // Constructors. public SimplePropertyDescriptor (Type componentType, String name, Type propertyType) : base(name, null) { this.componentType = componentType; this.propertyType = propertyType; } public SimplePropertyDescriptor (Type componentType, String name, Type propertyType, Attribute[] attributes) : base(name, attributes) { this.componentType = componentType; this.propertyType = propertyType; } // Get the component type that owns this property. public override Type ComponentType { get { return componentType; } } // Determine if this property is read-only. public override bool IsReadOnly { get { ReadOnlyAttribute attr; attr = (ReadOnlyAttribute) (Attributes[typeof(ReadOnlyAttribute)]); if(attr != null) { return attr.IsReadOnly; } else { return false; } } } // Get the type of this property. public override Type PropertyType { get { return propertyType; } } // Determine if resetting a component's property will change its value. public override bool CanResetValue(Object component) { DefaultValueAttribute attr; attr = (DefaultValueAttribute) (Attributes[typeof(DefaultValueAttribute)]); if(attr != null) { // Strictly speaking, this should probably // check that the values are *not* equal, but // other implementations check for equality. // So we do that as well, for compatibility. Object value1 = GetValue(component); Object value2 = attr.Value; if(value1 == null) { return (value2 == null); } else { return value1.Equals(value2); } } else { return false; } } // Reset the property value associated with a component. public override void ResetValue(Object component) { DefaultValueAttribute attr; attr = (DefaultValueAttribute) (Attributes[typeof(DefaultValueAttribute)]); if(attr != null) { SetValue(component, attr.Value); } } // Determine if a property value needs to be serialized. public override bool ShouldSerializeValue(Object component) { return false; } }; // class SimplePropertyDescriptor }; // class TypeConverter #endif // CONFIG_COMPONENT_MODEL }; // namespace System.ComponentModel
using System; using Server; using Server.Engines.MLQuests; using Server.Mobiles; using Server.Gumps; using System.Collections.Generic; namespace Server.Engines.MLQuests.Objectives { public abstract class BaseObjective { public virtual bool IsTimed { get { return false; } } public virtual TimeSpan Duration { get { return TimeSpan.Zero; } } public BaseObjective() { } public virtual bool CanOffer( IQuestGiver quester, PlayerMobile pm, bool message ) { return true; } public abstract void WriteToGump( Gump g, ref int y ); public virtual BaseObjectiveInstance CreateInstance( MLQuestInstance instance ) { return null; } } public abstract class BaseObjectiveInstance { private MLQuestInstance m_Instance; private DateTime m_EndTime; private bool m_Expired; public MLQuestInstance Instance { get { return m_Instance; } } public bool IsTimed { get { return ( m_EndTime != DateTime.MinValue ); } } public DateTime EndTime { get { return m_EndTime; } set { m_EndTime = value; } } public bool Expired { get { return m_Expired; } set { m_Expired = value; } } public BaseObjectiveInstance( MLQuestInstance instance, BaseObjective obj ) { m_Instance = instance; if ( obj.IsTimed ) m_EndTime = DateTime.Now + obj.Duration; } public virtual void WriteToGump( Gump g, ref int y ) { if ( IsTimed ) WriteTimeRemaining( g, ref y, ( m_EndTime > DateTime.Now ) ? ( m_EndTime - DateTime.Now ) : TimeSpan.Zero ); } public static void WriteTimeRemaining( Gump g, ref int y, TimeSpan timeRemaining ) { g.AddHtmlLocalized( 103, y, 120, 16, 1062379, 0x15F90, false, false ); // Est. time remaining: g.AddLabel( 223, y, 0x481, timeRemaining.TotalSeconds.ToString( "F0" ) ); y += 16; } public virtual bool AllowsQuestItem( Item item, Type type ) { return false; } public virtual bool IsCompleted() { return false; } public virtual void CheckComplete() { if ( IsCompleted() ) { m_Instance.Player.PlaySound( 0x5B6 ); // public sound m_Instance.CheckComplete(); } } public virtual void OnQuestAccepted() { } public virtual void OnQuestCancelled() { } public virtual void OnQuestCompleted() { } public virtual bool OnBeforeClaimReward() { return true; } public virtual void OnClaimReward() { } public virtual void OnAfterClaimReward() { } public virtual void OnRewardClaimed() { } public virtual void OnQuesterDeleted() { } public virtual void OnPlayerDeath() { } public virtual void OnExpire() { } public enum DataType : byte { None, EscortObjective, KillObjective, DeliverObjective } public virtual DataType ExtraDataType { get { return DataType.None; } } public virtual void Serialize( GenericWriter writer ) { // Version info is written in MLQuestPersistence.Serialize if ( IsTimed ) { writer.Write( true ); writer.WriteDeltaTime( m_EndTime ); } else { writer.Write( false ); } // For type checks on deserialization // (This way quest objectives can be changed without breaking serialization) writer.Write( (byte)ExtraDataType ); } public static void Deserialize( GenericReader reader, int version, BaseObjectiveInstance objInstance ) { if ( reader.ReadBool() ) { DateTime endTime = reader.ReadDeltaTime(); if ( objInstance != null ) objInstance.EndTime = endTime; } DataType extraDataType = (DataType)reader.ReadByte(); switch ( extraDataType ) { case DataType.EscortObjective: { bool completed = reader.ReadBool(); if ( objInstance is EscortObjectiveInstance ) ( (EscortObjectiveInstance)objInstance ).HasCompleted = completed; break; } case DataType.KillObjective: { int slain = reader.ReadInt(); if ( objInstance is KillObjectiveInstance ) ( (KillObjectiveInstance)objInstance ).Slain = slain; break; } case DataType.DeliverObjective: { bool completed = reader.ReadBool(); if ( objInstance is DeliverObjectiveInstance ) ( (DeliverObjectiveInstance)objInstance ).HasCompleted = completed; break; } } } } }
// 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; using System.Diagnostics.Contracts; using System.Reflection; using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { internal sealed class CLRIReferenceImpl<T> : CLRIPropertyValueImpl, IReference<T>, ICustomPropertyProvider { private T _value; public CLRIReferenceImpl(PropertyType type, T obj) : base(type, obj) { BCLDebug.Assert(obj != null, "Must not be null"); _value = obj; } public T Value { get { return _value; } } public override string ToString() { if (_value != null) { return _value.ToString(); } else { return base.ToString(); } } [Pure] ICustomProperty ICustomPropertyProvider.GetCustomProperty(string name) { // _value should not be null return ICustomPropertyProviderImpl.CreateProperty((object)_value, name); } [Pure] ICustomProperty ICustomPropertyProvider.GetIndexedProperty(string name, Type indexParameterType) { // _value should not be null return ICustomPropertyProviderImpl.CreateIndexedProperty((object)_value, name, indexParameterType); } [Pure] string ICustomPropertyProvider.GetStringRepresentation() { // _value should not be null return ((object)_value).ToString(); } Type ICustomPropertyProvider.Type { [Pure] get { // _value should not be null return ((object)_value).GetType(); } } // We have T in an IReference<T>. Need to QI for IReference<T> with the appropriate GUID, call // the get_Value property, allocate an appropriately-sized managed object, marshal the native object // to the managed object, and free the native method. Also we want the return value boxed (aka normal value type boxing). // // This method is called by VM. Mark the method with FriendAccessAllowed attribute to ensure that the unreferenced method // optimization skips it and the code will be saved into NGen image. [System.Runtime.CompilerServices.FriendAccessAllowed] internal static Object UnboxHelper(Object wrapper) { Contract.Requires(wrapper != null); IReference<T> reference = (IReference<T>) wrapper; Contract.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed."); return reference.Value; } } // T can be any WinRT-compatible type internal sealed class CLRIReferenceArrayImpl<T> : CLRIPropertyValueImpl, IReferenceArray<T>, ICustomPropertyProvider, IList // Jupiter data binding needs IList/IEnumerable { private T[] _value; private IList _list; public CLRIReferenceArrayImpl(PropertyType type, T[] obj) : base(type, obj) { BCLDebug.Assert(obj != null, "Must not be null"); _value = obj; _list = (IList) _value; } public T[] Value { get { return _value; } } public override string ToString() { if (_value != null) { return _value.ToString(); } else { return base.ToString(); } } [Pure] ICustomProperty ICustomPropertyProvider.GetCustomProperty(string name) { // _value should not be null return ICustomPropertyProviderImpl.CreateProperty((object)_value, name); } [Pure] ICustomProperty ICustomPropertyProvider.GetIndexedProperty(string name, Type indexParameterType) { // _value should not be null return ICustomPropertyProviderImpl.CreateIndexedProperty((object)_value, name, indexParameterType); } [Pure] string ICustomPropertyProvider.GetStringRepresentation() { // _value should not be null return ((object)_value).ToString(); } Type ICustomPropertyProvider.Type { [Pure] get { // _value should not be null return ((object)_value).GetType(); } } // // IEnumerable methods. Used by data-binding in Jupiter when you try to data bind // against a managed array // IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_value).GetEnumerator(); } // // IList & ICollection methods. // This enables two-way data binding and index access in Jupiter // Object IList.this[int index] { get { return _list[index]; } set { _list[index] = value; } } int IList.Add(Object value) { return _list.Add(value); } bool IList.Contains(Object value) { return _list.Contains(value); } void IList.Clear() { _list.Clear(); } bool IList.IsReadOnly { get { return _list.IsReadOnly; } } bool IList.IsFixedSize { get { return _list.IsFixedSize; } } int IList.IndexOf(Object value) { return _list.IndexOf(value); } void IList.Insert(int index, Object value) { _list.Insert(index, value); } void IList.Remove(Object value) { _list.Remove(value); } void IList.RemoveAt(int index) { _list.RemoveAt(index); } void ICollection.CopyTo(Array array, int index) { _list.CopyTo(array, index); } int ICollection.Count { get { return _list.Count; } } Object ICollection.SyncRoot { get { return _list.SyncRoot; } } bool ICollection.IsSynchronized { get { return _list.IsSynchronized; } } // We have T in an IReferenceArray<T>. Need to QI for IReferenceArray<T> with the appropriate GUID, call // the get_Value property, allocate an appropriately-sized managed object, marshal the native object // to the managed object, and free the native method. // // This method is called by VM. Mark the method with FriendAccessAllowed attribute to ensure that the unreferenced method // optimization skips it and the code will be saved into NGen image. [System.Runtime.CompilerServices.FriendAccessAllowed] internal static Object UnboxHelper(Object wrapper) { Contract.Requires(wrapper != null); IReferenceArray<T> reference = (IReferenceArray<T>)wrapper; Contract.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed."); T[] marshaled = reference.Value; return marshaled; } } // For creating instances of Windows Runtime's IReference<T> and IReferenceArray<T>. internal static class IReferenceFactory { internal static readonly Type s_pointType = Type.GetType("Windows.Foundation.Point, " + AssemblyRef.SystemRuntimeWindowsRuntime); internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, " + AssemblyRef.SystemRuntimeWindowsRuntime); internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, " + AssemblyRef.SystemRuntimeWindowsRuntime); [SecuritySafeCritical] internal static Object CreateIReference(Object obj) { Contract.Requires(obj != null, "Null should not be boxed."); Contract.Ensures(Contract.Result<Object>() != null); Type type = obj.GetType(); if (type.IsArray) return CreateIReferenceArray((Array) obj); if (type == typeof(int)) return new CLRIReferenceImpl<int>(PropertyType.Int32, (int)obj); if (type == typeof(String)) return new CLRIReferenceImpl<String>(PropertyType.String, (String)obj); if (type == typeof(byte)) return new CLRIReferenceImpl<byte>(PropertyType.UInt8, (byte)obj); if (type == typeof(short)) return new CLRIReferenceImpl<short>(PropertyType.Int16, (short)obj); if (type == typeof(ushort)) return new CLRIReferenceImpl<ushort>(PropertyType.UInt16, (ushort)obj); if (type == typeof(uint)) return new CLRIReferenceImpl<uint>(PropertyType.UInt32, (uint)obj); if (type == typeof(long)) return new CLRIReferenceImpl<long>(PropertyType.Int64, (long)obj); if (type == typeof(ulong)) return new CLRIReferenceImpl<ulong>(PropertyType.UInt64, (ulong)obj); if (type == typeof(float)) return new CLRIReferenceImpl<float>(PropertyType.Single, (float)obj); if (type == typeof(double)) return new CLRIReferenceImpl<double>(PropertyType.Double, (double)obj); if (type == typeof(char)) return new CLRIReferenceImpl<char>(PropertyType.Char16, (char)obj); if (type == typeof(bool)) return new CLRIReferenceImpl<bool>(PropertyType.Boolean, (bool)obj); if (type == typeof(Guid)) return new CLRIReferenceImpl<Guid>(PropertyType.Guid, (Guid)obj); if (type == typeof(DateTimeOffset)) return new CLRIReferenceImpl<DateTimeOffset>(PropertyType.DateTime, (DateTimeOffset)obj); if (type == typeof(TimeSpan)) return new CLRIReferenceImpl<TimeSpan>(PropertyType.TimeSpan, (TimeSpan)obj); if (type == typeof(Object)) return new CLRIReferenceImpl<Object>(PropertyType.Inspectable, (Object)obj); if (type == typeof(RuntimeType)) { // If the type is System.RuntimeType, we want to use System.Type marshaler (it's parent of the type) return new CLRIReferenceImpl<Type>(PropertyType.Other, (Type)obj); } // Handle arbitrary WinRT-compatible value types, and recognize a few special types. PropertyType? propType = null; if (type == s_pointType) { propType = PropertyType.Point; } else if (type == s_rectType) { propType = PropertyType.Rect; } else if (type == s_sizeType) { propType = PropertyType.Size; } else if (type.IsValueType || obj is Delegate) { propType = PropertyType.Other; } if (propType.HasValue) { Type specificType = typeof(CLRIReferenceImpl<>).MakeGenericType(type); return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj }); } Contract.Assert(false, "We should not see non-WinRT type here"); return null; } [SecuritySafeCritical] internal static Object CreateIReferenceArray(Array obj) { Contract.Requires(obj != null); Contract.Requires(obj.GetType().IsArray); Contract.Ensures(Contract.Result<Object>() != null); Type type = obj.GetType().GetElementType(); Contract.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray); if (type == typeof(int)) return new CLRIReferenceArrayImpl<int>(PropertyType.Int32Array, (int[])obj); if (type == typeof(String)) return new CLRIReferenceArrayImpl<String>(PropertyType.StringArray, (String[])obj); if (type == typeof(byte)) return new CLRIReferenceArrayImpl<byte>(PropertyType.UInt8Array, (byte[])obj); if (type == typeof(short)) return new CLRIReferenceArrayImpl<short>(PropertyType.Int16Array, (short[])obj); if (type == typeof(ushort)) return new CLRIReferenceArrayImpl<ushort>(PropertyType.UInt16Array, (ushort[])obj); if (type == typeof(uint)) return new CLRIReferenceArrayImpl<uint>(PropertyType.UInt32Array, (uint[])obj); if (type == typeof(long)) return new CLRIReferenceArrayImpl<long>(PropertyType.Int64Array, (long[])obj); if (type == typeof(ulong)) return new CLRIReferenceArrayImpl<ulong>(PropertyType.UInt64Array, (ulong[])obj); if (type == typeof(float)) return new CLRIReferenceArrayImpl<float>(PropertyType.SingleArray, (float[])obj); if (type == typeof(double)) return new CLRIReferenceArrayImpl<double>(PropertyType.DoubleArray, (double[])obj); if (type == typeof(char)) return new CLRIReferenceArrayImpl<char>(PropertyType.Char16Array, (char[])obj); if (type == typeof(bool)) return new CLRIReferenceArrayImpl<bool>(PropertyType.BooleanArray, (bool[])obj); if (type == typeof(Guid)) return new CLRIReferenceArrayImpl<Guid>(PropertyType.GuidArray, (Guid[])obj); if (type == typeof(DateTimeOffset)) return new CLRIReferenceArrayImpl<DateTimeOffset>(PropertyType.DateTimeArray, (DateTimeOffset[])obj); if (type == typeof(TimeSpan)) return new CLRIReferenceArrayImpl<TimeSpan>(PropertyType.TimeSpanArray, (TimeSpan[])obj); if (type == typeof(Type)) { // Note: The array type will be System.Type, not System.RuntimeType return new CLRIReferenceArrayImpl<Type>(PropertyType.OtherArray, (Type[])obj); } PropertyType? propType = null; if (type == s_pointType) { propType = PropertyType.PointArray; } else if (type == s_rectType) { propType = PropertyType.RectArray; } else if (type == s_sizeType) { propType = PropertyType.SizeArray; } else if (type.IsValueType) { // note that KeyValuePair`2 is a reference type on the WinRT side so the array // must be wrapped with CLRIReferenceArrayImpl<Object> if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>)) { Object[] objArray = new Object[obj.Length]; for (int i = 0; i < objArray.Length; i++) { objArray[i] = obj.GetValue(i); } obj = objArray; } else { propType = PropertyType.OtherArray; } } else if (typeof(Delegate).IsAssignableFrom(type)) { propType = PropertyType.OtherArray; } if (propType.HasValue) { // All WinRT value type will be Property.Other Type specificType = typeof(CLRIReferenceArrayImpl<>).MakeGenericType(type); return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj }); } else { // All WinRT reference type (including arbitary managed type) will be PropertyType.ObjectArray return new CLRIReferenceArrayImpl<Object>(PropertyType.InspectableArray, (Object[])obj); } } } }
// 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.Reflection; using Microsoft.AspNetCore.Mvc.DataAnnotations; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.AspNetCore.Mvc.ModelBinding { public class TestModelMetadataProvider : DefaultModelMetadataProvider { private static DataAnnotationsMetadataProvider CreateDefaultDataAnnotationsProvider(IStringLocalizerFactory stringLocalizerFactory) { var localizationOptions = Options.Create(new MvcDataAnnotationsLocalizationOptions()); localizationOptions.Value.DataAnnotationLocalizerProvider = (modelType, localizerFactory) => localizerFactory.Create(modelType); return new DataAnnotationsMetadataProvider(new MvcOptions(), localizationOptions, stringLocalizerFactory); } // Creates a provider with all the defaults - includes data annotations public static ModelMetadataProvider CreateDefaultProvider(IStringLocalizerFactory stringLocalizerFactory = null) { var detailsProviders = new List<IMetadataDetailsProvider> { new DefaultBindingMetadataProvider(), new DefaultValidationMetadataProvider(), CreateDefaultDataAnnotationsProvider(stringLocalizerFactory), new DataMemberRequiredBindingMetadataProvider(), }; MvcCoreMvcOptionsSetup.ConfigureAdditionalModelMetadataDetailsProviders(detailsProviders); var validationProviders = TestModelValidatorProvider.CreateDefaultProvider(); detailsProviders.Add(new HasValidatorsValidationMetadataProvider(validationProviders.ValidatorProviders)); var compositeDetailsProvider = new DefaultCompositeMetadataDetailsProvider(detailsProviders); return new DefaultModelMetadataProvider(compositeDetailsProvider, Options.Create(new MvcOptions())); } public static IModelMetadataProvider CreateDefaultProvider(IList<IMetadataDetailsProvider> providers) { var detailsProviders = new List<IMetadataDetailsProvider>() { new DefaultBindingMetadataProvider(), new DefaultValidationMetadataProvider(), new DataAnnotationsMetadataProvider( new MvcOptions(), Options.Create(new MvcDataAnnotationsLocalizationOptions()), stringLocalizerFactory: null), new DataMemberRequiredBindingMetadataProvider(), }; MvcCoreMvcOptionsSetup.ConfigureAdditionalModelMetadataDetailsProviders(detailsProviders); detailsProviders.AddRange(providers); var validationProviders = TestModelValidatorProvider.CreateDefaultProvider(); detailsProviders.Add(new HasValidatorsValidationMetadataProvider(validationProviders.ValidatorProviders)); var compositeDetailsProvider = new DefaultCompositeMetadataDetailsProvider(detailsProviders); return new DefaultModelMetadataProvider(compositeDetailsProvider, Options.Create(new MvcOptions())); } public static IModelMetadataProvider CreateProvider(IList<IMetadataDetailsProvider> providers) { var detailsProviders = new List<IMetadataDetailsProvider>(); if (providers != null) { detailsProviders.AddRange(providers); } var compositeDetailsProvider = new DefaultCompositeMetadataDetailsProvider(detailsProviders); return new DefaultModelMetadataProvider(compositeDetailsProvider, Options.Create(new MvcOptions())); } private readonly TestModelMetadataDetailsProvider _detailsProvider; public TestModelMetadataProvider() : this(new TestModelMetadataDetailsProvider()) { } private TestModelMetadataProvider(TestModelMetadataDetailsProvider detailsProvider) : base( new DefaultCompositeMetadataDetailsProvider(new IMetadataDetailsProvider[] { new DefaultBindingMetadataProvider(), new DefaultValidationMetadataProvider(), new DataAnnotationsMetadataProvider( new MvcOptions(), Options.Create(new MvcDataAnnotationsLocalizationOptions()), stringLocalizerFactory: null), detailsProvider }), Options.Create(new MvcOptions())) { _detailsProvider = detailsProvider; } public IMetadataBuilder ForType(Type type) { var key = ModelMetadataIdentity.ForType(type); var builder = new MetadataBuilder(key); _detailsProvider.Builders.Add(builder); return builder; } public IMetadataBuilder ForType<TModel>() { return ForType(typeof(TModel)); } public IMetadataBuilder ForProperty(Type containerType, string propertyName) { var property = containerType.GetRuntimeProperty(propertyName); Assert.NotNull(property); var key = ModelMetadataIdentity.ForProperty(property, property.PropertyType, containerType); var builder = new MetadataBuilder(key); _detailsProvider.Builders.Add(builder); return builder; } public IMetadataBuilder ForParameter(ParameterInfo parameter) { var key = ModelMetadataIdentity.ForParameter(parameter); var builder = new MetadataBuilder(key); _detailsProvider.Builders.Add(builder); return builder; } public IMetadataBuilder ForProperty<TContainer>(string propertyName) { return ForProperty(typeof(TContainer), propertyName); } private class TestModelMetadataDetailsProvider : IBindingMetadataProvider, IDisplayMetadataProvider, IValidationMetadataProvider { public List<MetadataBuilder> Builders { get; } = new List<MetadataBuilder>(); public void CreateBindingMetadata(BindingMetadataProviderContext context) { foreach (var builder in Builders) { builder.Apply(context); } } public void CreateDisplayMetadata(DisplayMetadataProviderContext context) { foreach (var builder in Builders) { builder.Apply(context); } } public void CreateValidationMetadata(ValidationMetadataProviderContext context) { foreach (var builder in Builders) { builder.Apply(context); } } } public interface IMetadataBuilder { IMetadataBuilder BindingDetails(Action<BindingMetadata> action); IMetadataBuilder DisplayDetails(Action<DisplayMetadata> action); IMetadataBuilder ValidationDetails(Action<ValidationMetadata> action); } private class MetadataBuilder : IMetadataBuilder { private readonly List<Action<BindingMetadata>> _bindingActions = new List<Action<BindingMetadata>>(); private readonly List<Action<DisplayMetadata>> _displayActions = new List<Action<DisplayMetadata>>(); private readonly List<Action<ValidationMetadata>> _validationActions = new List<Action<ValidationMetadata>>(); private readonly ModelMetadataIdentity _key; public MetadataBuilder(ModelMetadataIdentity key) { _key = key; } public void Apply(BindingMetadataProviderContext context) { if (_key.Equals(context.Key)) { foreach (var action in _bindingActions) { action(context.BindingMetadata); } } } public void Apply(DisplayMetadataProviderContext context) { if (_key.Equals(context.Key)) { foreach (var action in _displayActions) { action(context.DisplayMetadata); } } } public void Apply(ValidationMetadataProviderContext context) { if (_key.Equals(context.Key)) { foreach (var action in _validationActions) { action(context.ValidationMetadata); } } } public IMetadataBuilder BindingDetails(Action<BindingMetadata> action) { _bindingActions.Add(action); return this; } public IMetadataBuilder DisplayDetails(Action<DisplayMetadata> action) { _displayActions.Add(action); return this; } public IMetadataBuilder ValidationDetails(Action<ValidationMetadata> action) { _validationActions.Add(action); return this; } } } }