context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using ModestTree; using ModestTree.Util; #if !ZEN_NOT_UNITY3D using UnityEngine; #endif namespace Zenject { // Responsibilities: // - Expose methods to configure object graph via Bind() methods // - Build object graphs via Resolve() method public class DiContainer : IInstantiator, IResolver, IBinder { readonly Dictionary<BindingId, List<ProviderBase>> _providers = new Dictionary<BindingId, List<ProviderBase>>(); readonly SingletonProviderMap _singletonMap; readonly HashSet<Type> _installedInstallers = new HashSet<Type>(); readonly Stack<Type> _installsInProgress = new Stack<Type>(); readonly DiContainer _parentContainer; readonly Stack<LookupId> _resolvesInProgress = new Stack<LookupId>(); #if !ZEN_NOT_UNITY3D readonly Transform _rootTransform; #endif bool _isValidating; public DiContainer() { _singletonMap = new SingletonProviderMap(this); this.Bind<DiContainer>().ToInstance(this); this.Bind<IInstantiator>().ToInstance(this); this.Bind<SingletonProviderMap>().ToInstance(_singletonMap); #if !ZEN_NOT_UNITY3D this.Bind<PrefabSingletonProviderMap>().ToSingle<PrefabSingletonProviderMap>(); #endif this.Bind<SingletonInstanceHelper>().ToSingle<SingletonInstanceHelper>(); } public DiContainer(DiContainer parentContainer) : this() { _parentContainer = parentContainer; } #if !ZEN_NOT_UNITY3D public DiContainer(Transform rootTransform, DiContainer parentContainer) : this() { _parentContainer = parentContainer; _rootTransform = rootTransform; } public DiContainer(Transform rootTransform) : this() { _rootTransform = rootTransform; } #endif public SingletonProviderMap SingletonProviderMap { get { return _singletonMap; } } public DiContainer ParentContainer { get { return _parentContainer; } } public bool ChecksForCircularDependencies { get { #if ZEN_MULTITHREADING // When multithreading is supported we can't use a static field to track the lookup // TODO: We could look at the inject context though return false; #else return true; #endif } } public IEnumerable<Type> InstalledInstallers { get { return _installedInstallers; } } #if !ZEN_NOT_UNITY3D public Transform RootTransform { get { return _rootTransform; } } #endif // True if this container was created for the purposes of validation // Useful to avoid instantiating things that we shouldn't during this step public bool IsValidating { get { return _isValidating; } set { _isValidating = value; } } public IEnumerable<BindingId> AllContracts { get { return _providers.Keys; } } // Note that this list is not exhaustive or even accurate so use with caution public IEnumerable<Type> AllConcreteTypes { get { return (from x in _providers from p in x.Value select p.GetInstanceType()).Where(x => x != null && !x.IsInterface && !x.IsAbstract).Distinct(); } } public DiContainer CreateSubContainer() { #if ZEN_NOT_UNITY3D return new DiContainer(this); #else return new DiContainer(_rootTransform, this); #endif } public void RegisterProvider( ProviderBase provider, BindingId bindingId) { if (_providers.ContainsKey(bindingId)) { // Prevent duplicate singleton bindings: if (_providers[bindingId].Find(item => ReferenceEquals(item, provider)) != null) { throw new ZenjectBindException( "Found duplicate singleton binding for contract '{0}' and id '{1}'".Fmt(bindingId.Type, bindingId.Identifier)); } _providers[bindingId].Add(provider); } else { _providers.Add(bindingId, new List<ProviderBase> {provider}); } } public int UnregisterProvider(ProviderBase provider) { int numRemoved = 0; foreach (var keyValue in _providers) { numRemoved += keyValue.Value.RemoveAll(x => x == provider); } Assert.That(numRemoved > 0, "Tried to unregister provider that was not registered"); // Remove any empty contracts foreach (var bindingId in _providers.Where(x => x.Value.IsEmpty()).Select(x => x.Key).ToList()) { _providers.Remove(bindingId); } provider.Dispose(); return numRemoved; } public IEnumerable<Type> GetDependencyContracts<TContract>() { return GetDependencyContracts(typeof(TContract)); } public IEnumerable<ZenjectResolveException> ValidateResolve<TContract>() { return ValidateResolve<TContract>((string)null); } public IEnumerable<ZenjectResolveException> ValidateResolve<TContract>(string identifier) { return ValidateResolve(new InjectContext(this, typeof(TContract), identifier)); } public IEnumerable<ZenjectResolveException> ValidateValidatables(params Type[] ignoreTypes) { // Use ToList() in case it changes somehow during iteration foreach (var pair in _providers.ToList()) { var bindingId = pair.Key; if (ignoreTypes.Where(i => bindingId.Type.DerivesFromOrEqual(i)).Any()) { continue; } // Validate all IValidatableFactory's List<ProviderBase> validatableFactoryProviders; var providers = pair.Value; if (bindingId.Type.DerivesFrom<IValidatableFactory>()) { validatableFactoryProviders = providers; } else { validatableFactoryProviders = providers.Where(x => x.GetInstanceType().DerivesFrom<IValidatableFactory>()).ToList(); } var injectCtx = new InjectContext(this, bindingId.Type, bindingId.Identifier); foreach (var provider in validatableFactoryProviders) { var factory = (IValidatableFactory)provider.GetInstance(injectCtx); var type = factory.ConstructedType; var providedArgs = factory.ProvidedTypes; foreach (var error in ValidateObjectGraph(type, injectCtx, null, providedArgs)) { yield return error; } } // Validate all IValidatable's List<ProviderBase> validatableProviders; if (bindingId.Type.DerivesFrom<IValidatable>()) { validatableProviders = providers; } else { validatableProviders = providers.Where(x => x.GetInstanceType().DerivesFrom<IValidatable>()).ToList(); } Assert.That(validatableFactoryProviders.Intersect(validatableProviders).IsEmpty(), "Found provider implementing both IValidatable and IValidatableFactory. This is not allowed."); foreach (var provider in validatableProviders) { var factory = (IValidatable)provider.GetInstance(injectCtx); foreach (var error in factory.Validate()) { yield return error; } } } } // Wrap IEnumerable<> to avoid LINQ mistakes internal List<ProviderBase> GetAllProviderMatches(InjectContext context) { return GetProviderMatchesInternal(context).Select(x => x.Provider).ToList(); } // Be careful with this method since it is a coroutine IEnumerable<ProviderPair> GetProviderMatchesInternal(InjectContext context) { return GetProvidersForContract(context.BindingId, context.LocalOnly).Where(x => x.Provider.Matches(context)); } IEnumerable<ProviderPair> GetProvidersForContract(BindingId bindingId, bool localOnly) { var localPairs = GetLocalProviders(bindingId).Select(x => new ProviderPair(x, this)); if (localOnly || _parentContainer == null) { return localPairs; } return localPairs.Concat( _parentContainer.GetProvidersForContract(bindingId, false)); } List<ProviderBase> GetLocalProviders(BindingId bindingId) { List<ProviderBase> localProviders; if (_providers.TryGetValue(bindingId, out localProviders)) { return localProviders; } // If we are asking for a List<int>, we should also match for any localProviders that are bound to the open generic type List<> // Currently it only matches one and not the other - not totally sure if this is better than returning both if (bindingId.Type.IsGenericType && _providers.TryGetValue(new BindingId(bindingId.Type.GetGenericTypeDefinition(), bindingId.Identifier), out localProviders)) { return localProviders; } return new List<ProviderBase>(); } public IList ResolveAll(InjectContext context) { // Note that different types can map to the same provider (eg. a base type to a concrete class and a concrete class to itself) var matches = GetProviderMatchesInternal(context).ToList(); if (matches.Any()) { return ReflectionUtil.CreateGenericList( context.MemberType, matches.Select(x => SafeGetInstance(x.Provider, context)).ToArray()); } if (!context.Optional) { throw new ZenjectResolveException( "Could not find required dependency with type '" + context.MemberType.Name() + "' \nObject graph:\n" + context.GetObjectGraphString()); } return ReflectionUtil.CreateGenericList(context.MemberType, new object[] {}); } public List<Type> ResolveTypeAll(InjectContext context) { if (_providers.ContainsKey(context.BindingId)) { return _providers[context.BindingId].Select(x => x.GetInstanceType()).Where(x => x != null).ToList(); } return new List<Type> {}; } public void Install(IEnumerable<IInstaller> installers) { foreach (var installer in installers) { Assert.IsNotNull(installer, "Tried to install a null installer"); if (installer.IsEnabled) { Install(installer); } } } public void Install(IInstaller installer) { Assert.That(installer.IsEnabled); this.Inject(installer); InstallInstallerInternal(installer); } public void Install<T>(params object[] extraArgs) where T : IInstaller { Install(typeof(T), extraArgs); } public void Install(Type installerType, params object[] extraArgs) { Assert.That(installerType.DerivesFrom<IInstaller>()); #if !ZEN_NOT_UNITY3D if (installerType.DerivesFrom<MonoInstaller>()) { var installer = InstantiatePrefabResourceForComponent<MonoInstaller>("Installers/" + installerType.Name(), extraArgs); try { InstallInstallerInternal(installer); } finally { // When running, it is nice to keep the installer around so that you can change the settings live // But when validating at edit time, we don't want to add the new game object if (!Application.isPlaying) { GameObject.DestroyImmediate(installer.gameObject); } } } else #endif { var installer = (IInstaller)this.Instantiate(installerType, extraArgs); InstallInstallerInternal(installer); } } public bool HasInstalled<T>() where T : IInstaller { return HasInstalled(typeof(T)); } public bool HasInstalled(Type installerType) { return _installedInstallers.Where(x => x == installerType).Any(); } void InstallInstallerInternal(IInstaller installer) { var installerType = installer.GetType(); Log.Debug("Installing installer '{0}'", installerType); Assert.That(!_installsInProgress.Contains(installerType), "Potential infinite loop detected while installing '{0}'", installerType.Name()); Assert.That(!_installedInstallers.Contains(installerType), "Tried installing installer '{0}' twice", installerType.Name()); _installedInstallers.Add(installerType); _installsInProgress.Push(installerType); try { installer.InstallBindings(); } catch (Exception e) { // This context information is really helpful when bind commands fail throw new Exception( "Error occurred while running installer '{0}'".Fmt(installer.GetType().Name()), e); } finally { Assert.That(_installsInProgress.Peek().Equals(installerType)); _installsInProgress.Pop(); } } // Try looking up a single provider for a given context // Note that this method should not throw zenject exceptions internal ProviderLookupResult TryGetUniqueProvider( InjectContext context, out ProviderBase provider) { // Note that different types can map to the same provider (eg. a base type to a concrete class and a concrete class to itself) var providers = GetProviderMatchesInternal(context).ToList(); if (providers.IsEmpty()) { provider = null; return ProviderLookupResult.None; } if (providers.Count > 1) { // If we find multiple providers and we are looking for just one, then // try to intelligently choose one from the list before giving up // First try picking the most 'local' dependencies // This will bias towards bindings for the lower level specific containers rather than the global high level container // This will, for example, allow you to just ask for a DiContainer dependency without needing to specify [InjectLocal] // (otherwise it would always match for a list of DiContainer's for all parent containers) var sortedProviders = providers.Select(x => new { Pair = x, Distance = GetContainerHeirarchyDistance(x.Container) }).OrderBy(x => x.Distance).ToList(); sortedProviders.RemoveAll(x => x.Distance != sortedProviders[0].Distance); if (sortedProviders.Count == 1) { // We have one match that is the closest provider = sortedProviders[0].Pair.Provider; } else { // Try choosing the one with a condition before giving up and throwing an exception // This is nice because it allows us to bind a default and then override with conditions provider = sortedProviders.Select(x => x.Pair.Provider).Where(x => x.Condition != null).OnlyOrDefault(); if (provider == null) { return ProviderLookupResult.Multiple; } } } else { provider = providers.Single().Provider; } Assert.IsNotNull(provider); return ProviderLookupResult.Success; } // Return single instance of requested type or assert public object Resolve(InjectContext context) { ProviderBase provider; var result = TryGetUniqueProvider(context, out provider); if (result == ProviderLookupResult.Multiple) { throw new ZenjectResolveException( "Found multiple matches when only one was expected for type '{0}'{1}. \nObject graph:\n {2}" .Fmt( context.MemberType.Name(), (context.ObjectType == null ? "" : " while building object with type '{0}'".Fmt(context.ObjectType.Name())), context.GetObjectGraphString())); } if (result == ProviderLookupResult.None) { // If it's a generic list then try matching multiple instances to its generic type if (ReflectionUtil.IsGenericList(context.MemberType)) { var subType = context.MemberType.GetGenericArguments().Single(); var subContext = context.ChangeMemberType(subType); return ResolveAll(subContext); } if (context.Optional) { return context.FallBackValue; } throw new ZenjectResolveException( "Unable to resolve type '{0}'{1}. \nObject graph:\n{2}" .Fmt( context.MemberType.Name() + (context.Identifier == null ? "" : " with ID '" + context.Identifier.ToString() + "'"), (context.ObjectType == null ? "" : " while building object with type '{0}'".Fmt(context.ObjectType.Name())), context.GetObjectGraphString())); } Assert.That(result == ProviderLookupResult.Success); Assert.IsNotNull(provider); return SafeGetInstance(provider, context); } object SafeGetInstance(ProviderBase provider, InjectContext context) { if (ChecksForCircularDependencies) { var lookupId = new LookupId(provider, context.BindingId); // Allow one before giving up so that you can do circular dependencies via postinject or fields if (_resolvesInProgress.Where(x => x.Equals(lookupId)).Count() > 1) { throw new ZenjectResolveException( "Circular dependency detected! \nObject graph:\n {0}".Fmt(context.GetObjectGraphString())); } _resolvesInProgress.Push(lookupId); try { return provider.GetInstance(context); } finally { Assert.That(_resolvesInProgress.Peek().Equals(lookupId)); _resolvesInProgress.Pop(); } } else { return provider.GetInstance(context); } } int GetContainerHeirarchyDistance(DiContainer container) { return GetContainerHeirarchyDistance(container, 0); } int GetContainerHeirarchyDistance(DiContainer container, int depth) { if (container == this) { return depth; } Assert.IsNotNull(_parentContainer); return _parentContainer.GetContainerHeirarchyDistance(container, depth + 1); } public IEnumerable<Type> GetDependencyContracts(Type contract) { foreach (var injectMember in TypeAnalyzer.GetInfo(contract).AllInjectables) { yield return injectMember.MemberType; } } // Same as Instantiate except you can pass in null value // however the type for each parameter needs to be explicitly provided in this case public object InstantiateExplicit( Type concreteType, List<TypeValuePair> extraArgMap, InjectContext currentContext, string concreteIdentifier, bool autoInject) { #if PROFILING_ENABLED using (ProfileBlock.Start("Zenject.Instantiate({0})", concreteType)) #endif { return InstantiateInternal(concreteType, extraArgMap, currentContext, concreteIdentifier, autoInject); } } object InstantiateInternal( Type concreteType, IEnumerable<TypeValuePair> extraArgs, InjectContext currentContext, string concreteIdentifier, bool autoInject) { #if !ZEN_NOT_UNITY3D Assert.That(!concreteType.DerivesFrom<UnityEngine.Component>(), "Error occurred while instantiating object of type '{0}'. Instantiator should not be used to create new mono behaviours. Must use InstantiatePrefabForComponent, InstantiatePrefab, InstantiateComponentOnNewGameObject, InstantiateGameObject, or InstantiateComponent. You may also want to use GameObjectFactory class or plain old GameObject.Instantiate.", concreteType.Name()); #endif var typeInfo = TypeAnalyzer.GetInfo(concreteType); if (typeInfo.InjectConstructor == null) { throw new ZenjectResolveException( "More than one (or zero) constructors found for type '{0}' when creating dependencies. Use one [Inject] attribute to specify which to use.".Fmt(concreteType)); } // Make a copy since we remove from it below var extraArgList = extraArgs.ToList(); var paramValues = new List<object>(); foreach (var injectInfo in typeInfo.ConstructorInjectables) { object value; if (!InstantiateUtil.PopValueWithType(extraArgList, injectInfo.MemberType, out value)) { value = Resolve(injectInfo.CreateInjectContext(this, currentContext, null, concreteIdentifier)); } paramValues.Add(value); } object newObj; //Log.Debug("Zenject: Instantiating type '{0}'", concreteType.Name()); try { #if PROFILING_ENABLED using (ProfileBlock.Start("{0}.{0}()", concreteType)) #endif { newObj = typeInfo.InjectConstructor.Invoke(paramValues.ToArray()); } } catch (Exception e) { throw new ZenjectResolveException( "Error occurred while instantiating object with type '{0}'".Fmt(concreteType.Name()), e); } if (autoInject) { InjectExplicit(newObj, extraArgList, true, typeInfo, currentContext, concreteIdentifier); } else { if (!extraArgList.IsEmpty()) { throw new ZenjectResolveException( "Passed unnecessary parameters when injecting into type '{0}'. \nExtra Parameters: {1}\nObject graph:\n{2}" .Fmt(newObj.GetType().Name(), String.Join(",", extraArgList.Select(x => x.Type.Name()).ToArray()), currentContext.GetObjectGraphString())); } } return newObj; } // Iterate over fields/properties on the given object and inject any with the [Inject] attribute public void InjectExplicit( object injectable, IEnumerable<TypeValuePair> extraArgs, bool shouldUseAll, ZenjectTypeInfo typeInfo, InjectContext context, string concreteIdentifier) { Assert.IsEqual(typeInfo.TypeAnalyzed, injectable.GetType()); Assert.That(injectable != null); #if !ZEN_NOT_UNITY3D Assert.That(injectable.GetType() != typeof(GameObject), "Use InjectGameObject to Inject game objects instead of Inject method"); #endif // Make a copy since we remove from it below var extraArgsList = extraArgs.ToList(); foreach (var injectInfo in typeInfo.FieldInjectables.Concat(typeInfo.PropertyInjectables)) { object value; if (InstantiateUtil.PopValueWithType(extraArgsList, injectInfo.MemberType, out value)) { injectInfo.Setter(injectable, value); } else { value = Resolve( injectInfo.CreateInjectContext(this, context, injectable, concreteIdentifier)); if (injectInfo.Optional && value == null) { // Do not override in this case so it retains the hard-coded value } else { injectInfo.Setter(injectable, value); } } } foreach (var method in typeInfo.PostInjectMethods) { #if PROFILING_ENABLED using (ProfileBlock.Start("{0}.{1}()", injectable.GetType(), method.MethodInfo.Name)) #endif { var paramValues = new List<object>(); foreach (var injectInfo in method.InjectableInfo) { object value; if (!InstantiateUtil.PopValueWithType(extraArgsList, injectInfo.MemberType, out value)) { value = Resolve( injectInfo.CreateInjectContext(this, context, injectable, concreteIdentifier)); } paramValues.Add(value); } method.MethodInfo.Invoke(injectable, paramValues.ToArray()); } } if (shouldUseAll && !extraArgsList.IsEmpty()) { throw new ZenjectResolveException( "Passed unnecessary parameters when injecting into type '{0}'. \nExtra Parameters: {1}\nObject graph:\n{2}" .Fmt(injectable.GetType().Name(), String.Join(",", extraArgsList.Select(x => x.Type.Name()).ToArray()), context.GetObjectGraphString())); } } #if !ZEN_NOT_UNITY3D // NOTE: gameobject here is not a prefab prototype, it is an instance public Component InstantiateComponent( Type componentType, GameObject gameObject, params object[] extraArgMap) { Assert.That(componentType.DerivesFrom<Component>()); var monoBehaviour = (Component)gameObject.AddComponent(componentType); this.Inject(monoBehaviour, extraArgMap); return monoBehaviour; } public GameObject InstantiatePrefabResourceExplicit( string resourcePath, IEnumerable<object> extraArgMap, InjectContext context) { return InstantiatePrefabResourceExplicit(resourcePath, extraArgMap, context, false); } public GameObject InstantiatePrefabResourceExplicit( string resourcePath, IEnumerable<object> extraArgMap, InjectContext context, bool includeInactive) { var prefab = (GameObject)Resources.Load(resourcePath); Assert.IsNotNull(prefab, "Could not find prefab at resource location '{0}'".Fmt(resourcePath)); return InstantiatePrefabExplicit(prefab, extraArgMap, context, includeInactive); } public GameObject InstantiatePrefabExplicit( GameObject prefab, IEnumerable<object> extraArgMap, InjectContext context) { return InstantiatePrefabExplicit(prefab, extraArgMap, context, false); } public GameObject InstantiatePrefabExplicit( GameObject prefab, IEnumerable<object> extraArgMap, InjectContext context, bool includeInactive) { var gameObj = (GameObject)GameObject.Instantiate(prefab); if (_rootTransform != null) { // By default parent to comp root // This is good so that the entire object graph is // contained underneath it, which is useful for cases // where you need to delete the entire object graph gameObj.transform.SetParent(_rootTransform, false); } gameObj.SetActive(true); this.InjectGameObject(gameObj, true, includeInactive, extraArgMap, context); return gameObj; } // Create a new empty game object under the composition root public GameObject InstantiateGameObject(string name) { var gameObj = new GameObject(name); if (_rootTransform != null) { gameObj.transform.SetParent(_rootTransform, false); } return gameObj; } public object InstantiateComponentOnNewGameObjectExplicit( Type componentType, string name, List<TypeValuePair> extraArgMap, InjectContext currentContext) { Assert.That(componentType.DerivesFrom<Component>(), "Expected type '{0}' to derive from UnityEngine.Component", componentType.Name()); var gameObj = new GameObject(name); if (_rootTransform != null) { gameObj.transform.SetParent(_rootTransform, false); } if (componentType == typeof(Transform)) { Assert.That(extraArgMap.IsEmpty()); return gameObj.transform; } var component = (Component)gameObj.AddComponent(componentType); this.InjectExplicit(component, extraArgMap, currentContext); return component; } public object InstantiatePrefabResourceForComponentExplicit( Type componentType, string resourcePath, List<TypeValuePair> extraArgs, InjectContext currentContext) { var prefab = (GameObject)Resources.Load(resourcePath); Assert.IsNotNull(prefab, "Could not find prefab at resource location '{0}'".Fmt(resourcePath)); return InstantiatePrefabForComponentExplicit( componentType, prefab, extraArgs, currentContext); } public object InstantiatePrefabForComponentExplicit( Type componentType, GameObject prefab, List<TypeValuePair> extraArgs, InjectContext currentContext) { return InstantiatePrefabForComponentExplicit(componentType, prefab, extraArgs, currentContext, false); } public object InstantiatePrefabForComponentExplicit( Type componentType, GameObject prefab, List<TypeValuePair> extraArgs, InjectContext currentContext, bool includeInactive) { Assert.That(prefab != null, "Null prefab found when instantiating game object"); // It could be an interface so this may fail in valid cases so you may want to comment out // Leaving it in for now to catch the more likely scenario of it being a mistake Assert.That(componentType.DerivesFrom<Component>(), "Expected type '{0}' to derive from UnityEngine.Component", componentType.Name()); var gameObj = (GameObject)GameObject.Instantiate(prefab); if (_rootTransform != null) { // By default parent to comp root // This is good so that the entire object graph is // contained underneath it, which is useful for cases // where you need to delete the entire object graph gameObj.transform.SetParent(_rootTransform, false); } gameObj.SetActive(true); Component requestedScript = null; // Inject on the children first since the parent objects are more likely to use them in their post inject methods foreach (var component in UnityUtil.GetComponentsInChildrenBottomUp(gameObj, includeInactive)) { if (component != null) { if (component.GetType().DerivesFromOrEqual(componentType)) { Assert.IsNull(requestedScript, "Found multiple matches with type '{0}' when instantiating new game object from prefab '{1}'", componentType, prefab.name); requestedScript = component; this.InjectExplicit(component, extraArgs); } else { this.Inject(component); } } else { Log.Warn("Found null component while instantiating prefab '{0}'. Possible missing script.", prefab.name); } } if (requestedScript == null) { throw new ZenjectResolveException( "Could not find component with type '{0}' when instantiating new game object".Fmt(componentType)); } return requestedScript; } #endif ////////////// Convenience methods for IInstantiator //////////////// public T Instantiate<T>( params object[] extraArgs) { return (T)Instantiate(typeof(T), extraArgs); } public object Instantiate( Type concreteType, params object[] extraArgs) { Assert.That(!extraArgs.ContainsItem(null), "Null value given to factory constructor arguments when instantiating object with type '{0}'. In order to use null use InstantiateExplicit", concreteType); return InstantiateExplicit( concreteType, InstantiateUtil.CreateTypeValueList(extraArgs)); } // This is used instead of Instantiate to support specifying null values public T InstantiateExplicit<T>( List<TypeValuePair> extraArgMap) { return (T)InstantiateExplicit(typeof(T), extraArgMap); } public T InstantiateExplicit<T>( List<TypeValuePair> extraArgMap, InjectContext context) { return (T)InstantiateExplicit( typeof(T), extraArgMap, context); } public object InstantiateExplicit( Type concreteType, List<TypeValuePair> extraArgMap) { return InstantiateExplicit( concreteType, extraArgMap, new InjectContext(this, concreteType, null)); } public object InstantiateExplicit( Type concreteType, List<TypeValuePair> extraArgMap, InjectContext context) { return InstantiateExplicit( concreteType, extraArgMap, context, null, true); } #if !ZEN_NOT_UNITY3D public TContract InstantiateComponent<TContract>( GameObject gameObject, params object[] args) where TContract : Component { return (TContract)InstantiateComponent(typeof(TContract), gameObject, args); } public GameObject InstantiatePrefab( GameObject prefab, params object[] args) { return InstantiatePrefabExplicit(prefab, args, null); } public GameObject InstantiatePrefab( bool includeInactive, GameObject prefab, params object[] args) { return InstantiatePrefabExplicit(prefab, args, null, includeInactive); } public GameObject InstantiatePrefabResource( string resourcePath, params object[] args) { return InstantiatePrefabResourceExplicit(resourcePath, args, null, false); } public GameObject InstantiatePrefabResource( bool includeInactive, string resourcePath, params object[] args) { return InstantiatePrefabResourceExplicit(resourcePath, args, null, includeInactive); } /////////////// InstantiatePrefabForComponent public T InstantiatePrefabForComponent<T>( GameObject prefab, params object[] extraArgs) { return (T)InstantiatePrefabForComponent(typeof(T), prefab, extraArgs); } public object InstantiatePrefabForComponent( Type concreteType, GameObject prefab, params object[] extraArgs) { Assert.That(!extraArgs.ContainsItem(null), "Null value given to factory constructor arguments when instantiating object with type '{0}'. In order to use null use InstantiatePrefabForComponentExplicit", concreteType); return InstantiatePrefabForComponentExplicit( concreteType, prefab, InstantiateUtil.CreateTypeValueList(extraArgs)); } public T InstantiatePrefabForComponent<T>( bool includeInactive, GameObject prefab, params object[] extraArgs) { return (T)InstantiatePrefabForComponent(includeInactive, typeof(T), prefab, extraArgs); } public object InstantiatePrefabForComponent( bool includeInactive, Type concreteType, GameObject prefab, params object[] extraArgs) { Assert.That(!extraArgs.Contains(null), "Null value given to factory constructor arguments when instantiating object with type '{0}'. In order to use null use InstantiatePrefabForComponentExplicit", concreteType); return InstantiatePrefabForComponentExplicit( concreteType, prefab, InstantiateUtil.CreateTypeValueList(extraArgs), new InjectContext(this, concreteType, null), includeInactive); } // This is used instead of Instantiate to support specifying null values public T InstantiatePrefabForComponentExplicit<T>( GameObject prefab, List<TypeValuePair> extraArgMap) { return (T)InstantiatePrefabForComponentExplicit(typeof(T), prefab, extraArgMap); } public object InstantiatePrefabForComponentExplicit( Type concreteType, GameObject prefab, List<TypeValuePair> extraArgMap) { return InstantiatePrefabForComponentExplicit( concreteType, prefab, extraArgMap, new InjectContext(this, concreteType, null)); } /////////////// InstantiatePrefabForComponent public T InstantiatePrefabResourceForComponent<T>( string resourcePath, params object[] extraArgs) { return (T)InstantiatePrefabResourceForComponent(typeof(T), resourcePath, extraArgs); } public object InstantiatePrefabResourceForComponent( Type concreteType, string resourcePath, params object[] extraArgs) { Assert.That(!extraArgs.ContainsItem(null), "Null value given to factory constructor arguments when instantiating object with type '{0}'. In order to use null use InstantiatePrefabForComponentExplicit", concreteType); return InstantiatePrefabResourceForComponentExplicit( concreteType, resourcePath, InstantiateUtil.CreateTypeValueList(extraArgs)); } // This is used instead of Instantiate to support specifying null values public T InstantiatePrefabResourceForComponentExplicit<T>( string resourcePath, List<TypeValuePair> extraArgMap) { return (T)InstantiatePrefabResourceForComponentExplicit(typeof(T), resourcePath, extraArgMap); } public object InstantiatePrefabResourceForComponentExplicit( Type concreteType, string resourcePath, List<TypeValuePair> extraArgMap) { return InstantiatePrefabResourceForComponentExplicit( concreteType, resourcePath, extraArgMap, new InjectContext(this, concreteType, null)); } /////////////// InstantiateComponentOnNewGameObject public T InstantiateComponentOnNewGameObject<T>( string name, params object[] extraArgs) { return (T)InstantiateComponentOnNewGameObject(typeof(T), name, extraArgs); } public object InstantiateComponentOnNewGameObject( Type concreteType, string name, params object[] extraArgs) { Assert.That(!extraArgs.ContainsItem(null), "Null value given to factory constructor arguments when instantiating object with type '{0}'. In order to use null use InstantiateComponentOnNewGameObjectExplicit", concreteType); return InstantiateComponentOnNewGameObjectExplicit( concreteType, name, InstantiateUtil.CreateTypeValueList(extraArgs)); } // This is used instead of Instantiate to support specifying null values public T InstantiateComponentOnNewGameObjectExplicit<T>( string name, List<TypeValuePair> extraArgMap) { return (T)InstantiateComponentOnNewGameObjectExplicit(typeof(T), name, extraArgMap); } public object InstantiateComponentOnNewGameObjectExplicit( Type concreteType, string name, List<TypeValuePair> extraArgMap) { return InstantiateComponentOnNewGameObjectExplicit( concreteType, name, extraArgMap, new InjectContext(this, concreteType, null)); } #endif ////////////// Convenience methods for IResolver //////////////// #if !ZEN_NOT_UNITY3D // Inject dependencies into child game objects public void InjectGameObject( GameObject gameObject, bool recursive, bool includeInactive) { InjectGameObject(gameObject, recursive, includeInactive, Enumerable.Empty<object>()); } public void InjectGameObject( GameObject gameObject, bool recursive) { InjectGameObject(gameObject, recursive, false); } public void InjectGameObject( GameObject gameObject) { InjectGameObject(gameObject, true, false); } public void InjectGameObject( GameObject gameObject, bool recursive, bool includeInactive, IEnumerable<object> extraArgs) { InjectGameObject( gameObject, recursive, includeInactive, extraArgs, null); } public void InjectGameObject( GameObject gameObject, bool recursive, bool includeInactive, IEnumerable<object> extraArgs, InjectContext context) { IEnumerable<Component> components; if (recursive) { components = UnityUtil.GetComponentsInChildrenBottomUp(gameObject, includeInactive); } else { if (!includeInactive && !gameObject.activeSelf) { return; } components = gameObject.GetComponents<Component>(); } foreach (var component in components) { // null if monobehaviour link is broken // Do not inject on installers since these are always injected before they are installed if (component != null && !component.GetType().DerivesFrom<MonoInstaller>()) { Inject(component, extraArgs, false, context); } } } #endif public void Inject(object injectable) { Inject(injectable, Enumerable.Empty<object>()); } public void Inject(object injectable, IEnumerable<object> additional) { Inject(injectable, additional, true); } public void Inject(object injectable, IEnumerable<object> additional, bool shouldUseAll) { Inject( injectable, additional, shouldUseAll, new InjectContext(this, injectable.GetType(), null)); } public void Inject( object injectable, IEnumerable<object> additional, bool shouldUseAll, InjectContext context) { Inject( injectable, additional, shouldUseAll, context, TypeAnalyzer.GetInfo(injectable.GetType())); } public void Inject( object injectable, IEnumerable<object> additional, bool shouldUseAll, InjectContext context, ZenjectTypeInfo typeInfo) { Assert.That(!additional.ContainsItem(null), "Null value given to injection argument list. In order to use null you must provide a List<TypeValuePair> and not just a list of objects"); InjectExplicit( injectable, InstantiateUtil.CreateTypeValueList(additional), shouldUseAll, typeInfo, context, null); } public void InjectExplicit(object injectable, List<TypeValuePair> additional) { InjectExplicit( injectable, additional, new InjectContext(this, injectable.GetType(), null)); } public void InjectExplicit(object injectable, List<TypeValuePair> additional, InjectContext context) { InjectExplicit( injectable, additional, true, TypeAnalyzer.GetInfo(injectable.GetType()), context, null); } public List<Type> ResolveTypeAll(Type type) { return ResolveTypeAll(new InjectContext(this, type, null)); } public TContract Resolve<TContract>() { return Resolve<TContract>((string)null); } public TContract Resolve<TContract>(string identifier) { return Resolve<TContract>(new InjectContext(this, typeof(TContract), identifier)); } public TContract TryResolve<TContract>() where TContract : class { return TryResolve<TContract>((string)null); } public TContract TryResolve<TContract>(string identifier) where TContract : class { return (TContract)TryResolve(typeof(TContract), identifier); } public object TryResolve(Type contractType) { return TryResolve(contractType, null); } public object TryResolve(Type contractType, string identifier) { return Resolve(new InjectContext(this, contractType, identifier, true)); } public object Resolve(Type contractType) { return Resolve(new InjectContext(this, contractType, null)); } public object Resolve(Type contractType, string identifier) { return Resolve(new InjectContext(this, contractType, identifier)); } public TContract Resolve<TContract>(InjectContext context) { Assert.IsEqual(context.MemberType, typeof(TContract)); return (TContract) Resolve(context); } public List<TContract> ResolveAll<TContract>() { return ResolveAll<TContract>((string)null); } public List<TContract> ResolveAll<TContract>(bool optional) { return ResolveAll<TContract>(null, optional); } public List<TContract> ResolveAll<TContract>(string identifier) { return ResolveAll<TContract>(identifier, false); } public List<TContract> ResolveAll<TContract>(string identifier, bool optional) { var context = new InjectContext(this, typeof(TContract), identifier, optional); return ResolveAll<TContract>(context); } public List<TContract> ResolveAll<TContract>(InjectContext context) { Assert.IsEqual(context.MemberType, typeof(TContract)); return (List<TContract>) ResolveAll(context); } public IList ResolveAll(Type contractType) { return ResolveAll(contractType, null); } public IList ResolveAll(Type contractType, string identifier) { return ResolveAll(contractType, identifier, false); } public IList ResolveAll(Type contractType, bool optional) { return ResolveAll(contractType, null, optional); } public IList ResolveAll(Type contractType, string identifier, bool optional) { var context = new InjectContext(this, contractType, identifier, optional); return ResolveAll(context); } ////////////// IBinder //////////////// public bool Unbind<TContract>(string identifier) { List<ProviderBase> providersToRemove; var bindingId = new BindingId(typeof(TContract), identifier); if (_providers.TryGetValue(bindingId, out providersToRemove)) { _providers.Remove(bindingId); // Only dispose if the provider is not bound to another type foreach (var provider in providersToRemove) { if (_providers.Where(x => x.Value.ContainsItem(provider)).IsEmpty()) { provider.Dispose(); } } return true; } return false; } public BindingConditionSetter BindInstance<TContract>(string identifier, TContract obj) { return Bind<TContract>(identifier).ToInstance(obj); } public BindingConditionSetter BindInstance<TContract>(TContract obj) { return Bind<TContract>().ToInstance(obj); } public GenericBinder<TContract> Bind<TContract>() { return Bind<TContract>(null); } public UntypedBinder Bind(Type contractType) { return Bind(contractType, null); } public bool Unbind<TContract>() { return Unbind<TContract>(null); } public bool HasBinding(InjectContext context) { List<ProviderBase> providers; if (!_providers.TryGetValue(context.BindingId, out providers)) { return false; } return providers.Where(x => x.Matches(context)).HasAtLeast(1); } public bool HasBinding<TContract>() { return HasBinding<TContract>(null); } public bool HasBinding<TContract>(string identifier) { return HasBinding( new InjectContext(this, typeof(TContract), identifier)); } public void BindAllInterfacesToSingle<TConcrete>() { BindAllInterfacesToSingle(typeof(TConcrete)); } public void BindAllInterfacesToSingle(Type concreteType) { foreach (var interfaceType in concreteType.GetInterfaces()) { Assert.That(concreteType.DerivesFrom(interfaceType)); Bind(interfaceType).ToSingle(concreteType); } } public void BindAllInterfacesToInstance(object value) { BindAllInterfacesToInstance(value.GetType(), value); } public void BindAllInterfacesToInstance(Type concreteType, object value) { Assert.That((value == null && IsValidating) || value.GetType().DerivesFromOrEqual(concreteType)); foreach (var interfaceType in concreteType.GetInterfaces()) { Assert.That(concreteType.DerivesFrom(interfaceType)); Bind(interfaceType).ToInstance(concreteType, value); } } public IFactoryUntypedBinder<TContract> BindIFactoryUntyped<TContract>(string identifier) { return new IFactoryUntypedBinder<TContract>(this, identifier); } public IFactoryUntypedBinder<TContract> BindIFactoryUntyped<TContract>() { return BindIFactoryUntyped<TContract>(null); } public IFactoryBinder<TContract> BindIFactory<TContract>(string identifier) { return new IFactoryBinder<TContract>(this, identifier); } public IFactoryBinder<TContract> BindIFactory<TContract>() { return BindIFactory<TContract>(null); } public IFactoryBinder<TParam1, TContract> BindIFactory<TParam1, TContract>(string identifier) { return new IFactoryBinder<TParam1, TContract>(this, identifier); } public IFactoryBinder<TParam1, TContract> BindIFactory<TParam1, TContract>() { return BindIFactory<TParam1, TContract>(null); } public IFactoryBinder<TParam1, TParam2, TContract> BindIFactory<TParam1, TParam2, TContract>(string identifier) { return new IFactoryBinder<TParam1, TParam2, TContract>(this, identifier); } public IFactoryBinder<TParam1, TParam2, TContract> BindIFactory<TParam1, TParam2, TContract>() { return BindIFactory<TParam1, TParam2, TContract>(null); } public IFactoryBinder<TParam1, TParam2, TParam3, TContract> BindIFactory<TParam1, TParam2, TParam3, TContract>(string identifier) { return new IFactoryBinder<TParam1, TParam2, TParam3, TContract>(this, identifier); } public IFactoryBinder<TParam1, TParam2, TParam3, TContract> BindIFactory<TParam1, TParam2, TParam3, TContract>() { return BindIFactory<TParam1, TParam2, TParam3, TContract>(null); } public IFactoryBinder<TParam1, TParam2, TParam3, TParam4, TContract> BindIFactory<TParam1, TParam2, TParam3, TParam4, TContract>(string identifier) { return new IFactoryBinder<TParam1, TParam2, TParam3, TParam4, TContract>(this, identifier); } public IFactoryBinder<TParam1, TParam2, TParam3, TParam4, TContract> BindIFactory<TParam1, TParam2, TParam3, TParam4, TContract>() { return BindIFactory<TParam1, TParam2, TParam3, TParam4, TContract>(null); } public GenericBinder<TContract> Rebind<TContract>() { this.Unbind<TContract>(); return this.Bind<TContract>(); } public GenericBinder<TContract> Bind<TContract>(string identifier) { Assert.That(!typeof(TContract).DerivesFromOrEqual<IInstaller>(), "Deprecated usage of Bind<IInstaller>, use Install<IInstaller> instead"); return new GenericBinder<TContract>(this, identifier, _singletonMap); } public FacadeBinder<TFacade> BindFacade<TFacade>(Action<DiContainer> installerFunc) where TFacade : IFacade { return BindFacade<TFacade>(installerFunc, null); } public FacadeBinder<TFacade> BindFacade<TFacade>( Action<DiContainer> installerFunc, string identifier) where TFacade : IFacade { return new FacadeBinder<TFacade>(this, identifier, installerFunc); } // Note that this can include open generic types as well such as List<> public UntypedBinder Bind(Type contractType, string identifier) { Assert.That(!contractType.DerivesFromOrEqual<IInstaller>(), "Deprecated usage of Bind<IInstaller>, use Install<IInstaller> instead"); return new UntypedBinder(this, contractType, identifier, _singletonMap); } #if !ZEN_NOT_UNITY3D public BindingConditionSetter BindGameObjectFactory<T>( GameObject prefab) // This would be useful but fails with VerificationException's in webplayer builds for some reason //where T : GameObjectFactory where T : class { if (prefab == null) { throw new ZenjectBindException( "Null prefab provided to BindGameObjectFactory for type '{0}'".Fmt(typeof(T).Name())); } // We could bind the factory ToSingle but doing it this way is better // since it allows us to have multiple game object factories that // use different prefabs and have them injected into different places return Bind<T>().ToMethod((ctx) => ctx.Container.Instantiate<T>(prefab)); } #endif public BindingConditionSetter BindFacadeFactory<TFacade, TFacadeFactory>( Action<DiContainer> facadeInstaller) where TFacade : IFacade where TFacadeFactory : FacadeFactory<TFacade> { return this.Bind<TFacadeFactory>().ToMethod( x => x.Container.Instantiate<TFacadeFactory>(facadeInstaller)); } public BindingConditionSetter BindFacadeFactory<TParam1, TFacade, TFacadeFactory>( Action<DiContainer, TParam1> facadeInstaller) where TFacade : IFacade where TFacadeFactory : FacadeFactory<TParam1, TFacade> { return this.Bind<TFacadeFactory>().ToMethod( x => x.Container.Instantiate<TFacadeFactory>(facadeInstaller)); } public BindingConditionSetter BindFacadeFactory<TParam1, TParam2, TFacade, TFacadeFactory>( Action<DiContainer, TParam1, TParam2> facadeInstaller) where TFacade : IFacade where TFacadeFactory : FacadeFactory<TParam1, TParam2, TFacade> { return this.Bind<TFacadeFactory>().ToMethod( x => x.Container.Instantiate<TFacadeFactory>(facadeInstaller)); } public BindingConditionSetter BindFacadeFactory<TParam1, TParam2, TParam3, TFacade, TFacadeFactory>( Action<DiContainer, TParam1, TParam2, TParam3> facadeInstaller) where TFacade : IFacade where TFacadeFactory : FacadeFactory<TParam1, TParam2, TParam3, TFacade> { return this.Bind<TFacadeFactory>().ToMethod( x => x.Container.Instantiate<TFacadeFactory>(facadeInstaller)); } ////////////// Other //////////////// // Walk the object graph for the given type // Should never throw an exception - returns them instead // Note: If you just want to know whether a binding exists for the given TContract, // use HasBinding instead public IEnumerable<ZenjectResolveException> ValidateResolve(InjectContext context) { ProviderBase provider = null; var result = TryGetUniqueProvider(context, out provider); if (result == DiContainer.ProviderLookupResult.Success) { Assert.IsNotNull(provider); if (ChecksForCircularDependencies) { var lookupId = new LookupId(provider, context.BindingId); // Allow one before giving up so that you can do circular dependencies via postinject or fields if (_resolvesInProgress.Where(x => x.Equals(lookupId)).Count() > 1) { yield return new ZenjectResolveException( "Circular dependency detected! \nObject graph:\n {0}".Fmt(context.GetObjectGraphString())); } _resolvesInProgress.Push(lookupId); try { foreach (var error in provider.ValidateBinding(context)) { yield return error; } } finally { Assert.That(_resolvesInProgress.Peek().Equals(lookupId)); _resolvesInProgress.Pop(); } } else { foreach (var error in provider.ValidateBinding(context)) { yield return error; } } } else if (result == DiContainer.ProviderLookupResult.Multiple) { yield return new ZenjectResolveException( "Found multiple matches when only one was expected for dependency with type '{0}'{1} \nObject graph:\n{2}" .Fmt( context.MemberType.Name(), (context.ObjectType == null ? "" : " when injecting into '{0}'".Fmt(context.ObjectType.Name())), context.GetObjectGraphString())); } else { Assert.That(result == DiContainer.ProviderLookupResult.None); if (ReflectionUtil.IsGenericList(context.MemberType)) { var subType = context.MemberType.GetGenericArguments().Single(); var subContext = context.ChangeMemberType(subType); var matches = GetAllProviderMatches(subContext); if (matches.IsEmpty()) { if (!context.Optional) { yield return new ZenjectResolveException( "Could not find dependency with type 'List(0)'{1}. If the empty list is also valid, you can allow this by using the [InjectOptional] attribute.' \nObject graph:\n{2}" .Fmt( subContext.MemberType.Name(), (context.ObjectType == null ? "" : " when injecting into '{0}'".Fmt(context.ObjectType.Name())), context.GetObjectGraphString())); } } else { foreach (var match in matches) { foreach (var error in match.ValidateBinding(context)) { yield return error; } } } } else { if (!context.Optional) { yield return new ZenjectResolveException( "Could not find required dependency with type '{0}'{1} \nObject graph:\n{2}" .Fmt( context.MemberType.Name(), (context.ObjectType == null ? "" : " when injecting into '{0}'".Fmt(context.ObjectType.Name())), context.GetObjectGraphString())); } } } } public IEnumerable<ZenjectResolveException> ValidateObjectGraph<TConcrete>(params Type[] extras) { return ValidateObjectGraph(typeof(TConcrete), extras); } public IEnumerable<ZenjectResolveException> ValidateObjectGraph<TConcrete>(InjectContext context, params Type[] extras) { return ValidateObjectGraph(typeof(TConcrete), context, extras); } public IEnumerable<ZenjectResolveException> ValidateObjectGraph( Type contractType, params Type[] extras) { return ValidateObjectGraph( contractType, new InjectContext(this, contractType), extras); } public IEnumerable<ZenjectResolveException> ValidateObjectGraph( Type contractType, InjectContext context, params Type[] extras) { return ValidateObjectGraph( contractType, context, null, extras); } public IEnumerable<ZenjectResolveException> ValidateObjectGraph( Type concreteType, InjectContext currentContext, string concreteIdentifier, params Type[] extras) { if (concreteType.IsAbstract) { throw new ZenjectResolveException( "Expected contract type '{0}' to be non-abstract".Fmt(concreteType.Name())); } var typeInfo = TypeAnalyzer.GetInfo(concreteType); var extrasList = extras.ToList(); foreach (var dependInfo in typeInfo.AllInjectables) { Assert.IsEqual(dependInfo.ObjectType, concreteType); if (TryTakingFromExtras(dependInfo.MemberType, extrasList)) { continue; } var context = dependInfo.CreateInjectContext(this, currentContext, null, concreteIdentifier); foreach (var error in ValidateResolve(context)) { yield return error; } } if (!extrasList.IsEmpty()) { yield return new ZenjectResolveException( "Found unnecessary extra parameters passed when injecting into '{0}' with types '{1}'. \nObject graph:\n{2}" .Fmt(concreteType.Name(), String.Join(",", extrasList.Select(x => x.Name()).ToArray()), currentContext.GetObjectGraphString())); } } bool TryTakingFromExtras(Type contractType, List<Type> extrasList) { foreach (var extraType in extrasList) { if (extraType.DerivesFromOrEqual(contractType)) { var removed = extrasList.Remove(extraType); Assert.That(removed); return true; } } return false; } ////////////// Types //////////////// class ProviderPair { public readonly ProviderBase Provider; public readonly DiContainer Container; public ProviderPair( ProviderBase provider, DiContainer container) { Provider = provider; Container = container; } } public enum ProviderLookupResult { Success, Multiple, None } struct LookupId { public readonly ProviderBase Provider; public readonly BindingId BindingId; public LookupId( ProviderBase provider, BindingId bindingId) { Provider = provider; BindingId = bindingId; } } } }
// 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 Test.Cryptography; using Xunit; namespace System.Security.Cryptography.DeriveBytesTests { public class PasswordDeriveBytesTests { // Note some tests were copied from Rfc2898DeriveBytes (and modified accordingly). private static readonly byte[] s_testSalt = new byte[] { 9, 5, 5, 5, 1, 2, 1, 2 }; private static readonly byte[] s_testSaltB = new byte[] { 0, 4, 0, 4, 1, 9, 7, 5 }; private const string TestPassword = "PasswordGoesHere"; private const string TestPasswordB = "FakePasswordsAreHard"; private const int DefaultIterationCount = 100; [Fact] public static void Ctor_NullPasswordBytes() { using (var pdb = new PasswordDeriveBytes((byte[])null, s_testSalt)) { Assert.Equal(DefaultIterationCount, pdb.IterationCount); Assert.Equal(s_testSalt, pdb.Salt); Assert.Equal("SHA1", pdb.HashName); } } [Fact] public static void Ctor_NullPasswordString() { Assert.Throws<ArgumentNullException>(() => new PasswordDeriveBytes((string)null, s_testSalt)); } [Fact] public static void Ctor_NullSalt() { using (var pdb = new PasswordDeriveBytes(TestPassword, null)) { Assert.Equal(DefaultIterationCount, pdb.IterationCount); Assert.Null(pdb.Salt); Assert.Equal("SHA1", pdb.HashName); } } [Fact] public static void Ctor_EmptySalt() { using (var pdb = new PasswordDeriveBytes(TestPassword, Array.Empty<byte>())) { Assert.Equal(DefaultIterationCount, pdb.IterationCount); Assert.Equal(Array.Empty<byte>(), pdb.Salt); Assert.Equal("SHA1", pdb.HashName); } } [Fact] public static void Ctor_DiminishedSalt() { using (var pdb = new PasswordDeriveBytes(TestPassword, new byte[7])) { Assert.Equal(DefaultIterationCount, pdb.IterationCount); Assert.Equal(7, pdb.Salt.Length); Assert.Equal("SHA1", pdb.HashName); } } [Fact] public static void Ctor_TooFewIterations() { Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 0)); } [Fact] public static void Ctor_NegativeIterations() { Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", int.MinValue / 2)); } [Fact] public static void Ctor_DefaultIterations() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { Assert.Equal(DefaultIterationCount, deriveBytes.IterationCount); } } [Fact] public static void Ctor_IterationsRespected() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 1)) { Assert.Equal(1, deriveBytes.IterationCount); } } [Fact] public static void Ctor_CspParameters() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, new CspParameters())) { } using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, new CspParameters())) { } using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 100, new CspParameters())) { } using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, "SHA1", 100, new CspParameters())) { } } [Fact] public static void Ctor_CspParameters_Null() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, null)) { } using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, null)) { } using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 100, null)) { } using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, "SHA1", 100, null)) { } } [Fact] public static void Ctor_SaltCopied() { byte[] saltIn = (byte[])s_testSalt.Clone(); using (var deriveBytes = new PasswordDeriveBytes(TestPassword, saltIn, "SHA1", DefaultIterationCount)) { byte[] saltOut = deriveBytes.Salt; Assert.NotSame(saltIn, saltOut); Assert.Equal(saltIn, saltOut); // Right now we know that at least one of the constructor and get_Salt made a copy, if it was // only get_Salt then this next part would fail. saltIn[0] = unchecked((byte)~saltIn[0]); // Have to read the property again to prove it's detached. Assert.NotEqual(saltIn, deriveBytes.Salt); } } [Fact] public static void GetSaltCopies() { byte[] first; byte[] second; using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", DefaultIterationCount)) { first = deriveBytes.Salt; second = deriveBytes.Salt; } Assert.NotSame(first, second); Assert.Equal(first, second); } [Fact] public static void SetSaltAfterGetBytes_Throws() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { deriveBytes.GetBytes(1); Assert.Throws<CryptographicException>(() => deriveBytes.Salt = s_testSalt); } } [Fact] public static void SetSaltAfterGetBytes_Reset() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { deriveBytes.GetBytes(1); deriveBytes.Reset(); deriveBytes.Salt = s_testSaltB; Assert.Equal(s_testSaltB, deriveBytes.Salt); } } [Fact] public static void MinimumAcceptableInputs() { byte[] output; using (var deriveBytes = new PasswordDeriveBytes(string.Empty, new byte[8], "SHA1", 1)) { output = deriveBytes.GetBytes(1); } Assert.Equal(1, output.Length); Assert.Equal(0xF8, output[0]); } [Fact] public static void GetBytes_ZeroLength() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { AssertExtensions.Throws<ArgumentException>("", () => deriveBytes.GetBytes(0)); } } [Fact] public static void GetBytes_NegativeLength() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(-1)); Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(int.MinValue)); Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(int.MinValue / 2)); } } [Fact] public static void GetBytes_NotIdempotent() { byte[] first; byte[] second; using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { first = deriveBytes.GetBytes(32); second = deriveBytes.GetBytes(32); } Assert.NotEqual(first, second); } [Fact] public static void GetBytes_StableIfReset() { byte[] first; byte[] second; using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { first = deriveBytes.GetBytes(32); deriveBytes.Reset(); second = deriveBytes.GetBytes(32); } Assert.Equal(first, second); } [Fact] public static void GetBytes_StreamLike_ExtraBytes() { byte[] first; using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { // SHA1 default Assert.Equal("SHA1", deriveBytes.HashName); // Request double of SHA1 hash size first = deriveBytes.GetBytes(40); } byte[] second = new byte[first.Length]; // Reset using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { // Make two passes over the hash byte[] secondFirstHalf = deriveBytes.GetBytes(first.Length / 2); // Since we requested 20 bytes there are no 'extra' bytes left over to cause the "_extraCount" bug // in GetBytes(); that issue is tested in GetBytes_StreamLike_Bug_Compat. // Request 20 'extra' bytes in one call byte[] secondSecondHalf = deriveBytes.GetBytes(first.Length - secondFirstHalf.Length); Buffer.BlockCopy(secondFirstHalf, 0, second, 0, secondFirstHalf.Length); Buffer.BlockCopy(secondSecondHalf, 0, second, secondFirstHalf.Length, secondSecondHalf.Length); } Assert.Equal(first, second); } [Fact] public static void GetBytes_StreamLike_Bug_Compat() { byte[] first; using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { Assert.Equal("SHA1", deriveBytes.HashName); // Request 20 bytes (SHA1 hash size) plus 12 extra bytes first = deriveBytes.GetBytes(32); } byte[] second = new byte[first.Length]; // Reset using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { // Ask for half now (16 bytes) byte[] firstHalf = deriveBytes.GetBytes(first.Length / 2); // Ask for the other half now (16 bytes) byte[] lastHalf = deriveBytes.GetBytes(first.Length - firstHalf.Length); // lastHalf should contain the last 4 bytes from the SHA1 hash plus 12 extra bytes // but due to the _extraCount bug it doesn't. // Merge the two buffers into the second array Buffer.BlockCopy(firstHalf, 0, second, 0, firstHalf.Length); Buffer.BlockCopy(lastHalf, 0, second, firstHalf.Length, lastHalf.Length); } // Fails due to _extraCount bug (the bug is fixed in Rfc2898DeriveBytes) Assert.NotEqual(first, second); // However, the first 16 bytes will be equal because the _extraCount bug does // not affect the first call, only the subsequent GetBytes() call. byte[] first_firstHalf = new byte[first.Length / 2]; byte[] second_firstHalf = new byte[first.Length / 2]; Buffer.BlockCopy(first, 0, first_firstHalf, 0, first_firstHalf.Length); Buffer.BlockCopy(second, 0, second_firstHalf, 0, second_firstHalf.Length); Assert.Equal(first_firstHalf, second_firstHalf); } [Fact] public static void GetBytes_Boundary() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { // Boundary case success deriveBytes.GetBytes(1000 * 20); // Boundary case failure Assert.Throws<CryptographicException>(() => deriveBytes.GetBytes(1)); } } [Fact] public static void GetBytes_KnownValues_MD5_32() { TestKnownValue_GetBytes( HashAlgorithmName.MD5, TestPassword, s_testSalt, DefaultIterationCount, ByteUtils.HexToByteArray("F8D88E9DAFC828DA2400F5144271C2F630A1C061C654FC9DE2E7900E121461B9")); } [Fact] public static void GetBytes_KnownValues_SHA256_40() { TestKnownValue_GetBytes( HashAlgorithmName.SHA256, TestPassword, s_testSalt, DefaultIterationCount, ByteUtils.HexToByteArray("3774A17468276057717A90C25B72915921D8F8C046F7868868DBB99BB4C4031CADE9E26BE77BEA39")); } [Fact] public static void GetBytes_KnownValues_SHA1_40() { TestKnownValue_GetBytes( HashAlgorithmName.SHA1, TestPassword, s_testSalt, DefaultIterationCount, ByteUtils.HexToByteArray("12F2497EC3EB78B0EA32AABFD8B9515FBC800BEEB6316A4DDF4EA62518341488A116DA3BBC26C685")); } [Fact] public static void GetBytes_KnownValues_SHA1_40_2() { TestKnownValue_GetBytes( HashAlgorithmName.SHA1, TestPassword, s_testSalt, DefaultIterationCount + 1, ByteUtils.HexToByteArray("FB6199E4D9BB017D2F3AF6964F3299971607C6B984934A9E43140631957429160C33A6630EF12E31")); } [Fact] public static void GetBytes_KnownValues_SHA1_40_3() { TestKnownValue_GetBytes( HashAlgorithmName.SHA1, TestPassword, s_testSaltB, DefaultIterationCount, ByteUtils.HexToByteArray("DCA4851AB3C9960CF387E64DE7A1B2E09616BEA6A4666AAFAC31F1670F23530E38BD4BF4D9248A08")); } [Fact] public static void GetBytes_KnownValues_SHA1_40_4() { TestKnownValue_GetBytes( HashAlgorithmName.SHA1, TestPasswordB, s_testSalt, DefaultIterationCount, ByteUtils.HexToByteArray("1DCA2A3405E93D9E3F7CD10653444F2FD93F5BE32C4B1BEDDF94D0D67461CBE86B5BDFEB32071E96")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix public static void CryptDeriveKey_KnownValues_TripleDes() { byte[] key = TestKnownValue_CryptDeriveKey( HashAlgorithmName.SHA1, TestPassword, "TripleDES", 192, s_testSalt, ByteUtils.HexToByteArray("97628A641949D99DCED35DB0ABCE20F21FF4DA9B46E00BCE")); // Verify key is valid using (var alg = new TripleDESCryptoServiceProvider()) { alg.Key = key; alg.IV = new byte[8]; alg.Padding = PaddingMode.None; alg.Mode = CipherMode.CBC; byte[] plainText = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray(); byte[] cipher = alg.Encrypt(plainText); byte[] expectedCipher = "9DC863445642B88AC46B3B107CB5A0ACC1596A176962EE8F".HexToByteArray(); Assert.Equal<byte>(expectedCipher, cipher); byte[] decrypted = alg.Decrypt(cipher); byte[] expectedDecrypted = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray(); Assert.Equal<byte>(expectedDecrypted, decrypted); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix public static void CryptDeriveKey_KnownValues_RC2() { TestKnownValue_CryptDeriveKey( HashAlgorithmName.SHA1, TestPassword, "RC2", 128, s_testSalt, ByteUtils.HexToByteArray("B0695D8D98F5844B9650A9F68EFF105B")); TestKnownValue_CryptDeriveKey( HashAlgorithmName.SHA256, TestPassword, "RC2", 128, s_testSalt, ByteUtils.HexToByteArray("CF4A1CA60093E71D6B740DBB962B3C66")); TestKnownValue_CryptDeriveKey( HashAlgorithmName.MD5, TestPassword, "RC2", 128, s_testSalt, ByteUtils.HexToByteArray("84F4B6854CDF896A86FB493B852B6E1F")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix public static void CryptDeriveKey_KnownValues_RC2_NoSalt() { TestKnownValue_CryptDeriveKey( HashAlgorithmName.SHA1, TestPassword, "RC2", 128, null, // Salt is not used here so we should get same key value ByteUtils.HexToByteArray("B0695D8D98F5844B9650A9F68EFF105B")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix public static void CryptDeriveKey_KnownValues_DES() { TestKnownValue_CryptDeriveKey( HashAlgorithmName.SHA1, TestPassword, "DES", 64, s_testSalt, ByteUtils.HexToByteArray("B0685D8C98F4854A")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix public static void CryptDeriveKey_Invalid_KeyLength() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 127, s_testSalt)); Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 129, s_testSalt)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix public static void CryptDeriveKey_Invalid_Algorithm() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("BADALG", "SHA1", 128, s_testSalt)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix public static void CryptDeriveKey_Invalid_HashAlgorithm() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "BADALG", 128, s_testSalt)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix public static void CryptDeriveKey_Invalid_IV() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, null)); Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, new byte[1])); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public static void CryptDeriveKey_Throws_Unix() { using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt)) { Assert.Throws<PlatformNotSupportedException>(() => (deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, null))); } } private static byte[] TestKnownValue_CryptDeriveKey(HashAlgorithmName hashName, string password, string alg, int keySize, byte[] salt, byte[] expected) { byte[] output; byte[] iv = new byte[8]; using (var deriveBytes = new PasswordDeriveBytes(password, salt)) { output = deriveBytes.CryptDeriveKey(alg, hashName.Name, keySize, iv); } Assert.Equal(expected, output); // For these tests, the returned IV is always zero Assert.Equal(new byte[8], iv); return output; } private static void TestKnownValue_GetBytes(HashAlgorithmName hashName, string password, byte[] salt, int iterationCount, byte[] expected) { byte[] output; using (var deriveBytes = new PasswordDeriveBytes(password, salt, hashName.Name, iterationCount)) { output = deriveBytes.GetBytes(expected.Length); } Assert.Equal(expected, output); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //------------------------------------------------------------------------------ // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. //------------------------------------------------------------------------------ // To get up to date fundamental definition files for your hedgefund contact [email protected] using System; using System.IO; using Newtonsoft.Json; namespace QuantConnect.Data.Fundamental { /// <summary> /// Definition of the ValuationRatios class /// </summary> public class ValuationRatios : BaseData { /// <summary> /// Dividend per share / Diluted earnings per share /// </summary> /// <remarks> /// Morningstar DataId: 14000 /// </remarks> [JsonProperty("14000")] public decimal PayoutRatio { get; set; } /// <summary> /// ROE * (1 - Payout Ratio) /// </summary> /// <remarks> /// Morningstar DataId: 14001 /// </remarks> [JsonProperty("14001")] public decimal SustainableGrowthRate { get; set; } /// <summary> /// Refers to the ratio of free cash flow to enterprise value. Morningstar calculates the ratio by using the underlying data reported in /// the company filings or reports: FCF /Enterprise Value. /// </summary> /// <remarks> /// Morningstar DataId: 14002 /// </remarks> [JsonProperty("14002")] public decimal CashReturn { get; set; } /// <summary> /// Sales / Average Diluted Shares Outstanding /// </summary> /// <remarks> /// Morningstar DataId: 14003 /// </remarks> [JsonProperty("14003")] public decimal SalesPerShare { get; set; } /// <summary> /// Common Shareholder's Equity / Diluted Shares Outstanding /// </summary> /// <remarks> /// Morningstar DataId: 14004 /// </remarks> [JsonProperty("14004")] public decimal BookValuePerShare { get; set; } /// <summary> /// Cash Flow from Operations / Average Diluted Shares Outstanding /// </summary> /// <remarks> /// Morningstar DataId: 14005 /// </remarks> [JsonProperty("14005")] public decimal CFOPerShare { get; set; } /// <summary> /// Free Cash Flow / Average Diluted Shares Outstanding /// </summary> /// <remarks> /// Morningstar DataId: 14006 /// </remarks> [JsonProperty("14006")] public decimal FCFPerShare { get; set; } /// <summary> /// Diluted EPS / Price /// </summary> /// <remarks> /// Morningstar DataId: 14007 /// </remarks> [JsonProperty("14007")] public decimal EarningYield { get; set; } /// <summary> /// Adjusted Close Price/ EPS. If the result is negative, zero, &gt;10,000 or &lt;0.001, then null. /// </summary> /// <remarks> /// Morningstar DataId: 14008 /// </remarks> [JsonProperty("14008")] public decimal PERatio { get; set; } /// <summary> /// SalesPerShare / Price /// </summary> /// <remarks> /// Morningstar DataId: 14009 /// </remarks> [JsonProperty("14009")] public decimal SalesYield { get; set; } /// <summary> /// Adjusted close price / Sales Per Share. If the result is negative or zero, then null. /// </summary> /// <remarks> /// Morningstar DataId: 14010 /// </remarks> [JsonProperty("14010")] public decimal PSRatio { get; set; } /// <summary> /// BookValuePerShare / Price /// </summary> /// <remarks> /// Morningstar DataId: 14011 /// </remarks> [JsonProperty("14011")] public decimal BookValueYield { get; set; } /// <summary> /// Adjusted close price / Book Value Per Share. If the result is negative or zero, then null. /// </summary> /// <remarks> /// Morningstar DataId: 14012 /// </remarks> [JsonProperty("14012")] public decimal PBRatio { get; set; } /// <summary> /// CFOPerShare / Price /// </summary> /// <remarks> /// Morningstar DataId: 14013 /// </remarks> [JsonProperty("14013")] public decimal CFYield { get; set; } /// <summary> /// Adjusted close price /Cash Flow Per Share. If the result is negative or zero, then null. /// </summary> /// <remarks> /// Morningstar DataId: 14014 /// </remarks> [JsonProperty("14014")] public decimal PCFRatio { get; set; } /// <summary> /// FCFPerShare / Price /// </summary> /// <remarks> /// Morningstar DataId: 14015 /// </remarks> [JsonProperty("14015")] public decimal FCFYield { get; set; } /// <summary> /// Adjusted close price/ Free Cash Flow Per Share. If the result is negative or zero, then null. /// </summary> /// <remarks> /// Morningstar DataId: 14016 /// </remarks> [JsonProperty("14016")] public decimal FCFRatio { get; set; } /// <summary> /// Dividends Per Share over the trailing 12 months / Price /// </summary> /// <remarks> /// Morningstar DataId: 14017 /// </remarks> [JsonProperty("14017")] public decimal TrailingDividendYield { get; set; } /// <summary> /// (Current Dividend Per Share * Payout Frequency) / Price /// </summary> /// <remarks> /// Morningstar DataId: 14018 /// </remarks> [JsonProperty("14018")] public decimal ForwardDividendYield { get; set; } /// <summary> /// Estimated Earnings Per Share / Price /// Note: /// a) The "Next" Year's EPS Estimate is used; For instance, if today's actual date is March 1, 2009, the "Current" EPS Estimate for /// MSFT is June 2009, and the "Next" EPS Estimate for MSFT is June 2010; the latter is used. /// b) The eps estimated data is sourced from a third party. /// </summary> /// <remarks> /// Morningstar DataId: 14019 /// </remarks> [JsonProperty("14019")] public decimal ForwardEarningYield { get; set; } /// <summary> /// 1 / ForwardEarningYield /// If result is negative, then null /// </summary> /// <remarks> /// Morningstar DataId: 14020 /// </remarks> [JsonProperty("14020")] public decimal ForwardPERatio { get; set; } /// <summary> /// ForwardPERatio / Long-term Average Earning Growth Rate /// </summary> /// <remarks> /// Morningstar DataId: 14021 /// </remarks> [JsonProperty("14021")] public decimal PEGRatio { get; set; } /// <summary> /// The number of years it would take for a company's cumulative earnings to equal the stock's current trading price, assuming that the /// company continues to increase its annual earnings at the growth rate used to calculate the PEG ratio. /// [ Log (PG/E + 1) / Log (1 + G) ] - 1 /// Where /// P=Price /// E=Next Fiscal Year's Estimated EPS /// G=Long-term Average Earning Growth /// </summary> /// <remarks> /// Morningstar DataId: 14022 /// </remarks> [JsonProperty("14022")] public decimal PEGPayback { get; set; } /// <summary> /// The company's total book value less the value of any intangible assets dividend by number of shares. /// </summary> /// <remarks> /// Morningstar DataId: 14023 /// </remarks> [JsonProperty("14023")] public decimal TangibleBookValuePerShare { get; set; } /// <summary> /// The three year average for tangible book value per share. /// </summary> /// <remarks> /// Morningstar DataId: 14024 /// </remarks> [JsonProperty("14024")] public decimal TangibleBVPerShare3YrAvg { get; set; } /// <summary> /// The five year average for tangible book value per share. /// </summary> /// <remarks> /// Morningstar DataId: 14025 /// </remarks> [JsonProperty("14025")] public decimal TangibleBVPerShare5YrAvg { get; set; } /// <summary> /// Latest Dividend * Frequency /// </summary> /// <remarks> /// Morningstar DataId: 14026 /// </remarks> [JsonProperty("14026")] public decimal ForwardDividend { get; set; } /// <summary> /// (Current Assets - Current Liabilities)/number of shares /// </summary> /// <remarks> /// Morningstar DataId: 14027 /// </remarks> [JsonProperty("14027")] public decimal WorkingCapitalPerShare { get; set; } /// <summary> /// The three year average for working capital per share. /// </summary> /// <remarks> /// Morningstar DataId: 14028 /// </remarks> [JsonProperty("14028")] public decimal WorkingCapitalPerShare3YrAvg { get; set; } /// <summary> /// The five year average for working capital per share. /// </summary> /// <remarks> /// Morningstar DataId: 14029 /// </remarks> [JsonProperty("14029")] public decimal WorkingCapitalPerShare5YrAvg { get; set; } /// <summary> /// This reflects the fair market value of a company, and allows comparability to other companies as this is capital structure-neutral. /// </summary> /// <remarks> /// Morningstar DataId: 14030 /// </remarks> [JsonProperty("14030")] public decimal EVToEBITDA { get; set; } /// <summary> /// The net repurchase of shares outstanding over the market capital of the company. It is a measure of shareholder return. /// </summary> /// <remarks> /// Morningstar DataId: 14031 /// </remarks> [JsonProperty("14031")] public decimal BuyBackYield { get; set; } /// <summary> /// The total yield that shareholders can expect, by summing Dividend Yield and Buyback Yield. /// </summary> /// <remarks> /// Morningstar DataId: 14032 /// </remarks> [JsonProperty("14032")] public decimal TotalYield { get; set; } /// <summary> /// The five-year average of the company's price-to-earnings ratio. /// </summary> /// <remarks> /// Morningstar DataId: 14033 /// </remarks> [JsonProperty("14033")] public decimal RatioPE5YearAverage { get; set; } /// <summary> /// Price change this month, expressed as latest price/last month end price. /// </summary> /// <remarks> /// Morningstar DataId: 14034 /// </remarks> [JsonProperty("14034")] public decimal PriceChange1M { get; set; } /// <summary> /// Adjusted Close Price/ Normalized EPS. Normalized EPS removes onetime and unusual items from net EPS, to provide investors with /// a more accurate measure of the company's true earnings. If the result is negative, zero, &gt;10,000 or &lt;0.001, then null. /// </summary> /// <remarks> /// Morningstar DataId: 14035 /// </remarks> [JsonProperty("14035")] public decimal NormalizedPERatio { get; set; } /// <summary> /// Adjusted close price/EBITDA Per Share. If the result is negative or zero, then null. /// </summary> /// <remarks> /// Morningstar DataId: 14036 /// </remarks> [JsonProperty("14036")] public decimal PricetoEBITDA { get; set; } /// <summary> /// Average of the last 60 monthly observations of trailing dividend yield in the last 5 years. /// </summary> /// <remarks> /// Morningstar DataId: 14037 /// </remarks> [JsonProperty("14037")] public decimal DivYield5Year { get; set; } /// <summary> /// Indicates the method used to calculate Forward Dividend. There are three options: Annual, Look-back and Manual. /// </summary> /// <remarks> /// Morningstar DataId: 14042 /// </remarks> [JsonProperty("14042")] public string ForwardCalculationStyle { get; set; } /// <summary> /// Used to collect the forward dividend for companies where our formula will not produce the correct value. /// </summary> /// <remarks> /// Morningstar DataId: 14043 /// </remarks> [JsonProperty("14043")] public decimal ActualForwardDividend { get; set; } /// <summary> /// Indicates the method used to calculate Trailing Dividend. There are two options: Look-back and Manual. /// </summary> /// <remarks> /// Morningstar DataId: 14044 /// </remarks> [JsonProperty("14044")] public string TrailingCalculationStyle { get; set; } /// <summary> /// Used to collect the trailing dividend for companies where our formula will not produce the correct value. /// </summary> /// <remarks> /// Morningstar DataId: 14045 /// </remarks> [JsonProperty("14045")] public decimal ActualTrailingDividend { get; set; } /// <summary> /// The growth rate from the TrailingDividend to the Forward Dividend: {(Forward Dividend/Trailing Dividend) - 1}*100. /// </summary> /// <remarks> /// Morningstar DataId: 14047 /// </remarks> [JsonProperty("14047")] public decimal ExpectedDividendGrowthRate { get; set; } /// <summary> /// Creates an instance of the ValuationRatios class /// </summary> public ValuationRatios() { } /// <summary> /// Sets values for non existing periods from a previous instance /// </summary> /// <remarks>Used to fill-forward values from previous dates</remarks> /// <param name="previous">The previous instance</param> public void UpdateValues(ValuationRatios previous) { } } }
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 Tracy.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using MS.Utility; using System; using System.IO; using System.Windows; using System.Windows.Media; using MS.Internal; using MS.Internal.Ink; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Ink { ///<summary> /// Defines the style of pen tip for rendering. ///</summary> /// <remarks> /// The Stylus size and coordinates are in units equal to 1/96th of an inch. /// The default in V1 the default width is 1 pixel. This is 53 himetric units. /// There are 2540 himetric units per inch. /// This means that 53 high metric units is equivalent to 53/2540*96 in avalon. /// </remarks> public abstract class StylusShape { #region Fields private double m_width; private double m_height; private double m_rotation; private Point[] m_vertices; private StylusTip m_tip; private Matrix _transform = Matrix.Identity; #endregion #region Constructors internal StylusShape(){} ///<summary> /// constructor for a StylusShape. ///</summary> internal StylusShape(StylusTip tip, double width, double height, double rotation) { if (Double.IsNaN(width) || Double.IsInfinity(width) || width < DrawingAttributes.MinWidth || width > DrawingAttributes.MaxWidth) { throw new ArgumentOutOfRangeException("width"); } if (Double.IsNaN(height) || Double.IsInfinity(height) || height < DrawingAttributes.MinHeight || height > DrawingAttributes.MaxHeight) { throw new ArgumentOutOfRangeException("height"); } if (Double.IsNaN(rotation) || Double.IsInfinity(rotation)) { throw new ArgumentOutOfRangeException("rotation"); } if (!StylusTipHelper.IsDefined(tip)) { throw new ArgumentOutOfRangeException("tip"); } // // mod rotation to 360 (720 to 0, 361 to 1, -270 to 90) // m_width = width; m_height = height; m_rotation = rotation == 0 ? 0 : rotation % 360; m_tip = tip; if (tip == StylusTip.Rectangle) { ComputeRectangleVertices(); } } #endregion #region Public properties ///<summary> /// Width of the non-rotated shape. ///</summary> public double Width { get { return m_width; } } ///<summary> /// Height of the non-rotated shape. ///</summary> public double Height { get { return m_height; } } ///<summary> /// The shape's rotation angle. The rotation is done about the origin (0,0). ///</summary> public double Rotation { get { return m_rotation; } } /// <summary> /// GetVerticesAsVectors /// </summary> /// <returns></returns> internal Vector[] GetVerticesAsVectors() { Vector[] vertices; if (null != m_vertices) { // For a Rectangle vertices = new Vector[m_vertices.Length]; if (_transform.IsIdentity) { for (int i = 0; i < vertices.Length; i++) { vertices[i] = (Vector)m_vertices[i]; } } else { for (int i = 0; i < vertices.Length; i++) { vertices[i] = _transform.Transform((Vector)m_vertices[i]); } // A transform might make the vertices in counter-clockwise order // Fix it if this is the case. FixCounterClockwiseVertices(vertices); } } else { // For ellipse // The transform is already applied on these points. Point[] p = GetBezierControlPoints(); vertices = new Vector[p.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = (Vector)p[i]; } } return vertices; } #endregion #region Misc. internal API /// <summary> /// This is the transform on the StylusShape /// </summary> internal Matrix Transform { get { return _transform; } set { System.Diagnostics.Debug.Assert(value.HasInverse); _transform = value; } } ///<summary> /// A helper property. ///</summary> internal bool IsEllipse { get { return (null == m_vertices); } } ///<summary> /// A helper property. ///</summary> internal bool IsPolygon { get { return (null != m_vertices); } } /// <summary> /// Generally, there's no need for the shape's bounding box. /// We use it to approximate v2 shapes with a rectangle for v1. /// </summary> internal Rect BoundingBox { get { Rect bbox; if (this.IsPolygon) { bbox = Rect.Empty; foreach (Point vertex in m_vertices) { bbox.Union(vertex); } } // Future enhancement: Implement bbox for rotated ellipses. else //if (DoubleUtil.IsZero(m_rotation) || DoubleUtil.AreClose(m_width, m_height)) { bbox = new Rect(-(m_width * 0.5), -(m_height * 0.5), m_width, m_height); } //else //{ // throw new NotImplementedException("Rotated ellipse"); //} return bbox; } } #endregion #region Implementation helpers /// <summary>TBS</summary> private void ComputeRectangleVertices() { Point topLeft = new Point(-(m_width * 0.5), -(m_height * 0.5)); m_vertices = new Point[4] { topLeft, topLeft + new Vector(m_width, 0), topLeft + new Vector(m_width, m_height), topLeft + new Vector(0, m_height)}; if (false == DoubleUtil.IsZero(m_rotation)) { Matrix rotationTransform = Matrix.Identity; rotationTransform.Rotate(m_rotation); rotationTransform.Transform(m_vertices); } } /// <summary> A transform might make the vertices in counter-clockwise order Fix it if this is the case.</summary> private void FixCounterClockwiseVertices(Vector[] vertices) { // The private method should only called for Rectangle case. System.Diagnostics.Debug.Assert(vertices.Length == 4); Point prevVertex = (Point)vertices[vertices.Length - 1]; int counterClockIndex = 0, clockWiseIndex = 0; for (int i = 0; i < vertices.Length; i++) { Point vertex = (Point) vertices[i]; Vector edge = vertex - prevVertex; // Verify that the next vertex is on the right side off the edge vector. double det = Vector.Determinant(edge, (Point)vertices[(i + 1) % vertices.Length] - (Point)vertex); if (0 > det) { counterClockIndex++; } else if (0 < det) { clockWiseIndex++; } prevVertex = vertex; } // Assert the transform will make it either clockwise or counter-clockwise. System.Diagnostics.Debug.Assert(clockWiseIndex == vertices.Length || counterClockIndex == vertices.Length); if (counterClockIndex == vertices.Length) { // Make it Clockwise int lastIndex = vertices.Length -1; for (int j = 0; j < vertices.Length/2; j++) { Vector tmp = vertices[j]; vertices[j] = vertices[lastIndex - j]; vertices[lastIndex-j] = tmp; } } } private Point[] GetBezierControlPoints() { System.Diagnostics.Debug.Assert(m_tip == StylusTip.Ellipse); // Approximating a 1/4 circle with a Bezier curve (borrowed from Avalon's EllipseGeometry.cs) const double ArcAsBezier = 0.5522847498307933984; // =(\/2 - 1)*4/3 double radiusX = m_width / 2; double radiusY = m_height / 2; double borderMagicX = radiusX * ArcAsBezier; double borderMagicY = radiusY * ArcAsBezier; Point[] controlPoints = new Point[] { new Point( -radiusX, -borderMagicY), new Point(-borderMagicX, -radiusY), new Point( 0, -radiusY), new Point( borderMagicX, -radiusY), new Point( radiusX, -borderMagicY), new Point( radiusX, 0), new Point( radiusX, borderMagicY), new Point( borderMagicX, radiusY), new Point( 0, radiusY), new Point(-borderMagicX, radiusY), new Point( -radiusX, borderMagicY), new Point( -radiusX, 0)}; // Future enhancement: Apply the transform to the vertices // Apply rotation and the shape transform to the control points Matrix transform = Matrix.Identity; if (m_rotation != 0) { transform.Rotate(m_rotation); } if (_transform.IsIdentity == false) { transform *= _transform; } if (transform.IsIdentity == false) { for (int i = 0; i < controlPoints.Length; i++) { controlPoints[i] = transform.Transform(controlPoints[i]); } } return controlPoints; } #endregion } /// <summary> /// Class for an elliptical StylusShape /// </summary> public sealed class EllipseStylusShape : StylusShape { /// <summary> /// Constructor for an elliptical StylusShape /// </summary> /// <param name="width"></param> /// <param name="height"></param> public EllipseStylusShape(double width, double height) :this(width, height, 0f) { } /// <summary> /// Constructor for an ellptical StylusShape ,with roation in degree /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="rotation"></param> public EllipseStylusShape(double width, double height, double rotation) : base(StylusTip.Ellipse, width, height, rotation) { } } /// <summary> /// Class for a rectangle StylusShape /// </summary> public sealed class RectangleStylusShape : StylusShape { /// <summary> /// Constructor /// </summary> /// <param name="width"></param> /// <param name="height"></param> public RectangleStylusShape(double width, double height) : this(width, height, 0f) { } /// <summary> /// Constructor with rogation in degree /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="rotation"></param> public RectangleStylusShape(double width, double height, double rotation) : base(StylusTip.Rectangle, width, height, rotation) { } } }
// 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! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedTransitionRouteGroupsClientSnippets { /// <summary>Snippet for ListTransitionRouteGroups</summary> public void ListTransitionRouteGroupsRequestObject() { // Snippet: ListTransitionRouteGroups(ListTransitionRouteGroupsRequest, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) ListTransitionRouteGroupsRequest request = new ListTransitionRouteGroupsRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "", }; // Make the request PagedEnumerable<ListTransitionRouteGroupsResponse, TransitionRouteGroup> response = transitionRouteGroupsClient.ListTransitionRouteGroups(request); // Iterate over all response items, lazily performing RPCs as required foreach (TransitionRouteGroup item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTransitionRouteGroupsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TransitionRouteGroup item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TransitionRouteGroup> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TransitionRouteGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTransitionRouteGroupsAsync</summary> public async Task ListTransitionRouteGroupsRequestObjectAsync() { // Snippet: ListTransitionRouteGroupsAsync(ListTransitionRouteGroupsRequest, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) ListTransitionRouteGroupsRequest request = new ListTransitionRouteGroupsRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "", }; // Make the request PagedAsyncEnumerable<ListTransitionRouteGroupsResponse, TransitionRouteGroup> response = transitionRouteGroupsClient.ListTransitionRouteGroupsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TransitionRouteGroup item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListTransitionRouteGroupsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TransitionRouteGroup item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TransitionRouteGroup> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TransitionRouteGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTransitionRouteGroups</summary> public void ListTransitionRouteGroups() { // Snippet: ListTransitionRouteGroups(string, string, int?, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]"; // Make the request PagedEnumerable<ListTransitionRouteGroupsResponse, TransitionRouteGroup> response = transitionRouteGroupsClient.ListTransitionRouteGroups(parent); // Iterate over all response items, lazily performing RPCs as required foreach (TransitionRouteGroup item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTransitionRouteGroupsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TransitionRouteGroup item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TransitionRouteGroup> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TransitionRouteGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTransitionRouteGroupsAsync</summary> public async Task ListTransitionRouteGroupsAsync() { // Snippet: ListTransitionRouteGroupsAsync(string, string, int?, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]"; // Make the request PagedAsyncEnumerable<ListTransitionRouteGroupsResponse, TransitionRouteGroup> response = transitionRouteGroupsClient.ListTransitionRouteGroupsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TransitionRouteGroup item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListTransitionRouteGroupsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TransitionRouteGroup item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TransitionRouteGroup> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TransitionRouteGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTransitionRouteGroups</summary> public void ListTransitionRouteGroupsResourceNames() { // Snippet: ListTransitionRouteGroups(FlowName, string, int?, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) FlowName parent = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"); // Make the request PagedEnumerable<ListTransitionRouteGroupsResponse, TransitionRouteGroup> response = transitionRouteGroupsClient.ListTransitionRouteGroups(parent); // Iterate over all response items, lazily performing RPCs as required foreach (TransitionRouteGroup item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTransitionRouteGroupsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TransitionRouteGroup item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TransitionRouteGroup> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TransitionRouteGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTransitionRouteGroupsAsync</summary> public async Task ListTransitionRouteGroupsResourceNamesAsync() { // Snippet: ListTransitionRouteGroupsAsync(FlowName, string, int?, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) FlowName parent = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"); // Make the request PagedAsyncEnumerable<ListTransitionRouteGroupsResponse, TransitionRouteGroup> response = transitionRouteGroupsClient.ListTransitionRouteGroupsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TransitionRouteGroup item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListTransitionRouteGroupsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TransitionRouteGroup item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TransitionRouteGroup> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TransitionRouteGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetTransitionRouteGroup</summary> public void GetTransitionRouteGroupRequestObject() { // Snippet: GetTransitionRouteGroup(GetTransitionRouteGroupRequest, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), LanguageCode = "", }; // Make the request TransitionRouteGroup response = transitionRouteGroupsClient.GetTransitionRouteGroup(request); // End snippet } /// <summary>Snippet for GetTransitionRouteGroupAsync</summary> public async Task GetTransitionRouteGroupRequestObjectAsync() { // Snippet: GetTransitionRouteGroupAsync(GetTransitionRouteGroupRequest, CallSettings) // Additional: GetTransitionRouteGroupAsync(GetTransitionRouteGroupRequest, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), LanguageCode = "", }; // Make the request TransitionRouteGroup response = await transitionRouteGroupsClient.GetTransitionRouteGroupAsync(request); // End snippet } /// <summary>Snippet for GetTransitionRouteGroup</summary> public void GetTransitionRouteGroup() { // Snippet: GetTransitionRouteGroup(string, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/transitionRouteGroups/[TRANSITION_ROUTE_GROUP]"; // Make the request TransitionRouteGroup response = transitionRouteGroupsClient.GetTransitionRouteGroup(name); // End snippet } /// <summary>Snippet for GetTransitionRouteGroupAsync</summary> public async Task GetTransitionRouteGroupAsync() { // Snippet: GetTransitionRouteGroupAsync(string, CallSettings) // Additional: GetTransitionRouteGroupAsync(string, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/transitionRouteGroups/[TRANSITION_ROUTE_GROUP]"; // Make the request TransitionRouteGroup response = await transitionRouteGroupsClient.GetTransitionRouteGroupAsync(name); // End snippet } /// <summary>Snippet for GetTransitionRouteGroup</summary> public void GetTransitionRouteGroupResourceNames() { // Snippet: GetTransitionRouteGroup(TransitionRouteGroupName, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) TransitionRouteGroupName name = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"); // Make the request TransitionRouteGroup response = transitionRouteGroupsClient.GetTransitionRouteGroup(name); // End snippet } /// <summary>Snippet for GetTransitionRouteGroupAsync</summary> public async Task GetTransitionRouteGroupResourceNamesAsync() { // Snippet: GetTransitionRouteGroupAsync(TransitionRouteGroupName, CallSettings) // Additional: GetTransitionRouteGroupAsync(TransitionRouteGroupName, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) TransitionRouteGroupName name = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"); // Make the request TransitionRouteGroup response = await transitionRouteGroupsClient.GetTransitionRouteGroupAsync(name); // End snippet } /// <summary>Snippet for CreateTransitionRouteGroup</summary> public void CreateTransitionRouteGroupRequestObject() { // Snippet: CreateTransitionRouteGroup(CreateTransitionRouteGroupRequest, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), LanguageCode = "", }; // Make the request TransitionRouteGroup response = transitionRouteGroupsClient.CreateTransitionRouteGroup(request); // End snippet } /// <summary>Snippet for CreateTransitionRouteGroupAsync</summary> public async Task CreateTransitionRouteGroupRequestObjectAsync() { // Snippet: CreateTransitionRouteGroupAsync(CreateTransitionRouteGroupRequest, CallSettings) // Additional: CreateTransitionRouteGroupAsync(CreateTransitionRouteGroupRequest, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), LanguageCode = "", }; // Make the request TransitionRouteGroup response = await transitionRouteGroupsClient.CreateTransitionRouteGroupAsync(request); // End snippet } /// <summary>Snippet for CreateTransitionRouteGroup</summary> public void CreateTransitionRouteGroup() { // Snippet: CreateTransitionRouteGroup(string, TransitionRouteGroup, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]"; TransitionRouteGroup transitionRouteGroup = new TransitionRouteGroup(); // Make the request TransitionRouteGroup response = transitionRouteGroupsClient.CreateTransitionRouteGroup(parent, transitionRouteGroup); // End snippet } /// <summary>Snippet for CreateTransitionRouteGroupAsync</summary> public async Task CreateTransitionRouteGroupAsync() { // Snippet: CreateTransitionRouteGroupAsync(string, TransitionRouteGroup, CallSettings) // Additional: CreateTransitionRouteGroupAsync(string, TransitionRouteGroup, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]"; TransitionRouteGroup transitionRouteGroup = new TransitionRouteGroup(); // Make the request TransitionRouteGroup response = await transitionRouteGroupsClient.CreateTransitionRouteGroupAsync(parent, transitionRouteGroup); // End snippet } /// <summary>Snippet for CreateTransitionRouteGroup</summary> public void CreateTransitionRouteGroupResourceNames() { // Snippet: CreateTransitionRouteGroup(FlowName, TransitionRouteGroup, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) FlowName parent = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"); TransitionRouteGroup transitionRouteGroup = new TransitionRouteGroup(); // Make the request TransitionRouteGroup response = transitionRouteGroupsClient.CreateTransitionRouteGroup(parent, transitionRouteGroup); // End snippet } /// <summary>Snippet for CreateTransitionRouteGroupAsync</summary> public async Task CreateTransitionRouteGroupResourceNamesAsync() { // Snippet: CreateTransitionRouteGroupAsync(FlowName, TransitionRouteGroup, CallSettings) // Additional: CreateTransitionRouteGroupAsync(FlowName, TransitionRouteGroup, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) FlowName parent = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"); TransitionRouteGroup transitionRouteGroup = new TransitionRouteGroup(); // Make the request TransitionRouteGroup response = await transitionRouteGroupsClient.CreateTransitionRouteGroupAsync(parent, transitionRouteGroup); // End snippet } /// <summary>Snippet for UpdateTransitionRouteGroup</summary> public void UpdateTransitionRouteGroupRequestObject() { // Snippet: UpdateTransitionRouteGroup(UpdateTransitionRouteGroupRequest, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new FieldMask(), LanguageCode = "", }; // Make the request TransitionRouteGroup response = transitionRouteGroupsClient.UpdateTransitionRouteGroup(request); // End snippet } /// <summary>Snippet for UpdateTransitionRouteGroupAsync</summary> public async Task UpdateTransitionRouteGroupRequestObjectAsync() { // Snippet: UpdateTransitionRouteGroupAsync(UpdateTransitionRouteGroupRequest, CallSettings) // Additional: UpdateTransitionRouteGroupAsync(UpdateTransitionRouteGroupRequest, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new FieldMask(), LanguageCode = "", }; // Make the request TransitionRouteGroup response = await transitionRouteGroupsClient.UpdateTransitionRouteGroupAsync(request); // End snippet } /// <summary>Snippet for UpdateTransitionRouteGroup</summary> public void UpdateTransitionRouteGroup() { // Snippet: UpdateTransitionRouteGroup(TransitionRouteGroup, FieldMask, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) TransitionRouteGroup transitionRouteGroup = new TransitionRouteGroup(); FieldMask updateMask = new FieldMask(); // Make the request TransitionRouteGroup response = transitionRouteGroupsClient.UpdateTransitionRouteGroup(transitionRouteGroup, updateMask); // End snippet } /// <summary>Snippet for UpdateTransitionRouteGroupAsync</summary> public async Task UpdateTransitionRouteGroupAsync() { // Snippet: UpdateTransitionRouteGroupAsync(TransitionRouteGroup, FieldMask, CallSettings) // Additional: UpdateTransitionRouteGroupAsync(TransitionRouteGroup, FieldMask, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) TransitionRouteGroup transitionRouteGroup = new TransitionRouteGroup(); FieldMask updateMask = new FieldMask(); // Make the request TransitionRouteGroup response = await transitionRouteGroupsClient.UpdateTransitionRouteGroupAsync(transitionRouteGroup, updateMask); // End snippet } /// <summary>Snippet for DeleteTransitionRouteGroup</summary> public void DeleteTransitionRouteGroupRequestObject() { // Snippet: DeleteTransitionRouteGroup(DeleteTransitionRouteGroupRequest, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), Force = false, }; // Make the request transitionRouteGroupsClient.DeleteTransitionRouteGroup(request); // End snippet } /// <summary>Snippet for DeleteTransitionRouteGroupAsync</summary> public async Task DeleteTransitionRouteGroupRequestObjectAsync() { // Snippet: DeleteTransitionRouteGroupAsync(DeleteTransitionRouteGroupRequest, CallSettings) // Additional: DeleteTransitionRouteGroupAsync(DeleteTransitionRouteGroupRequest, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), Force = false, }; // Make the request await transitionRouteGroupsClient.DeleteTransitionRouteGroupAsync(request); // End snippet } /// <summary>Snippet for DeleteTransitionRouteGroup</summary> public void DeleteTransitionRouteGroup() { // Snippet: DeleteTransitionRouteGroup(string, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/transitionRouteGroups/[TRANSITION_ROUTE_GROUP]"; // Make the request transitionRouteGroupsClient.DeleteTransitionRouteGroup(name); // End snippet } /// <summary>Snippet for DeleteTransitionRouteGroupAsync</summary> public async Task DeleteTransitionRouteGroupAsync() { // Snippet: DeleteTransitionRouteGroupAsync(string, CallSettings) // Additional: DeleteTransitionRouteGroupAsync(string, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/transitionRouteGroups/[TRANSITION_ROUTE_GROUP]"; // Make the request await transitionRouteGroupsClient.DeleteTransitionRouteGroupAsync(name); // End snippet } /// <summary>Snippet for DeleteTransitionRouteGroup</summary> public void DeleteTransitionRouteGroupResourceNames() { // Snippet: DeleteTransitionRouteGroup(TransitionRouteGroupName, CallSettings) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create(); // Initialize request argument(s) TransitionRouteGroupName name = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"); // Make the request transitionRouteGroupsClient.DeleteTransitionRouteGroup(name); // End snippet } /// <summary>Snippet for DeleteTransitionRouteGroupAsync</summary> public async Task DeleteTransitionRouteGroupResourceNamesAsync() { // Snippet: DeleteTransitionRouteGroupAsync(TransitionRouteGroupName, CallSettings) // Additional: DeleteTransitionRouteGroupAsync(TransitionRouteGroupName, CancellationToken) // Create client TransitionRouteGroupsClient transitionRouteGroupsClient = await TransitionRouteGroupsClient.CreateAsync(); // Initialize request argument(s) TransitionRouteGroupName name = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"); // Make the request await transitionRouteGroupsClient.DeleteTransitionRouteGroupAsync(name); // End snippet } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Api.Attributes; using ASC.Api.Collections; using ASC.Api.CRM.Wrappers; using ASC.Api.Exceptions; using ASC.CRM.Core; using ASC.CRM.Core.Entities; using ASC.ElasticSearch; using ASC.MessagingSystem; using ASC.Web.CRM.Classes; using ASC.Web.CRM.Core.Search; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace ASC.Api.CRM { public partial class CRMApi { /// <summary> /// Returns the list of all available contact categories /// </summary> /// <param name="infoType"> /// Contact information type /// </param> /// <short>Get all categories</short> /// <category>Contacts</category> /// <returns> /// List of all available contact categories /// </returns> [Read(@"contact/data/{infoType}/category")] public IEnumerable<string> GetContactInfoCategory(ContactInfoType infoType) { return Enum.GetNames(ContactInfo.GetCategory(infoType)).ToItemList(); } /// <summary> /// Returns the list of all available contact information types /// </summary> /// <short>Get all contact info types</short> /// <category>Contacts</category> /// <returns></returns> [Read(@"contact/data/infoType")] public IEnumerable<string> GetContactInfoType() { return Enum.GetNames(typeof(ContactInfoType)).ToItemList(); } /// <summary> /// Returns the detailed information for the contact /// </summary> /// <param name="contactid">Contact ID</param> /// <short>Get contact information</short> /// <category>Contacts</category> /// <returns> /// Contact information /// </returns> [Read(@"contact/{contactid:[0-9]+}/data")] public IEnumerable<ContactInfoWrapper> GetContactInfo(int contactid) { if (contactid <= 0) throw new ArgumentException(); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null || !CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); return DaoFactory.ContactInfoDao.GetList(contactid, null, null, null) .OrderByDescending(info => info.ID) .ToList() .ConvertAll(ToContactInfoWrapper); } /// <summary> /// Returns the detailed list of all information available for the contact with the ID specified in the request /// </summary> /// <param name="contactid">Contact ID</param> /// <param name="id">Contact information ID</param> /// <short>Get contact info</short> /// <category>Contacts</category> /// <returns>Contact information</returns> ///<exception cref="ArgumentException"></exception> [Read(@"contact/{contactid:[0-9]+}/data/{id:[0-9]+}")] public ContactInfoWrapper GetContactInfoByID(int contactid, int id) { if (contactid <= 0 || id <= 0) throw new ArgumentException(); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null || !CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); var contactInfo = DaoFactory.ContactInfoDao.GetByID(id); if (contactInfo == null || contactInfo.ContactID != contactid) throw new ArgumentException(); return ToContactInfoWrapper(contactInfo); } /// <summary> /// Adds the information with the parameters specified in the request to the contact with the selected ID /// </summary> ///<param name="contactid">Contact ID</param> ///<param name="infoType">Contact information type</param> ///<param name="data">Data</param> ///<param name="isPrimary">Contact importance: primary or not</param> ///<param name="category">Category</param> ///<short> Add contact info</short> ///<category>Contacts</category> /// <seealso cref="GetContactInfoType"/> /// <seealso cref="GetContactInfoCategory"/> /// <returns> /// Contact information /// </returns> ///<exception cref="ArgumentException"></exception> [Create(@"contact/{contactid:[0-9]+}/data")] public ContactInfoWrapper CreateContactInfo(int contactid, ContactInfoType infoType, string data, bool isPrimary, string category) { if (string.IsNullOrEmpty(data) || contactid <= 0) throw new ArgumentException(); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null) throw new ItemNotFoundException(); if (infoType == ContactInfoType.Twitter) { if (!CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); } else { if (!CRMSecurity.CanEdit(contact)) throw new ItemNotFoundException(); } var categoryType = ContactInfo.GetCategory(infoType); if (!Enum.IsDefined(categoryType, category)) throw new ArgumentException(); var contactInfo = new ContactInfo { Data = data, InfoType = infoType, ContactID = contactid, IsPrimary = isPrimary, Category = (int)Enum.Parse(categoryType, category) }; if (contactInfo.InfoType == ContactInfoType.Address) { Address res; if (!Address.TryParse(contactInfo, out res)) throw new ArgumentException(); } var contactInfoID = DaoFactory.ContactInfoDao.Save(contactInfo); var messageAction = contact is Company ? MessageAction.CompanyUpdatedPrincipalInfo : MessageAction.PersonUpdatedPrincipalInfo; MessageService.Send(Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); var contactInfoWrapper = ToContactInfoWrapper(contactInfo); contactInfoWrapper.ID = contactInfoID; return contactInfoWrapper; } /// <summary> /// Adds the address information to the contact with the selected ID /// </summary> /// <param name="contactid">Contact ID</param> /// <param name="address">Address data</param> /// <short>Add address info</short> /// <category>Contacts</category> /// <seealso cref="GetContactInfoType"/> /// <seealso cref="GetContactInfoCategory"/> /// <returns> /// Contact information /// </returns> /// <exception cref="ArgumentException"></exception> /// <exception cref="ItemNotFoundException"></exception> [Create(@"contact/{contactid:[0-9]+}/addressdata")] public ContactInfoWrapper CreateContactInfoAddress(int contactid, Address address) { if (contactid <= 0) throw new ArgumentException("Invalid value", "contactid"); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null || !CRMSecurity.CanEdit(contact)) throw new ItemNotFoundException(); if (address == null) throw new ArgumentException("Value cannot be null", "address"); if (!Enum.IsDefined(typeof(AddressCategory), address.Category)) throw new ArgumentException("Value does not fall within the expected range.", "address.Category"); address.CategoryName = ((AddressCategory)address.Category).ToLocalizedString(); var settings = new JsonSerializerSettings { ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }, Formatting = Formatting.Indented }; var contactInfo = new ContactInfo { InfoType = ContactInfoType.Address, ContactID = contactid, IsPrimary = address.IsPrimary, Category = address.Category, Data = JsonConvert.SerializeObject(address, settings) }; contactInfo.ID = DaoFactory.ContactInfoDao.Save(contactInfo); var messageAction = contact is Company ? MessageAction.CompanyUpdatedPrincipalInfo : MessageAction.PersonUpdatedPrincipalInfo; MessageService.Send(Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); return ToContactInfoWrapper(contactInfo); } /// <summary> /// Creates contact information (add new information to the old list) with the parameters specified in the request for the contact with the selected ID /// </summary> ///<short>Group contact info</short> /// <param name="contactid">Contact ID</param> /// <param name="items">Contact information</param> /// <remarks> /// <![CDATA[ /// items has format /// [{infoType : 1, category : 1, categoryName : 'work', data : "[email protected]", isPrimary : true}, {infoType : 0, category : 0, categoryName : 'home', data : "+8999111999111", isPrimary : true}] /// ]]> /// </remarks> /// <category>Contacts</category> /// <exception cref="ArgumentException"></exception> /// <returns> /// Contact information /// </returns> /// <visible>false</visible> [Create(@"contact/{contactid:[0-9]+}/batch")] public IEnumerable<ContactInfoWrapper> CreateBatchContactInfo(int contactid, IEnumerable<ContactInfoWrapper> items) { if (contactid <= 0) throw new ArgumentException(); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null || !CRMSecurity.CanEdit(contact)) throw new ItemNotFoundException(); var itemsList = items != null ? items.ToList() : new List<ContactInfoWrapper>(); var contactInfoList = itemsList.Select(FromContactInfoWrapper).ToList(); foreach (var contactInfo in contactInfoList) { if (contactInfo.InfoType == ContactInfoType.Address) { Address res; if (!Address.TryParse(contactInfo, out res)) throw new ArgumentException(); } contactInfo.ContactID = contactid; } var ids = DaoFactory.ContactInfoDao.SaveList(contactInfoList, contact); for (var index = 0; index < itemsList.Count; index++) { var infoWrapper = itemsList[index]; infoWrapper.ID = ids[index]; } return itemsList; } /// <summary> /// Updates the information with the parameters specified in the request for the contact with the selected ID /// </summary> ///<param name="id">Contact information record ID</param> ///<param name="contactid">Contact ID</param> ///<param optional="true" name="infoType">Contact information type</param> ///<param name="data">Data</param> ///<param optional="true" name="isPrimary">Contact importance: primary or not</param> ///<param optional="true" name="category">Contact information category</param> ///<short>Update contact info</short> ///<category>Contacts</category> ///<exception cref="ArgumentException"></exception> /// <returns> /// Contact information /// </returns> [Update(@"contact/{contactid:[0-9]+}/data/{id:[0-9]+}")] public ContactInfoWrapper UpdateContactInfo(int id, int contactid, ContactInfoType? infoType, string data, bool? isPrimary, string category) { if (id <= 0 || string.IsNullOrEmpty(data) || contactid <= 0) throw new ArgumentException(); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null || !CRMSecurity.CanEdit(contact)) throw new ItemNotFoundException(); var contactInfo = DaoFactory.ContactInfoDao.GetByID(id); if (infoType != null) { var categoryType = ContactInfo.GetCategory(infoType.Value); if (!string.IsNullOrEmpty(category) && Enum.IsDefined(categoryType, category)) { contactInfo.Category = (int)Enum.Parse(categoryType, category); } contactInfo.InfoType = infoType.Value; } contactInfo.ContactID = contactid; if (isPrimary != null) { contactInfo.IsPrimary = isPrimary.Value; } contactInfo.Data = data; if (contactInfo.InfoType == ContactInfoType.Address) { Address res; if (!Address.TryParse(contactInfo, out res)) throw new ArgumentException(); } DaoFactory.ContactInfoDao.Update(contactInfo); var messageAction = contact is Company ? MessageAction.CompanyUpdatedPrincipalInfo : MessageAction.PersonUpdatedPrincipalInfo; MessageService.Send(Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); var contactInfoWrapper = ToContactInfoWrapper(contactInfo); return contactInfoWrapper; } /// <summary> /// Updates the address information with the parameters specified in the request for the contact with the selected ID /// </summary> /// <param name="id">Contact information record ID</param> /// <param name="contactid">Contact ID</param> /// <param name="address">Address data</param> /// <short>Update address info</short> /// <category>Contacts</category> /// <exception cref="ArgumentException"></exception> /// <exception cref="ItemNotFoundException"></exception> /// <returns> /// Contact information /// </returns> [Update(@"contact/{contactid:[0-9]+}/addressdata/{id:[0-9]+}")] public ContactInfoWrapper UpdateContactInfoAddress(int id, int contactid, Address address) { if (id <= 0) throw new ArgumentException("Invalid value", "id"); var contactInfo = DaoFactory.ContactInfoDao.GetByID(id); if (contactInfo == null || contactInfo.InfoType != ContactInfoType.Address) throw new ItemNotFoundException(); if (contactid <= 0) throw new ArgumentException("Invalid value", "contactid"); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null || !CRMSecurity.CanEdit(contact) || contactInfo.ContactID != contactid) throw new ItemNotFoundException(); if (address == null) throw new ArgumentException("Value cannot be null", "address"); if (!Enum.IsDefined(typeof(AddressCategory), address.Category)) throw new ArgumentException("Value does not fall within the expected range.", "address.Category"); address.CategoryName = ((AddressCategory)address.Category).ToLocalizedString(); var settings = new JsonSerializerSettings { ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }, Formatting = Formatting.Indented }; contactInfo.IsPrimary = address.IsPrimary; contactInfo.Category = address.Category; contactInfo.Data = JsonConvert.SerializeObject(address, settings); DaoFactory.ContactInfoDao.Update(contactInfo); var messageAction = contact is Company ? MessageAction.CompanyUpdatedPrincipalInfo : MessageAction.PersonUpdatedPrincipalInfo; MessageService.Send(Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); return ToContactInfoWrapper(contactInfo); } /// <summary> /// Updates contact information (delete old information and add new list) with the parameters specified in the request for the contact with the selected ID /// </summary> ///<short>Group contact info update</short> ///<param name="contactid">Contact ID</param> ///<param name="items">Contact information</param> /// <![CDATA[ /// items has format /// [{infoType : 1, category : 1, categoryName : 'work', data : "[email protected]", isPrimary : true}, {infoType : 0, category : 0, categoryName : 'home', data : "+8999111999111", isPrimary : true}] /// ]]> ///<category>Contacts</category> ///<exception cref="ArgumentException"></exception> /// <returns> /// Contact information /// </returns> /// <visible>false</visible> [Update(@"contact/{contactid:[0-9]+}/batch")] public IEnumerable<ContactInfoWrapper> UpdateBatchContactInfo(int contactid, IEnumerable<ContactInfoWrapper> items) { if (contactid <= 0) throw new ArgumentException(); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null || !CRMSecurity.CanEdit(contact)) throw new ItemNotFoundException(); var itemsList = items != null ? items.ToList() : new List<ContactInfoWrapper>(); var contactInfoList = itemsList.Select(FromContactInfoWrapper).ToList(); foreach (var contactInfo in contactInfoList) { if (contactInfo.InfoType == ContactInfoType.Address) { Address res; if (!Address.TryParse(contactInfo, out res)) throw new ArgumentException(); } contactInfo.ContactID = contactid; } DaoFactory.ContactInfoDao.DeleteByContact(contactid); var ids = DaoFactory.ContactInfoDao.SaveList(contactInfoList, contact); for (var index = 0; index < itemsList.Count; index++) { var infoWrapper = itemsList[index]; infoWrapper.ID = ids[index]; } return itemsList; } /// <summary> /// Returns the detailed information for the contact with the selected ID by the information type specified in the request /// </summary> /// <param name="contactid">Contact ID</param> /// <param name="infoType">Contact information type</param> /// <short>Get contact information by type</short> /// <category>Contacts</category> /// <returns> /// Contact information /// </returns> [Read(@"contact/{contactid:[0-9]+}/data/{infoType}")] public IEnumerable<string> GetContactInfo(int contactid, ContactInfoType infoType) { if (contactid <= 0) throw new ArgumentException(); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null || !CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); return DaoFactory.ContactInfoDao.GetListData(contactid, infoType); } /// <summary> /// Deletes the contact information for the contact with the ID specified in the request /// </summary> /// <param name="contactid">Contact ID</param> /// <param name="id">Contact information record ID</param> /// <short>Delete contact info</short> /// <category>Contacts</category> /// <exception cref="ArgumentException"></exception> /// <exception cref="ItemNotFoundException"></exception> /// <returns> /// Contact information /// </returns> [Delete(@"contact/{contactid:[0-9]+}/data/{id:[0-9]+}")] public ContactInfoWrapper DeleteContactInfo(int contactid, int id) { if (id <= 0 || contactid <= 0) throw new ArgumentException(); var contact = DaoFactory.ContactDao.GetByID(contactid); if (contact == null || !CRMSecurity.CanEdit(contact)) throw new ItemNotFoundException(); var contactInfo = DaoFactory.ContactInfoDao.GetByID(id); if (contactInfo == null) throw new ItemNotFoundException(); var wrapper = ToContactInfoWrapper(contactInfo); DaoFactory.ContactInfoDao.Delete(id); var messageAction = contact is Company ? MessageAction.CompanyUpdatedPrincipalInfo : MessageAction.PersonUpdatedPrincipalInfo; MessageService.Send(Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); if (contactInfo.InfoType == ContactInfoType.Email) { FactoryIndexer<EmailWrapper>.DeleteAsync(EmailWrapper.ToEmailWrapper(contact, new List<ContactInfo> { contactInfo })); } FactoryIndexer<InfoWrapper>.DeleteAsync(contactInfo); return wrapper; } private static ContactInfoWrapper ToContactInfoWrapper(ContactInfo contactInfo) { return new ContactInfoWrapper(contactInfo); } private static ContactInfo FromContactInfoWrapper(ContactInfoWrapper contactInfoWrapper) { return new ContactInfo { ID = contactInfoWrapper.ID, Category = contactInfoWrapper.Category, Data = contactInfoWrapper.Data, InfoType = contactInfoWrapper.InfoType, IsPrimary = contactInfoWrapper.IsPrimary }; } } }
// 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.Diagnostics; using System.Text; using System.Threading; using System.Globalization; using System.Security; using System.Runtime.CompilerServices; namespace System.Text { internal class SBCSCodePageEncoding : BaseCodePageEncoding { // Pointers to our memory section parts private unsafe char* _mapBytesToUnicode = null; // char 256 private unsafe byte* _mapUnicodeToBytes = null; // byte 65536 private const char UNKNOWN_CHAR = (char)0xFFFD; // byteUnknown is used for default fallback only private byte _byteUnknown; private char _charUnknown; public SBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } public SBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } // We have a managed code page entry, so load our tables // SBCS data section looks like: // // char[256] - what each byte maps to in unicode. No support for surrogates. 0 is undefined code point // (except 0 for byte 0 is expected to be a real 0) // // byte/char* - Data for best fit (unicode->bytes), again no best fit for Unicode // 1st WORD is Unicode // of 1st character position // Next bytes are best fit byte for that position. Position is incremented after each byte // byte < 0x20 means skip the next n positions. (Where n is the byte #) // byte == 1 means that next word is another unicode code point # // byte == 0 is unknown. (doesn't override initial WCHAR[256] table! protected override unsafe void LoadManagedCodePage() { Debug.Assert(m_codePageHeader?.Length > 0); fixed (byte* pBytes = &m_codePageHeader[0]) { CodePageHeader* pCodePage = (CodePageHeader*)pBytes; // Should be loading OUR code page Debug.Assert(pCodePage->CodePage == dataTableCodePage, "[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1 byte code page if (pCodePage->ByteCount != 1) throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage)); // Remember our unknown bytes & chars _byteUnknown = (byte)pCodePage->ByteReplace; _charUnknown = pCodePage->UnicodeReplace; // Get our mapped section 65536 bytes for unicode->bytes, 256 * 2 bytes for bytes->unicode // Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment) const int UnicodeToBytesMappingSize = 65536; const int BytesToUnicodeMappingSize = 256 * 2; const int CodePageNumberSize = 4; int bytesToAllocate = UnicodeToBytesMappingSize + BytesToUnicodeMappingSize + CodePageNumberSize + iExtraBytes; byte* pNativeMemory = GetNativeMemory(bytesToAllocate); Unsafe.InitBlockUnaligned(pNativeMemory, 0, (uint)bytesToAllocate); char* mapBytesToUnicode = (char*)pNativeMemory; byte* mapUnicodeToBytes = (byte*)(pNativeMemory + 256 * 2); // Need to read our data file and fill in our section. // WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide) // so be careful here. Only stick legal values in here, don't stick temporary values. // Read our data file and set mapBytesToUnicode and mapUnicodeToBytes appropriately // First table is just all 256 mappings byte[] buffer = new byte[256 * sizeof(char)]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(buffer, 0, buffer.Length); } fixed (byte* pBuffer = &buffer[0]) { char* pTemp = (char*)pBuffer; for (int b = 0; b < 256; b++) { // Don't want to force 0's to map Unicode wrong. 0 byte == 0 unicode already taken care of if (pTemp[b] != 0 || b == 0) { mapBytesToUnicode[b] = pTemp[b]; if (pTemp[b] != UNKNOWN_CHAR) mapUnicodeToBytes[pTemp[b]] = (byte)b; } else { mapBytesToUnicode[b] = UNKNOWN_CHAR; } } } _mapBytesToUnicode = mapBytesToUnicode; _mapUnicodeToBytes = mapUnicodeToBytes; } } // Private object for locking instead of locking on a public type for SQL reliability work. private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object o = new object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Read in our best fit table protected unsafe override void ReadBestFitTable() { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // If we got a best fit array already, then don't do this if (arrayUnicodeBestFit == null) { // // Read in Best Fit table. // // First check the SBCS->Unicode best fit table, which starts right after the // 256 word data table. This table looks like word, word where 1st word is byte and 2nd // word is replacement for that word. It ends when byte == 0. byte[] buffer = new byte[m_dataSize - 512]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset + 512, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(buffer, 0, buffer.Length); } fixed (byte* pBuffer = buffer) { byte* pData = pBuffer; // Need new best fit array char[] arrayTemp = new char[256]; for (int i = 0; i < 256; i++) arrayTemp[i] = _mapBytesToUnicode[i]; // See if our words are zero ushort byteTemp; while ((byteTemp = *((ushort*)pData)) != 0) { Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, $"[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{(int)arrayTemp[byteTemp]:X2}) for best fit byte at 0x{byteTemp:X2} for code page {CodePage}"); pData += 2; arrayTemp[byteTemp] = *((char*)pData); pData += 2; } // Remember our new array arrayBytesBestFit = arrayTemp; // It was on 0, it needs to be on next byte pData += 2; byte* pUnicodeToSBCS = pData; // Now count our characters from our Unicode->SBCS best fit table, // which is right after our 256 byte data table int iBestFitCount = 0; // Now do the UnicodeToBytes Best Fit mapping (this is the one we normally think of when we say "best fit") // pData should be pointing at the first data point for Bytes->Unicode table int unicodePosition = *((ushort*)pData); pData += 2; while (unicodePosition < 0x10000) { // Get the next byte byte input = *pData; pData++; // build our table: if (input == 1) { // Use next 2 bytes as our byte position unicodePosition = *((ushort*)pData); pData += 2; } else if (input < 0x20 && input > 0 && input != 0x1e) { // Advance input characters unicodePosition += input; } else { // Use this character if it isn't zero if (input > 0) iBestFitCount++; // skip this unicode position in any case unicodePosition++; } } // Make an array for our best fit data arrayTemp = new char[iBestFitCount * 2]; // Now actually read in the data // reset pData should be pointing at the first data point for Bytes->Unicode table pData = pUnicodeToSBCS; unicodePosition = *((ushort*)pData); pData += 2; iBestFitCount = 0; while (unicodePosition < 0x10000) { // Get the next byte byte input = *pData; pData++; // build our table: if (input == 1) { // Use next 2 bytes as our byte position unicodePosition = *((ushort*)pData); pData += 2; } else if (input < 0x20 && input > 0 && input != 0x1e) { // Advance input characters unicodePosition += input; } else { // Check for escape for glyph range if (input == 0x1e) { // Its an escape, so just read next byte directly input = *pData; pData++; } // 0 means just skip me if (input > 0) { // Use this character arrayTemp[iBestFitCount++] = (char)unicodePosition; // Have to map it to Unicode because best fit will need unicode value of best fit char. arrayTemp[iBestFitCount++] = _mapBytesToUnicode[input]; // This won't work if it won't round trip. Debug.Assert(arrayTemp[iBestFitCount - 1] != (char)0, $"[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {(int)_mapBytesToUnicode[input]:X4} for round trip bytes {(int)input:X4}, encoding {CodePage}"); } unicodePosition++; } } // Remember it arrayUnicodeBestFit = arrayTemp; } // Fixed() } } } // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption public override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative"); Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(EncoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); // Need to test fallback EncoderReplacementFallback fallback = null; // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, actually for SBCS this is always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start"); } else { // If we aren't using default fallback then we may have a complicated count. fallback = EncoderFallback as EncoderReplacementFallback; } if ((fallback != null && fallback.MaxCharCount == 1)/* || bIsBestFit*/) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplementary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if (charLeftOver > 0) count++; return (count); } // It had a funky fallback, so it's more complicated // May need buffer later EncoderFallbackBuffer fallbackBuffer = null; // prepare our end int byteCount = 0; char* charEnd = chars + count; EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Since leftover char was a surrogate, it'll have to be fallen back. // Get fallback Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate fallbackHelper.InternalFallback(charLeftOver, ref chars); } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char byte bTemp = _mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (bTemp == 0 && ch != (char)0) { if (fallbackBuffer == null) { // Create & init fallback buffer if (encoder == null) fallbackBuffer = EncoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // chars has moved so we need to remember figure it out so Exception fallback // index will be correct fallbackHelper.InternalInitialize(charEnd - count, charEnd, encoder, false); } // Get Fallback fallbackHelper.InternalFallback(ch, ref chars); continue; } // We'll use this one byteCount++; } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end"); return (int)byteCount; } public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative"); Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(EncoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); // Need to test fallback EncoderReplacementFallback fallback = null; // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetBytes]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, for SBCS its always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetBytes]Expected empty fallback buffer at start"); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && // encoder.FallbackBuffer.Remaining > 0) // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", // EncodingName, encoder.Fallback.GetType())); } else { // If we aren't using default fallback then we may have a complicated count. fallback = EncoderFallback as EncoderReplacementFallback; } // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; // See if we do the fast default or slightly slower fallback if (fallback != null && fallback.MaxCharCount == 1) { // Make sure our fallback character is valid first byte bReplacement = _mapUnicodeToBytes[fallback.DefaultString[0]]; // Check for replacements in range, otherwise fall back to slow version. if (bReplacement != 0) { // We should have exactly as many output bytes as input bytes, unless there's a leftover // character, in which case we may need one more. // If we had a leftover character we will have to add a ? (This happens if they had a funky // fallback last time, but not this time. We can't spit any out though, // because with fallback encoder each surrogate is treated as a separate code point) if (charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if (byteCount == 0) ThrowBytesOverflow(encoder, true); // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = bReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if (byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow(encoder, byteCount < 1); // Just use what we can charEnd = chars + byteCount; } // Simple way while (chars < charEnd) { char ch2 = *chars; chars++; byte bTemp = _mapUnicodeToBytes[ch2]; // Check for fallback if (bTemp == 0 && ch2 != (char)0) *bytes = bReplacement; else *bytes = bTemp; bytes++; } // Clear encoder if (encoder != null) { encoder.charLeftOver = (char)0; encoder.m_charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // For fallback we may need a fallback buffer, we know we aren't default fallback EncoderFallbackBuffer fallbackBuffer = null; // prepare our end byte* byteEnd = bytes + byteCount; EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(chars, charEnd, encoder, true); // This will fallback a pair if *chars is a low surrogate fallbackHelper.InternalFallback(charLeftOver, ref chars); if (fallbackBuffer.Remaining > byteEnd - bytes) { // Throw it, if we don't have enough for this we never will ThrowBytesOverflow(encoder, true); } } // Now we may have fallback char[] already from the encoder fallback above // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char byte bTemp = _mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (bTemp == 0 && ch != (char)0) { // Get Fallback if (fallbackBuffer == null) { // Create & init fallback buffer if (encoder == null) fallbackBuffer = EncoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // chars has moved so we need to remember figure it out so Exception fallback // index will be correct fallbackHelper.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Make sure we have enough room. Each fallback char will be 1 output char // (or recursion exception will be thrown) fallbackHelper.InternalFallback(ch, ref chars); if (fallbackBuffer.Remaining > byteEnd - bytes) { // Didn't use this char, reset it Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)"); chars--; fallbackHelper.InternalReset(); // Throw it & drop this data ThrowBytesOverflow(encoder, chars == charStart); break; } continue; } // We'll use this one // Bounds check if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer Debug.Assert(fallbackBuffer == null || fallbackHelper.bFallingBack == false, "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back"); if (fallbackBuffer == null || fallbackHelper.bFallingBack == false) { Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)"); chars--; // don't use last char } ThrowBytesOverflow(encoder, chars == charStart); // throw ? break; // don't throw, stop } // Go ahead and add it *bytes = bTemp; bytes++; } // encoder stuff if we have one if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } // Expect Empty fallback buffer for SBCS Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } // This is internal and called by something else, public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); // See if we have best fit bool bUseBestFit = false; // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback. DecoderReplacementFallback fallback = null; if (decoder == null) { fallback = DecoderFallback as DecoderReplacementFallback; bUseBestFit = DecoderFallback is InternalDecoderBestFitFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback is InternalDecoderBestFitFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1)) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Might need one of these later DecoderFallbackBuffer fallbackBuffer = null; DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while (bytes < byteEnd) { // Faster if don't use *bytes++; char c; c = _mapBytesToUnicode[*bytes]; bytes++; // If unknown we have to do fallback count if (c == UNKNOWN_CHAR) { // Must have a fallback buffer if (fallbackBuffer == null) { // Need to adjust count so we get real start if (decoder == null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - count, null); } // Use fallback buffer byteBuffer[0] = *(bytes - 1); charCount--; // We'd already reserved one for *(bytes-1) charCount += fallbackHelper.InternalFallback(byteBuffer, bytes); } } // Fallback buffer must be empty Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end"); // Converted sequence is same length as input return charCount; } public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative"); Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); // See if we have best fit bool bUseBestFit = false; // Do it fast way if using ? replacement or best fit fallbacks byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback. DecoderReplacementFallback fallback = null; if (decoder == null) { fallback = DecoderFallback as DecoderReplacementFallback; bUseBestFit = DecoderFallback is InternalDecoderBestFitFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback is InternalDecoderBestFitFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1)) { // Try it the fast way char replacementChar; if (fallback == null) replacementChar = '?'; // Best fit always has ? for fallback for SBCS else replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow(decoder, charCount < 1); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while (bytes < byteEnd) { char c; if (bUseBestFit) { if (arrayBytesBestFit == null) { ReadBestFitTable(); } c = arrayBytesBestFit[*bytes]; } else c = _mapBytesToUnicode[*bytes]; bytes++; if (c == UNKNOWN_CHAR) // This is an invalid byte in the ASCII encoding. *chars = replacementChar; else *chars = c; chars++; } // bytes & chars used are the same if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(null); // Not quite so fast loop while (bytes < byteEnd) { // Faster if don't use *bytes++; char c = _mapBytesToUnicode[*bytes]; bytes++; // See if it was unknown if (c == UNKNOWN_CHAR) { // Make sure we have a fallback buffer if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd); } // Use fallback buffer Debug.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (unknown byte)"); byteBuffer[0] = *(bytes - 1); // Fallback adds fallback to chars, but doesn't increment chars unless the whole thing fits. if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get this byte bytes--; // unused byte fallbackHelper.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if (chars >= charEnd) { Debug.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)"); bytes--; // unused byte ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } *(chars) = c; chars++; } } // Might have had decoder fallback stuff. if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetChars]Expected Empty fallback buffer at end"); return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } // True if and only if the encoding only uses single byte code points. (i.e. ASCII, 1252, etc) public override bool IsSingleByte { get { return true; } } } }
using GraphQLParser.Visitors; namespace GraphQLParser.Tests.Visitors; [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly", Justification = "CountVisitor is sync")] public class GraphQLAstVisitorTests { public class CountVisitor : ASTVisitor<CountContext> { protected override async ValueTask VisitBooleanValueAsync(GraphQLBooleanValue booleanValue, CountContext context) { context.VisitedBooleanValues.Add(booleanValue); await base.VisitBooleanValueAsync(booleanValue, context); } protected override async ValueTask VisitIntValueAsync(GraphQLIntValue intValue, CountContext context) { context.VisitedIntValues.Add(intValue); await base.VisitIntValueAsync(intValue, context); } protected override async ValueTask VisitFragmentSpreadAsync(GraphQLFragmentSpread fragmentSpread, CountContext context) { context.VisitedFragmentSpreads.Add(fragmentSpread); await base.VisitFragmentSpreadAsync(fragmentSpread, context); } protected override async ValueTask VisitArgumentAsync(GraphQLArgument argument, CountContext context) { context.VisitedArguments.Add(argument); await base.VisitArgumentAsync(argument, context); } protected override async ValueTask VisitVariableAsync(GraphQLVariable variable, CountContext context) { context.VisitedVariables.Add(variable); await base.VisitVariableAsync(variable, context); } protected override async ValueTask VisitSelectionSetAsync(GraphQLSelectionSet selectionSet, CountContext context) { context.VisitedSelectionSets.Add(selectionSet); await base.VisitSelectionSetAsync(selectionSet, context); } protected override async ValueTask VisitDirectiveAsync(GraphQLDirective directive, CountContext context) { context.VisitedDirectives.Add(directive); await base.VisitDirectiveAsync(directive, context); } protected override async ValueTask VisitEnumValueAsync(GraphQLEnumValue enumValue, CountContext context) { context.VisitedEnumValues.Add(enumValue); await base.VisitEnumValueAsync(enumValue, context); } protected override async ValueTask VisitStringValueAsync(GraphQLStringValue stringValue, CountContext context) { context.VisitedStringValues.Add(stringValue); await base.VisitStringValueAsync(stringValue, context); } protected override async ValueTask VisitNameAsync(GraphQLName name, CountContext context) { context.VisitedNames.Add(name); await base.VisitNameAsync(name, context); } protected override async ValueTask VisitFieldAsync(GraphQLField field, CountContext context) { context.VisitedFields.Add(field); if (field.Alias != null) context.VisitedAliases.Add(field.Alias); await base.VisitFieldAsync(field, context); } protected override async ValueTask VisitFloatValueAsync(GraphQLFloatValue floatValue, CountContext context) { context.VisitedFloatValues.Add(floatValue); await base.VisitFloatValueAsync(floatValue, context); } protected override async ValueTask VisitEnumTypeDefinitionAsync(GraphQLEnumTypeDefinition enumTypeDefinition, CountContext context) { context.VisitedDefinitions.Add(enumTypeDefinition); await base.VisitEnumTypeDefinitionAsync(enumTypeDefinition, context); } protected override async ValueTask VisitInlineFragmentAsync(GraphQLInlineFragment inlineFragment, CountContext context) { context.VisitedInlineFragments.Add(inlineFragment); context.VisitedFragmentTypeConditions.Add(inlineFragment.TypeCondition); await base.VisitInlineFragmentAsync(inlineFragment, context); } protected override async ValueTask VisitFragmentDefinitionAsync(GraphQLFragmentDefinition fragmentDefinition, CountContext context) { context.VisitedFragmentDefinitions.Add(fragmentDefinition); context.VisitedFragmentTypeConditions.Add(fragmentDefinition.TypeCondition); await base.VisitFragmentDefinitionAsync(fragmentDefinition, context); } protected override async ValueTask VisitFieldDefinitionAsync(GraphQLFieldDefinition fieldDefinition, CountContext context) { context.VisitedDefinitions.Add(fieldDefinition); await base.VisitFieldDefinitionAsync(fieldDefinition, context); } protected override async ValueTask VisitDirectiveDefinitionAsync(GraphQLDirectiveDefinition directiveDefinition, CountContext context) { context.VisitedDefinitions.Add(directiveDefinition); await base.VisitDirectiveDefinitionAsync(directiveDefinition, context); } protected override async ValueTask VisitEnumValueDefinitionAsync(GraphQLEnumValueDefinition enumValueDefinition, CountContext context) { context.VisitedDefinitions.Add(enumValueDefinition); await base.VisitEnumValueDefinitionAsync(enumValueDefinition, context); } protected override async ValueTask VisitInputObjectTypeDefinitionAsync(GraphQLInputObjectTypeDefinition inputObjectTypeDefinition, CountContext context) { context.VisitedDefinitions.Add(inputObjectTypeDefinition); await base.VisitInputObjectTypeDefinitionAsync(inputObjectTypeDefinition, context); } protected override async ValueTask VisitInputValueDefinitionAsync(GraphQLInputValueDefinition inputValueDefinition, CountContext context) { context.VisitedDefinitions.Add(inputValueDefinition); await base.VisitInputValueDefinitionAsync(inputValueDefinition, context); } protected override async ValueTask VisitInterfaceTypeDefinitionAsync(GraphQLInterfaceTypeDefinition interfaceTypeDefinition, CountContext context) { context.VisitedDefinitions.Add(interfaceTypeDefinition); await base.VisitInterfaceTypeDefinitionAsync(interfaceTypeDefinition, context); } protected override async ValueTask VisitObjectTypeDefinitionAsync(GraphQLObjectTypeDefinition objectTypeDefinition, CountContext context) { context.VisitedDefinitions.Add(objectTypeDefinition); await base.VisitObjectTypeDefinitionAsync(objectTypeDefinition, context); } protected override async ValueTask VisitOperationDefinitionAsync(GraphQLOperationDefinition operationDefinition, CountContext context) { context.VisitedDefinitions.Add(operationDefinition); await base.VisitOperationDefinitionAsync(operationDefinition, context); } protected override async ValueTask VisitScalarTypeDefinitionAsync(GraphQLScalarTypeDefinition scalarTypeDefinition, CountContext context) { context.VisitedDefinitions.Add(scalarTypeDefinition); await base.VisitScalarTypeDefinitionAsync(scalarTypeDefinition, context); } protected override async ValueTask VisitRootOperationTypeDefinitionAsync(GraphQLRootOperationTypeDefinition rootOperationTypeDefinition, CountContext context) { context.VisitedDefinitions.Add(rootOperationTypeDefinition); await base.VisitRootOperationTypeDefinitionAsync(rootOperationTypeDefinition, context); } protected override async ValueTask VisitVariableDefinitionAsync(GraphQLVariableDefinition variableDefinition, CountContext context) { context.VisitedDefinitions.Add(variableDefinition); await base.VisitVariableDefinitionAsync(variableDefinition, context); } protected override async ValueTask VisitUnionTypeDefinitionAsync(GraphQLUnionTypeDefinition unionTypeDefinition, CountContext context) { context.VisitedDefinitions.Add(unionTypeDefinition); await base.VisitUnionTypeDefinitionAsync(unionTypeDefinition, context); } protected override async ValueTask VisitSchemaDefinitionAsync(GraphQLSchemaDefinition schemaDefinition, CountContext context) { context.VisitedDefinitions.Add(schemaDefinition); await base.VisitSchemaDefinitionAsync(schemaDefinition, context); } } public class CountContext : IASTVisitorContext { public List<GraphQLAlias> VisitedAliases = new(); public List<GraphQLArgument> VisitedArguments = new(); public List<ASTNode> VisitedDefinitions = new(); public List<GraphQLDirective> VisitedDirectives = new(); public List<GraphQLEnumValue> VisitedEnumValues = new(); public List<GraphQLField> VisitedFields = new(); public List<GraphQLFloatValue> VisitedFloatValues = new(); public List<GraphQLFragmentDefinition> VisitedFragmentDefinitions = new(); public List<GraphQLFragmentSpread> VisitedFragmentSpreads = new(); public List<GraphQLTypeCondition> VisitedFragmentTypeConditions = new(); public List<GraphQLInlineFragment> VisitedInlineFragments = new(); public List<GraphQLIntValue> VisitedIntValues = new(); public List<GraphQLName> VisitedNames = new(); public List<GraphQLSelectionSet> VisitedSelectionSets = new(); public List<GraphQLStringValue> VisitedStringValues = new(); public List<GraphQLVariable> VisitedVariables = new(); public List<GraphQLBooleanValue> VisitedBooleanValues = new(); public CancellationToken CancellationToken { get; set; } } private readonly CountVisitor _visitor = new(); public CountContext Context = new(); [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_BooleanValueArgument_VisitsOneBooleanValue(IgnoreOptions options) { var d = "{ stuff(id : true) }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedBooleanValues.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_DefinitionWithSingleFragmentSpread_VisitsFragmentSpreadOneTime(IgnoreOptions options) { var d = "{ foo { ...fragment } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedFragmentSpreads.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_DefinitionWithSingleFragmentSpread_VisitsNameOfPropertyAndFragmentSpread(IgnoreOptions options) { var d = "{ foo { ...fragment } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedNames.Count.ShouldBe(2); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_DirectiveWithVariable_VisitsVariableOnce(IgnoreOptions options) { var d = "{ ... @include(if : $stuff) { field } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedVariables.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_EnumValueArgument_VisitsOneEnumValue(IgnoreOptions options) { var d = "{ stuff(id : TEST_ENUM) }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedEnumValues.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_FloatValueArgument_VisitsOneFloatValue(IgnoreOptions options) { var d = "{ stuff(id : 1.2) }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedFloatValues.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_FragmentWithTypeCondition_VisitsFragmentDefinitionOnce(IgnoreOptions options) { var d = "fragment testFragment on Stuff { field }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedFragmentDefinitions.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_FragmentWithTypeCondition_VisitsTypeConditionOnce(IgnoreOptions options) { var d = "fragment testFragment on Stuff { field }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedFragmentTypeConditions.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_InlineFragmentWithDirectiveAndArgument_VisitsArgumentsOnce(IgnoreOptions options) { var d = "{ ... @include(if : $stuff) { field } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedArguments.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_InlineFragmentWithDirectiveAndArgument_VisitsDirectiveOnce(IgnoreOptions options) { var d = "{ ... @include(if : $stuff) { field } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedDirectives.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_InlineFragmentWithDirectiveAndArgument_VisitsNameThreeTimes(IgnoreOptions options) { var d = "{ ... @include(if : $stuff) { field } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedNames.Count.ShouldBe(4); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_InlineFragmentWithOneField_VisitsOneField(IgnoreOptions options) { var d = "{ ... @include(if : $stuff) { field } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedFields.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_InlineFragmentWithTypeCondition_VisitsInlineFragmentOnce(IgnoreOptions options) { var d = "{ ... on Stuff { field } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedInlineFragments.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_InlineFragmentWithTypeCondition_VisitsTypeConditionOnce(IgnoreOptions options) { var d = "{ ... on Stuff { field } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedFragmentTypeConditions.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_IntValueArgument_VisitsOneIntValue(IgnoreOptions options) { var d = "{ stuff(id : 1) }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedIntValues.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_OneDefinition_CallsVisitDefinitionOnce(IgnoreOptions options) { var d = "{ a }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedDefinitions.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_OneDefinition_ProvidesCorrectDefinitionAsParameter(IgnoreOptions options) { var d = "{ a }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedDefinitions.Single().ShouldBe(d.Definitions.Single()); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_OneDefinition_VisitsOneSelectionSet(IgnoreOptions options) { var d = "{ a, b }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedSelectionSets.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_OneDefinitionWithOneAliasedField_VisitsOneAlias(IgnoreOptions options) { var d = "{ foo, foo : bar }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedAliases.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_OneDefinitionWithOneArgument_VisitsOneArgument(IgnoreOptions options) { var d = "{ foo(id : 1) { name } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedArguments.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_OneDefinitionWithOneNestedArgument_VisitsOneArgument(IgnoreOptions options) { var d = "{ foo{ names(size: 10) } }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedArguments.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_StringValueArgument_VisitsOneStringValue(IgnoreOptions options) { var d = "{ stuff(id : \"abc\") }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedStringValues.ShouldHaveSingleItem(); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_TwoDefinitions_CallsVisitDefinitionTwice(IgnoreOptions options) { var d = "{ a }\n{ b }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedDefinitions.Count.ShouldBe(2); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_TwoFields_VisitsFieldTwice(IgnoreOptions options) { var d = "{ a, b }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedFields.Count.ShouldBe(2); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_TwoFields_VisitsTwoFieldNames(IgnoreOptions options) { var d = "{ a, b }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedNames.Count.ShouldBe(2); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_TwoFields_VisitsTwoFieldNamesAndDefinitionName(IgnoreOptions options) { var d = "query foo { a, b }".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedNames.Count.ShouldBe(3); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_TwoFieldsWithOneNested_VisitsFiveFields(IgnoreOptions options) { var d = "{a, nested { x, y }, b}".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedFields.Count.ShouldBe(5); } [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Visit_TwoFieldsWithOneNested_VisitsFiveNames(IgnoreOptions options) { var d = "{a, nested { x, y }, b}".Parse(new ParserOptions { Ignore = options }); _visitor.VisitAsync(d, Context); Context.VisitedNames.Count.ShouldBe(5); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { [Flags] internal enum CompilationFlags { EmitExpressionStart = 0x0001, EmitNoExpressionStart = 0x0002, EmitAsDefaultType = 0x0010, EmitAsVoidType = 0x0020, EmitAsTail = 0x0100, // at the tail position of a lambda, tail call can be safely emitted EmitAsMiddle = 0x0200, // in the middle of a lambda, tail call can be emitted if it is in a return EmitAsNoTail = 0x0400, // neither at the tail or in a return, or tail call is not turned on, no tail call is emitted EmitExpressionStartMask = 0x000f, EmitAsTypeMask = 0x00f0, EmitAsTailCallMask = 0x0f00 } /// <summary> /// Update the flag with a new EmitAsTailCall flag /// </summary> private static CompilationFlags UpdateEmitAsTailCallFlag(CompilationFlags flags, CompilationFlags newValue) { Debug.Assert(newValue == CompilationFlags.EmitAsTail || newValue == CompilationFlags.EmitAsMiddle || newValue == CompilationFlags.EmitAsNoTail); CompilationFlags oldValue = flags & CompilationFlags.EmitAsTailCallMask; return flags ^ oldValue | newValue; } /// <summary> /// Update the flag with a new EmitExpressionStart flag /// </summary> private static CompilationFlags UpdateEmitExpressionStartFlag(CompilationFlags flags, CompilationFlags newValue) { Debug.Assert(newValue == CompilationFlags.EmitExpressionStart || newValue == CompilationFlags.EmitNoExpressionStart); CompilationFlags oldValue = flags & CompilationFlags.EmitExpressionStartMask; return flags ^ oldValue | newValue; } /// <summary> /// Update the flag with a new EmitAsType flag /// </summary> private static CompilationFlags UpdateEmitAsTypeFlag(CompilationFlags flags, CompilationFlags newValue) { Debug.Assert(newValue == CompilationFlags.EmitAsDefaultType || newValue == CompilationFlags.EmitAsVoidType); CompilationFlags oldValue = flags & CompilationFlags.EmitAsTypeMask; return flags ^ oldValue | newValue; } /// <summary> /// Generates code for this expression in a value position. /// This method will leave the value of the expression /// on the top of the stack typed as Type. /// </summary> internal void EmitExpression(Expression node) { EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitExpressionStart); } /// <summary> /// Emits an expression and discards the result. For some nodes this emits /// more optimal code then EmitExpression/Pop /// </summary> private void EmitExpressionAsVoid(Expression node) { EmitExpressionAsVoid(node, CompilationFlags.EmitAsNoTail); } private void EmitExpressionAsVoid(Expression node, CompilationFlags flags) { Debug.Assert(node != null); CompilationFlags startEmitted = EmitExpressionStart(node); switch (node.NodeType) { case ExpressionType.Assign: EmitAssign((AssignBinaryExpression)node, CompilationFlags.EmitAsVoidType); break; case ExpressionType.Block: Emit((BlockExpression)node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType)); break; case ExpressionType.Throw: EmitThrow((UnaryExpression)node, CompilationFlags.EmitAsVoidType); break; case ExpressionType.Goto: EmitGotoExpression(node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType)); break; case ExpressionType.Constant: case ExpressionType.Default: case ExpressionType.Parameter: // no-op break; default: if (node.Type == typeof(void)) { EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitNoExpressionStart)); } else { EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); _ilg.Emit(OpCodes.Pop); } break; } EmitExpressionEnd(startEmitted); } private void EmitExpressionAsType(Expression node, Type type, CompilationFlags flags) { if (type == typeof(void)) { EmitExpressionAsVoid(node, flags); } else { // if the node is emitted as a different type, CastClass IL is emitted at the end, // should not emit with tail calls. if (!TypeUtils.AreEquivalent(node.Type, type)) { EmitExpression(node); Debug.Assert(TypeUtils.AreReferenceAssignable(type, node.Type)); _ilg.Emit(OpCodes.Castclass, type); } else { // emit the node with the flags and emit expression start EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart)); } } } #region label block tracking private CompilationFlags EmitExpressionStart(Expression node) { if (TryPushLabelBlock(node)) { return CompilationFlags.EmitExpressionStart; } return CompilationFlags.EmitNoExpressionStart; } private void EmitExpressionEnd(CompilationFlags flags) { if ((flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart) { PopLabelBlock(_labelBlock.Kind); } } #endregion #region InvocationExpression private void EmitInvocationExpression(Expression expr, CompilationFlags flags) { InvocationExpression node = (InvocationExpression)expr; // Optimization: inline code for literal lambda's directly // // This is worth it because otherwise we end up with a extra call // to DynamicMethod.CreateDelegate, which is expensive. // if (node.LambdaOperand != null) { EmitInlinedInvoke(node, flags); return; } expr = node.Expression; Debug.Assert(!typeof(LambdaExpression).IsAssignableFrom(expr.Type)); EmitMethodCall(expr, expr.Type.GetInvokeMethod(), node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitExpressionStart); } private void EmitInlinedInvoke(InvocationExpression invoke, CompilationFlags flags) { LambdaExpression lambda = invoke.LambdaOperand; // This is tricky: we need to emit the arguments outside of the // scope, but set them inside the scope. Fortunately, using the IL // stack it is entirely doable. // 1. Emit invoke arguments List<WriteBack> wb = EmitArguments(lambda.Type.GetInvokeMethod(), invoke); // 2. Create the nested LambdaCompiler var inner = new LambdaCompiler(this, lambda, invoke); // 3. Emit the body // if the inlined lambda is the last expression of the whole lambda, // tail call can be applied. if (wb != null) { Debug.Assert(wb.Count > 0); flags = UpdateEmitAsTailCallFlag(flags, CompilationFlags.EmitAsNoTail); } inner.EmitLambdaBody(_scope, true, flags); // 4. Emit write-backs if needed EmitWriteBack(wb); } #endregion #region IndexExpression private void EmitIndexExpression(Expression expr) { var node = (IndexExpression)expr; // Emit instance, if calling an instance method Type objectType = null; if (node.Object != null) { EmitInstance(node.Object, out objectType); } // Emit indexes. We don't allow byref args, so no need to worry // about write-backs or EmitAddress for (int i = 0, n = node.ArgumentCount; i < n; i++) { Expression arg = node.GetArgument(i); EmitExpression(arg); } EmitGetIndexCall(node, objectType); } private void EmitIndexAssignment(AssignBinaryExpression node, CompilationFlags flags) { Debug.Assert(!node.IsByRef); var index = (IndexExpression)node.Left; CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; // Emit instance, if calling an instance method Type objectType = null; if (index.Object != null) { EmitInstance(index.Object, out objectType); } // Emit indexes. We don't allow byref args, so no need to worry // about write-backs or EmitAddress for (int i = 0, n = index.ArgumentCount; i < n; i++) { Expression arg = index.GetArgument(i); EmitExpression(arg); } // Emit value EmitExpression(node.Right); // Save the expression value, if needed LocalBuilder temp = null; if (emitAs != CompilationFlags.EmitAsVoidType) { _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type)); } EmitSetIndexCall(index, objectType); // Restore the value if (emitAs != CompilationFlags.EmitAsVoidType) { _ilg.Emit(OpCodes.Ldloc, temp); FreeLocal(temp); } } private void EmitGetIndexCall(IndexExpression node, Type objectType) { if (node.Indexer != null) { // For indexed properties, just call the getter MethodInfo method = node.Indexer.GetGetMethod(nonPublic: true); EmitCall(objectType, method); } else { EmitGetArrayElement(objectType); } } private void EmitGetArrayElement(Type arrayType) { if (arrayType.IsSZArray) { // For one dimensional arrays, emit load _ilg.EmitLoadElement(arrayType.GetElementType()); } else { // Multidimensional arrays, call get _ilg.Emit(OpCodes.Call, arrayType.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance)); } } private void EmitSetIndexCall(IndexExpression node, Type objectType) { if (node.Indexer != null) { // For indexed properties, just call the setter MethodInfo method = node.Indexer.GetSetMethod(nonPublic: true); EmitCall(objectType, method); } else { EmitSetArrayElement(objectType); } } private void EmitSetArrayElement(Type arrayType) { if (arrayType.IsSZArray) { // For one dimensional arrays, emit store _ilg.EmitStoreElement(arrayType.GetElementType()); } else { // Multidimensional arrays, call set _ilg.Emit(OpCodes.Call, arrayType.GetMethod("Set", BindingFlags.Public | BindingFlags.Instance)); } } #endregion #region MethodCallExpression private void EmitMethodCallExpression(Expression expr, CompilationFlags flags) { MethodCallExpression node = (MethodCallExpression)expr; EmitMethodCall(node.Object, node.Method, node, flags); } private void EmitMethodCallExpression(Expression expr) { EmitMethodCallExpression(expr, CompilationFlags.EmitAsNoTail); } private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr) { EmitMethodCall(obj, method, methodCallExpr, CompilationFlags.EmitAsNoTail); } private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr, CompilationFlags flags) { // Emit instance, if calling an instance method Type objectType = null; if (!method.IsStatic) { Debug.Assert(obj != null); EmitInstance(obj, out objectType); } // if the obj has a value type, its address is passed to the method call so we cannot destroy the // stack by emitting a tail call if (obj != null && obj.Type.IsValueType) { EmitMethodCall(method, methodCallExpr, objectType); } else { EmitMethodCall(method, methodCallExpr, objectType, flags); } } // assumes 'object' of non-static call is already on stack private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType) { EmitMethodCall(mi, args, objectType, CompilationFlags.EmitAsNoTail); } // assumes 'object' of non-static call is already on stack private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType, CompilationFlags flags) { // Emit arguments List<WriteBack> wb = EmitArguments(mi, args); // Emit the actual call OpCode callOp = UseVirtual(mi) ? OpCodes.Callvirt : OpCodes.Call; if (callOp == OpCodes.Callvirt && objectType.IsValueType) { // This automatically boxes value types if necessary. _ilg.Emit(OpCodes.Constrained, objectType); } // The method call can be a tail call if // 1) the method call is the last instruction before Ret // 2) the method does not have any ByRef parameters, refer to ECMA-335 Partition III Section 2.4. // "Verification requires that no managed pointers are passed to the method being called, since // it does not track pointers into the current frame." if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail && !MethodHasByRefParameter(mi)) { _ilg.Emit(OpCodes.Tailcall); } if (mi.CallingConvention == CallingConventions.VarArgs) { int count = args.ArgumentCount; Type[] types = new Type[count]; for (int i = 0; i < count; i++) { types[i] = args.GetArgument(i).Type; } _ilg.EmitCall(callOp, mi, types); } else { _ilg.Emit(callOp, mi); } // Emit write-backs for properties passed as "ref" arguments EmitWriteBack(wb); } private static bool MethodHasByRefParameter(MethodInfo mi) { foreach (ParameterInfo pi in mi.GetParametersCached()) { if (pi.IsByRefParameter()) { return true; } } return false; } private void EmitCall(Type objectType, MethodInfo method) { if (method.CallingConvention == CallingConventions.VarArgs) { throw Error.UnexpectedVarArgsCall(method); } OpCode callOp = UseVirtual(method) ? OpCodes.Callvirt : OpCodes.Call; if (callOp == OpCodes.Callvirt && objectType.IsValueType) { _ilg.Emit(OpCodes.Constrained, objectType); } _ilg.Emit(callOp, method); } private static bool UseVirtual(MethodInfo mi) { // There are two factors: is the method static, virtual or non-virtual instance? // And is the object ref or value? // The cases are: // // static, ref: call // static, value: call // virtual, ref: callvirt // virtual, value: call -- e.g. double.ToString must be a non-virtual call to be verifiable. // instance, ref: callvirt -- this looks wrong, but is verifiable and gives us a free null check. // instance, value: call // // We never need to generate a non-virtual call to a virtual method on a reference type because // expression trees do not support "base.Foo()" style calling. // // We could do an optimization here for the case where we know that the object is a non-null // reference type and the method is a non-virtual instance method. For example, if we had // (new Foo()).Bar() for instance method Bar we don't need the null check so we could do a // call rather than a callvirt. However that seems like it would not be a very big win for // most dynamically generated code scenarios, so let's not do that for now. if (mi.IsStatic) { return false; } if (mi.DeclaringType.IsValueType) { return false; } return true; } /// <summary> /// Emits arguments to a call, and returns an array of write-backs that /// should happen after the call. /// </summary> private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args) { return EmitArguments(method, args, 0); } /// <summary> /// Emits arguments to a call, and returns an array of write-backs that /// should happen after the call. For emitting dynamic expressions, we /// need to skip the first parameter of the method (the call site). /// </summary> private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args, int skipParameters) { ParameterInfo[] pis = method.GetParametersCached(); Debug.Assert(args.ArgumentCount + skipParameters == pis.Length); List<WriteBack> writeBacks = null; for (int i = skipParameters, n = pis.Length; i < n; i++) { ParameterInfo parameter = pis[i]; Expression argument = args.GetArgument(i - skipParameters); Type type = parameter.ParameterType; if (type.IsByRef) { type = type.GetElementType(); WriteBack wb = EmitAddressWriteBack(argument, type); if (wb != null) { if (writeBacks == null) { writeBacks = new List<WriteBack>(); } writeBacks.Add(wb); } } else { EmitExpression(argument); } } return writeBacks; } private void EmitWriteBack(List<WriteBack> writeBacks) { if (writeBacks != null) { foreach (WriteBack wb in writeBacks) { wb(this); } } } #endregion private void EmitConstantExpression(Expression expr) { ConstantExpression node = (ConstantExpression)expr; EmitConstant(node.Value, node.Type); } private void EmitConstant(object value) { Debug.Assert(value != null); EmitConstant(value, value.GetType()); } private void EmitConstant(object value, Type type) { // Try to emit the constant directly into IL if (!_ilg.TryEmitConstant(value, type, this)) { _boundConstants.EmitConstant(this, value, type); } } private void EmitDynamicExpression(Expression expr) { #if FEATURE_COMPILE_TO_METHODBUILDER if (!(_method is DynamicMethod)) { throw Error.CannotCompileDynamic(); } #else Debug.Assert(_method is DynamicMethod); #endif var node = (IDynamicExpression)expr; object site = node.CreateCallSite(); Type siteType = site.GetType(); MethodInfo invoke = node.DelegateType.GetInvokeMethod(); // site.Target.Invoke(site, args) EmitConstant(site, siteType); // Emit the temp as type CallSite so we get more reuse _ilg.Emit(OpCodes.Dup); LocalBuilder siteTemp = GetLocal(siteType); _ilg.Emit(OpCodes.Stloc, siteTemp); _ilg.Emit(OpCodes.Ldfld, siteType.GetField("Target")); _ilg.Emit(OpCodes.Ldloc, siteTemp); FreeLocal(siteTemp); List<WriteBack> wb = EmitArguments(invoke, node, 1); _ilg.Emit(OpCodes.Callvirt, invoke); EmitWriteBack(wb); } private void EmitNewExpression(Expression expr) { NewExpression node = (NewExpression)expr; if (node.Constructor != null) { if (node.Constructor.DeclaringType.IsAbstract) throw Error.NonAbstractConstructorRequired(); List<WriteBack> wb = EmitArguments(node.Constructor, node); _ilg.Emit(OpCodes.Newobj, node.Constructor); EmitWriteBack(wb); } else { Debug.Assert(node.ArgumentCount == 0, "Node with arguments must have a constructor."); Debug.Assert(node.Type.IsValueType, "Only value type may have constructor not set."); LocalBuilder temp = GetLocal(node.Type); _ilg.Emit(OpCodes.Ldloca, temp); _ilg.Emit(OpCodes.Initobj, node.Type); _ilg.Emit(OpCodes.Ldloc, temp); FreeLocal(temp); } } private void EmitTypeBinaryExpression(Expression expr) { TypeBinaryExpression node = (TypeBinaryExpression)expr; if (node.NodeType == ExpressionType.TypeEqual) { EmitExpression(node.ReduceTypeEqual()); return; } Type type = node.Expression.Type; // Try to determine the result statically AnalyzeTypeIsResult result = ConstantCheck.AnalyzeTypeIs(node); if (result == AnalyzeTypeIsResult.KnownTrue || result == AnalyzeTypeIsResult.KnownFalse) { // Result is known statically, so just emit the expression for // its side effects and return the result EmitExpressionAsVoid(node.Expression); _ilg.EmitPrimitive(result == AnalyzeTypeIsResult.KnownTrue); return; } if (result == AnalyzeTypeIsResult.KnownAssignable) { // We know the type can be assigned, but still need to check // for null at runtime if (type.IsNullableType()) { EmitAddress(node.Expression, type); _ilg.EmitHasValue(type); return; } Debug.Assert(!type.IsValueType); EmitExpression(node.Expression); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Cgt_Un); return; } Debug.Assert(result == AnalyzeTypeIsResult.Unknown); // Emit a full runtime "isinst" check EmitExpression(node.Expression); if (type.IsValueType) { _ilg.Emit(OpCodes.Box, type); } _ilg.Emit(OpCodes.Isinst, node.TypeOperand); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Cgt_Un); } private void EmitVariableAssignment(AssignBinaryExpression node, CompilationFlags flags) { var variable = (ParameterExpression)node.Left; CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; if (node.IsByRef) { EmitAddress(node.Right, node.Right.Type); } else { EmitExpression(node.Right); } if (emitAs != CompilationFlags.EmitAsVoidType) { _ilg.Emit(OpCodes.Dup); } if (variable.IsByRef) { // Note: the stloc/ldloc pattern is a bit suboptimal, but it // saves us from having to spill stack when assigning to a // byref parameter. We already make this same trade-off for // hoisted variables, see ElementStorage.EmitStore LocalBuilder value = GetLocal(variable.Type); _ilg.Emit(OpCodes.Stloc, value); _scope.EmitGet(variable); _ilg.Emit(OpCodes.Ldloc, value); FreeLocal(value); _ilg.EmitStoreValueIndirect(variable.Type); } else { _scope.EmitSet(variable); } } private void EmitAssignBinaryExpression(Expression expr) { EmitAssign((AssignBinaryExpression)expr, CompilationFlags.EmitAsDefaultType); } private void EmitAssign(AssignBinaryExpression node, CompilationFlags emitAs) { switch (node.Left.NodeType) { case ExpressionType.Index: EmitIndexAssignment(node, emitAs); return; case ExpressionType.MemberAccess: EmitMemberAssignment(node, emitAs); return; case ExpressionType.Parameter: EmitVariableAssignment(node, emitAs); return; default: throw ContractUtils.Unreachable; } } private void EmitParameterExpression(Expression expr) { ParameterExpression node = (ParameterExpression)expr; _scope.EmitGet(node); if (node.IsByRef) { _ilg.EmitLoadValueIndirect(node.Type); } } private void EmitLambdaExpression(Expression expr) { LambdaExpression node = (LambdaExpression)expr; EmitDelegateConstruction(node); } private void EmitRuntimeVariablesExpression(Expression expr) { RuntimeVariablesExpression node = (RuntimeVariablesExpression)expr; _scope.EmitVariableAccess(this, node.Variables); } private void EmitMemberAssignment(AssignBinaryExpression node, CompilationFlags flags) { Debug.Assert(!node.IsByRef); MemberExpression lvalue = (MemberExpression)node.Left; MemberInfo member = lvalue.Member; // emit "this", if any Type objectType = null; if (lvalue.Expression != null) { EmitInstance(lvalue.Expression, out objectType); } // emit value EmitExpression(node.Right); LocalBuilder temp = null; CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; if (emitAs != CompilationFlags.EmitAsVoidType) { // save the value so we can return it _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type)); } var fld = member as FieldInfo; if ((object)fld != null) { _ilg.EmitFieldSet((FieldInfo)member); } else { // MemberExpression.Member can only be a FieldInfo or a PropertyInfo Debug.Assert(member is PropertyInfo); var prop = (PropertyInfo)member; EmitCall(objectType, prop.GetSetMethod(nonPublic: true)); } if (emitAs != CompilationFlags.EmitAsVoidType) { _ilg.Emit(OpCodes.Ldloc, temp); FreeLocal(temp); } } private void EmitMemberExpression(Expression expr) { MemberExpression node = (MemberExpression)expr; // emit "this", if any Type instanceType = null; if (node.Expression != null) { EmitInstance(node.Expression, out instanceType); } EmitMemberGet(node.Member, instanceType); } // assumes instance is already on the stack private void EmitMemberGet(MemberInfo member, Type objectType) { var fi = member as FieldInfo; if ((object)fi != null) { if (fi.IsLiteral) { EmitConstant(fi.GetRawConstantValue(), fi.FieldType); } else { _ilg.EmitFieldGet(fi); } } else { // MemberExpression.Member or MemberBinding.Member can only be a FieldInfo or a PropertyInfo Debug.Assert(member is PropertyInfo); var prop = (PropertyInfo)member; EmitCall(objectType, prop.GetGetMethod(nonPublic: true)); } } private void EmitInstance(Expression instance, out Type type) { type = instance.Type; // NB: Instance can be a ByRef type due to stack spilling introducing ref locals for // accessing an instance of a value type. In that case, we don't have to take the // address of the instance anymore; we just load the ref local. if (type.IsByRef) { type = type.GetElementType(); Debug.Assert(instance.NodeType == ExpressionType.Parameter); Debug.Assert(type.IsValueType); EmitExpression(instance); } else if (type.IsValueType) { EmitAddress(instance, type); } else { EmitExpression(instance); } } private void EmitNewArrayExpression(Expression expr) { NewArrayExpression node = (NewArrayExpression)expr; ReadOnlyCollection<Expression> expressions = node.Expressions; int n = expressions.Count; if (node.NodeType == ExpressionType.NewArrayInit) { Type elementType = node.Type.GetElementType(); _ilg.EmitArray(elementType, n); for (int i = 0; i < n; i++) { _ilg.Emit(OpCodes.Dup); _ilg.EmitPrimitive(i); EmitExpression(expressions[i]); _ilg.EmitStoreElement(elementType); } } else { for (int i = 0; i < n; i++) { Expression x = expressions[i]; EmitExpression(x); _ilg.EmitConvertToType(x.Type, typeof(int), isChecked: true, locals: this); } _ilg.EmitArray(node.Type); } } private void EmitDebugInfoExpression(Expression expr) { return; } #region ListInit, MemberInit private void EmitListInitExpression(Expression expr) { EmitListInit((ListInitExpression)expr); } private void EmitMemberInitExpression(Expression expr) { EmitMemberInit((MemberInitExpression)expr); } private void EmitBinding(MemberBinding binding, Type objectType) { switch (binding.BindingType) { case MemberBindingType.Assignment: EmitMemberAssignment((MemberAssignment)binding, objectType); break; case MemberBindingType.ListBinding: EmitMemberListBinding((MemberListBinding)binding); break; case MemberBindingType.MemberBinding: EmitMemberMemberBinding((MemberMemberBinding)binding); break; } } private void EmitMemberAssignment(MemberAssignment binding, Type objectType) { EmitExpression(binding.Expression); if (binding.Member is FieldInfo fi) { _ilg.Emit(OpCodes.Stfld, fi); } else { Debug.Assert(binding.Member is PropertyInfo); EmitCall(objectType, (binding.Member as PropertyInfo).GetSetMethod(nonPublic: true)); } } private void EmitMemberMemberBinding(MemberMemberBinding binding) { Type type = GetMemberType(binding.Member); if (binding.Member is PropertyInfo && type.IsValueType) { throw Error.CannotAutoInitializeValueTypeMemberThroughProperty(binding.Member); } if (type.IsValueType) { EmitMemberAddress(binding.Member, binding.Member.DeclaringType); } else { EmitMemberGet(binding.Member, binding.Member.DeclaringType); } EmitMemberInit(binding.Bindings, false, type); } private void EmitMemberListBinding(MemberListBinding binding) { Type type = GetMemberType(binding.Member); if (binding.Member is PropertyInfo && type.IsValueType) { throw Error.CannotAutoInitializeValueTypeElementThroughProperty(binding.Member); } if (type.IsValueType) { EmitMemberAddress(binding.Member, binding.Member.DeclaringType); } else { EmitMemberGet(binding.Member, binding.Member.DeclaringType); } EmitListInit(binding.Initializers, false, type); } private void EmitMemberInit(MemberInitExpression init) { EmitExpression(init.NewExpression); LocalBuilder loc = null; if (init.NewExpression.Type.IsValueType && init.Bindings.Count > 0) { loc = GetLocal(init.NewExpression.Type); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); } EmitMemberInit(init.Bindings, loc == null, init.NewExpression.Type); if (loc != null) { _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); } } // This method assumes that the instance is on the stack and is expected, based on "keepOnStack" flag // to either leave the instance on the stack, or pop it. private void EmitMemberInit(ReadOnlyCollection<MemberBinding> bindings, bool keepOnStack, Type objectType) { int n = bindings.Count; if (n == 0) { // If there are no initializers and instance is not to be kept on the stack, we must pop explicitly. if (!keepOnStack) { _ilg.Emit(OpCodes.Pop); } } else { for (int i = 0; i < n; i++) { if (keepOnStack || i < n - 1) { _ilg.Emit(OpCodes.Dup); } EmitBinding(bindings[i], objectType); } } } private void EmitListInit(ListInitExpression init) { EmitExpression(init.NewExpression); LocalBuilder loc = null; if (init.NewExpression.Type.IsValueType) { loc = GetLocal(init.NewExpression.Type); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); } EmitListInit(init.Initializers, loc == null, init.NewExpression.Type); if (loc != null) { _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); } } // This method assumes that the list instance is on the stack and is expected, based on "keepOnStack" flag // to either leave the list instance on the stack, or pop it. private void EmitListInit(ReadOnlyCollection<ElementInit> initializers, bool keepOnStack, Type objectType) { int n = initializers.Count; if (n == 0) { // If there are no initializers and instance is not to be kept on the stack, we must pop explicitly. if (!keepOnStack) { _ilg.Emit(OpCodes.Pop); } } else { for (int i = 0; i < n; i++) { if (keepOnStack || i < n - 1) { _ilg.Emit(OpCodes.Dup); } EmitMethodCall(initializers[i].AddMethod, initializers[i], objectType); // Some add methods, ArrayList.Add for example, return non-void if (initializers[i].AddMethod.ReturnType != typeof(void)) { _ilg.Emit(OpCodes.Pop); } } } } private static Type GetMemberType(MemberInfo member) { Debug.Assert(member is FieldInfo || member is PropertyInfo); return member is FieldInfo fi ? fi.FieldType : (member as PropertyInfo).PropertyType; } #endregion #region Expression helpers [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private void EmitLift(ExpressionType nodeType, Type resultType, MethodCallExpression mc, ParameterExpression[] paramList, Expression[] argList) { Debug.Assert(TypeUtils.AreEquivalent(resultType.GetNonNullableType(), mc.Type.GetNonNullableType())); switch (nodeType) { default: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: { Label exit = _ilg.DefineLabel(); Label exitNull = _ilg.DefineLabel(); LocalBuilder anyNull = GetLocal(typeof(bool)); for (int i = 0, n = paramList.Length; i < n; i++) { ParameterExpression v = paramList[i]; Expression arg = argList[i]; if (arg.Type.IsNullableType()) { _scope.AddLocal(this, v); EmitAddress(arg, arg.Type); _ilg.Emit(OpCodes.Dup); _ilg.EmitHasValue(arg.Type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Stloc, anyNull); _ilg.EmitGetValueOrDefault(arg.Type); _scope.EmitSet(v); } else { _scope.AddLocal(this, v); EmitExpression(arg); if (!arg.Type.IsValueType) { _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Stloc, anyNull); } _scope.EmitSet(v); } _ilg.Emit(OpCodes.Ldloc, anyNull); _ilg.Emit(OpCodes.Brtrue, exitNull); } EmitMethodCallExpression(mc); if (resultType.IsNullableType() && !TypeUtils.AreEquivalent(resultType, mc.Type)) { ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type }); _ilg.Emit(OpCodes.Newobj, ci); } _ilg.Emit(OpCodes.Br_S, exit); _ilg.MarkLabel(exitNull); if (TypeUtils.AreEquivalent(resultType, mc.Type.GetNullableType())) { if (resultType.IsValueType) { LocalBuilder result = GetLocal(resultType); _ilg.Emit(OpCodes.Ldloca, result); _ilg.Emit(OpCodes.Initobj, resultType); _ilg.Emit(OpCodes.Ldloc, result); FreeLocal(result); } else { _ilg.Emit(OpCodes.Ldnull); } } else { Debug.Assert(nodeType == ExpressionType.LessThan || nodeType == ExpressionType.LessThanOrEqual || nodeType == ExpressionType.GreaterThan || nodeType == ExpressionType.GreaterThanOrEqual); _ilg.Emit(OpCodes.Ldc_I4_0); } _ilg.MarkLabel(exit); FreeLocal(anyNull); return; } case ExpressionType.Equal: case ExpressionType.NotEqual: { if (TypeUtils.AreEquivalent(resultType, mc.Type.GetNullableType())) { goto default; } Label exit = _ilg.DefineLabel(); Label exitAllNull = _ilg.DefineLabel(); Label exitAnyNull = _ilg.DefineLabel(); LocalBuilder anyNull = GetLocal(typeof(bool)); LocalBuilder allNull = GetLocal(typeof(bool)); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Stloc, anyNull); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Stloc, allNull); for (int i = 0, n = paramList.Length; i < n; i++) { ParameterExpression v = paramList[i]; Expression arg = argList[i]; _scope.AddLocal(this, v); if (arg.Type.IsNullableType()) { EmitAddress(arg, arg.Type); _ilg.Emit(OpCodes.Dup); _ilg.EmitHasValue(arg.Type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Ldloc, anyNull); _ilg.Emit(OpCodes.Or); _ilg.Emit(OpCodes.Stloc, anyNull); _ilg.Emit(OpCodes.Ldloc, allNull); _ilg.Emit(OpCodes.And); _ilg.Emit(OpCodes.Stloc, allNull); _ilg.EmitGetValueOrDefault(arg.Type); } else { EmitExpression(arg); if (!arg.Type.IsValueType) { _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Ldloc, anyNull); _ilg.Emit(OpCodes.Or); _ilg.Emit(OpCodes.Stloc, anyNull); _ilg.Emit(OpCodes.Ldloc, allNull); _ilg.Emit(OpCodes.And); _ilg.Emit(OpCodes.Stloc, allNull); } else { _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Stloc, allNull); } } _scope.EmitSet(v); } _ilg.Emit(OpCodes.Ldloc, allNull); _ilg.Emit(OpCodes.Brtrue, exitAllNull); _ilg.Emit(OpCodes.Ldloc, anyNull); _ilg.Emit(OpCodes.Brtrue, exitAnyNull); EmitMethodCallExpression(mc); if (resultType.IsNullableType() && !TypeUtils.AreEquivalent(resultType, mc.Type)) { ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type }); _ilg.Emit(OpCodes.Newobj, ci); } _ilg.Emit(OpCodes.Br_S, exit); _ilg.MarkLabel(exitAllNull); _ilg.EmitPrimitive(nodeType == ExpressionType.Equal); _ilg.Emit(OpCodes.Br_S, exit); _ilg.MarkLabel(exitAnyNull); _ilg.EmitPrimitive(nodeType == ExpressionType.NotEqual); _ilg.MarkLabel(exit); FreeLocal(anyNull); FreeLocal(allNull); return; } } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using MyMeta; using WeifenLuo.WinFormsUI; using WeifenLuo.WinFormsUI.Docking; namespace MyGeneration { public partial class DefaultSettingsControl : UserControl { private string _lastLoadedConnection = string.Empty; private dbRoot _myMeta; private Color _defaultOleDbButtonColor; private DataTable _driversTable; private IMyGenerationMDI _mdi; public ShowOleDbDialogHandler ShowOleDbDialog; public delegate void AfterSaveDelegate(); public event EventHandler AfterSave; public DataTable DriversTable { get { if (_driversTable == null) { _driversTable = new DataTable(); _driversTable.Columns.Add("DISPLAY"); _driversTable.Columns.Add("VALUE"); _driversTable.Columns.Add("ISPLUGIN"); _driversTable.Rows.Add(new object[] { "<None>", "NONE", false }); _driversTable.Rows.Add(new object[] { "Advantage Database Server", "ADVANTAGE", false }); _driversTable.Rows.Add(new object[] { "Firebird", "FIREBIRD", false }); _driversTable.Rows.Add(new object[] { "IBM DB2", "DB2", false }); _driversTable.Rows.Add(new object[] { "IBM iSeries (AS400)", "ISERIES", false }); _driversTable.Rows.Add(new object[] { "Interbase", "INTERBASE", false }); _driversTable.Rows.Add(new object[] { "Microsoft SQL Server", "SQL", false }); _driversTable.Rows.Add(new object[] { "Microsoft Access", "ACCESS", false }); _driversTable.Rows.Add(new object[] { "MySQL", "MYSQL", false }); _driversTable.Rows.Add(new object[] { "MySQL2", "MYSQL2", false }); _driversTable.Rows.Add(new object[] { "Oracle", "ORACLE", false }); _driversTable.Rows.Add(new object[] { "Pervasive", "PERVASIVE", false }); _driversTable.Rows.Add(new object[] { "PostgreSQL", "POSTGRESQL", false }); _driversTable.Rows.Add(new object[] { "PostgreSQL 8+", "POSTGRESQL8", false }); _driversTable.Rows.Add(new object[] { "SQLite", "SQLITE", false }); #if !IGNORE_VISTA _driversTable.Rows.Add(new object[] { "VistaDB", "VISTADB", false }); #endif foreach (IMyMetaPlugin plugin in MyMeta.dbRoot.Plugins.Values) { _driversTable.Rows.Add(new object[] { plugin.ProviderName, plugin.ProviderUniqueKey, true }); } _driversTable.DefaultView.Sort = "DISPLAY"; } return _driversTable; } } public DefaultSettingsControl() { InitializeComponent(); } public void Initialize(IMyGenerationMDI mdi) { _mdi = mdi; } public void Populate() { PopulateConnectionSettings(); PopulateTemplateSettings(); PopulateMiscSettings(); } private void PopulateConnectionSettings() { _myMeta = new dbRoot(); _myMeta.ShowDefaultDatabaseOnly = DefaultSettings.Instance.ShowDefaultDatabaseOnly; _myMeta.LanguageMappingFileName = DefaultSettings.Instance.LanguageMappingFile; _myMeta.DbTargetMappingFileName = DefaultSettings.Instance.DbTargetMappingFile; ReloadSavedDbConnections(); PopulateConnectionStringSettings(); PopulateDbTargetSettings(); PopulateLanguageSettings(); DbUserMetaMappingsTextBox.Text = DefaultSettings.Instance.DatabaseUserDataXmlMappingsString; UserMetaDataFileTextBox.Text = DefaultSettings.Instance.UserMetaDataFileName; } private void ReloadSavedDbConnections() { SavedConnectionComboBox.Items.Clear(); foreach (ConnectionInfo info in DefaultSettings.Instance.SavedConnections.Values) { SavedConnectionComboBox.Items.Add(info); } SavedConnectionComboBox.Sorted = true; SavedConnectionComboBox.SelectedIndex = -1; } private void PopulateMiscSettings() { CheckForUpdatesCheckBox.Checked = DefaultSettings.Instance.CheckForNewBuild; DomainOverrideCheckBox.Checked = DefaultSettings.Instance.DomainOverride; } private void PopulateLanguageSettings() { PopulateLanguages(); LanguageComboBox.Enabled = true; LanguageComboBox.SelectedItem = DefaultSettings.Instance.Language; LanguageFileTextBox.Text = DefaultSettings.Instance.LanguageMappingFile; } private void PopulateDbTargetSettings() { PopulateDbTargets(); TargetDbComboBox.Enabled = true; TargetDbComboBox.SelectedItem = DefaultSettings.Instance.DbTarget; DbTargetFileTextBox.Text = DefaultSettings.Instance.DbTargetMappingFile; } private void PopulateTemplateSettings() { CopyOutputToClipboardCheckBox.Checked = DefaultSettings.Instance.EnableClipboard; RunTemplatesAsyncCheckBox.Checked = DefaultSettings.Instance.ExecuteFromTemplateBrowserAsync; ShowConsoleOutputCheckBox.Checked = DefaultSettings.Instance.ConsoleWriteGeneratedDetails; DocumentStyleSettingsCheckBox.Checked = DefaultSettings.Instance.EnableDocumentStyleSettings; ShowLineNumbersCheckBox.Checked = DefaultSettings.Instance.EnableLineNumbering; TabSizeTextBox.Text = DefaultSettings.Instance.Tabs.ToString(); DefaultTemplatePathTextBox.Text = DefaultSettings.Instance.DefaultTemplateDirectory; OutputPathTextBox.Text = DefaultSettings.Instance.DefaultOutputDirectory; FontTextBox.Text = DefaultSettings.Instance.FontFamily; PopulateTimeoutSettings(); PopulateProxySettings(); PopulateCodePageEncodingSettings(); } private void PopulateConnectionStringSettings() { _defaultOleDbButtonColor = OleDbButton.BackColor; ShowDefaultDbOnlyCheckBox.Checked = DefaultSettings.Instance.ShowDefaultDatabaseOnly; DbDriverComboBox.DisplayMember = "DISPLAY"; DbDriverComboBox.ValueMember = "VALUE"; DbDriverComboBox.DataSource = DriversTable; DbDriverComboBox.SelectedValue = DefaultSettings.Instance.DbDriver; switch (DefaultSettings.Instance.DbDriver) { case "PERVASIVE": case "POSTGRESQL": case "POSTGRESQL8": case "FIREBIRD": case "INTERBASE": case "SQLITE": case "MYSQL2": case "VISTADB": case "ISERIES": case "NONE": case "": OleDbButton.Enabled = false; break; } ConnectionStringTextBox.Enabled = true; ConnectionStringTextBox.Text = DefaultSettings.Instance.ConnectionString; } private void PopulateTimeoutSettings() { var timeout = DefaultSettings.Instance.ScriptTimeout; if (timeout == -1) { DisableTimeoutCheckBox.Checked = true; DisableTimeoutCheckBox_OnCheckedStateChanged(this, new EventArgs()); } else { DisableTimeoutCheckBox.Checked = false; DisableTimeoutCheckBox_OnCheckedStateChanged(this, new EventArgs()); TimeoutTextBox.Text = timeout.ToString(); } } private void PopulateCodePageEncodingSettings() { var encodings = Encoding.GetEncodings(); CodePageComboBox.Items.Add(string.Empty); foreach (EncodingInfo encoding in encodings) { var windowsCodePage = encoding.CodePage.ToString() + ": " + encoding.DisplayName; var idx = CodePageComboBox.Items.Add(windowsCodePage); if (encoding.CodePage == DefaultSettings.Instance.CodePage) { CodePageComboBox.SelectedIndex = idx; } } } private void PopulateProxySettings() { UseProxyServerCheckBox.Checked = DefaultSettings.Instance.UseProxyServer; ProxyServerTextBox.Text = DefaultSettings.Instance.ProxyServerUri; ProxyUserTextBox.Text = DefaultSettings.Instance.ProxyAuthUsername; ProxyPasswordTextBox.Text = DefaultSettings.Instance.ProxyAuthPassword; ProxyDomainTextBox.Text = DefaultSettings.Instance.ProxyAuthDomain; } public bool Save() { BindControlsToSettings(); DefaultSettings.Instance.Save(); return true; } protected void OnAfterSave() { if (AfterSave != null) AfterSave(this, EventArgs.Empty); } public void Cancel() { DefaultSettings.Instance.DiscardChanges(); } public bool ConnectionInfoModified { get { var info = DefaultSettings.Instance.SavedConnections[_lastLoadedConnection] as ConnectionInfo; if ((_lastLoadedConnection == string.Empty) || (DefaultSettings.Instance.SavedConnections.ContainsKey(_lastLoadedConnection))) { return false; } return (info.Driver != DbDriverComboBox.SelectedValue.ToString()) || (info.ConnectionString != ConnectionStringTextBox.Text) || (info.LanguagePath != LanguageFileTextBox.Text) || (info.Language != LanguageComboBox.Text) || (info.DbTargetPath != DbTargetFileTextBox.Text) || (info.DbTarget != TargetDbComboBox.Text) || (info.UserMetaDataPath != UserMetaDataFileTextBox.Text) || (info.DatabaseUserDataXmlMappingsString != DbUserMetaMappingsTextBox.Text); } } public bool SettingsModified { get { if (DbDriverComboBox.SelectedValue == null) return false; return (DefaultSettings.Instance.DbDriver != DbDriverComboBox.SelectedValue.ToString()) || (DefaultSettings.Instance.ConnectionString != ConnectionStringTextBox.Text) || (DefaultSettings.Instance.LanguageMappingFile != LanguageFileTextBox.Text) || (DefaultSettings.Instance.Language != LanguageComboBox.Text) || (DefaultSettings.Instance.DbTargetMappingFile != DbTargetFileTextBox.Text) || (DefaultSettings.Instance.DbTarget != TargetDbComboBox.Text) || (DefaultSettings.Instance.UserMetaDataFileName != UserMetaDataFileTextBox.Text); } } private void PopulateLanguages() { LanguageComboBox.Items.Clear(); LanguageComboBox.SelectedText = ""; string[] languages = _myMeta.GetLanguageMappings(DbDriverComboBox.SelectedValue as string); if (null != languages) { foreach (string language in languages) { LanguageComboBox.Items.Add(language); } } } private void PopulateDbTargets() { TargetDbComboBox.Items.Clear(); TargetDbComboBox.SelectedText = ""; string[] targets = _myMeta.GetDbTargetMappings(DbDriverComboBox.SelectedValue as string); if (null != targets) { foreach (string target in targets) { TargetDbComboBox.Items.Add(target); } } } private string PickFile(string filter) { openFileDialog.InitialDirectory = Application.StartupPath + @"\Settings"; openFileDialog.Filter = filter; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { return openFileDialog.FileName; } else return string.Empty; } private void BindControlsToSettings() { DefaultSettings.Instance.DbDriver = DbDriverComboBox.SelectedValue as string; DefaultSettings.Instance.ConnectionString = ConnectionStringTextBox.Text; DefaultSettings.Instance.LanguageMappingFile = LanguageFileTextBox.Text; DefaultSettings.Instance.Language = LanguageComboBox.SelectedItem as string; DefaultSettings.Instance.DbTargetMappingFile = DbTargetFileTextBox.Text; DefaultSettings.Instance.DbTarget = TargetDbComboBox.SelectedItem as string; DefaultSettings.Instance.UserMetaDataFileName = UserMetaDataFileTextBox.Text; DefaultSettings.Instance.EnableClipboard = CopyOutputToClipboardCheckBox.Checked; DefaultSettings.Instance.ExecuteFromTemplateBrowserAsync = RunTemplatesAsyncCheckBox.Checked; DefaultSettings.Instance.ShowDefaultDatabaseOnly = ShowDefaultDbOnlyCheckBox.Checked; DefaultSettings.Instance.ConsoleWriteGeneratedDetails = ShowConsoleOutputCheckBox.Checked; DefaultSettings.Instance.EnableDocumentStyleSettings = DocumentStyleSettingsCheckBox.Checked; DefaultSettings.Instance.EnableLineNumbering = ShowLineNumbersCheckBox.Checked; DefaultSettings.Instance.Tabs = Convert.ToInt32(TabSizeTextBox.Text); DefaultSettings.Instance.CheckForNewBuild = CheckForUpdatesCheckBox.Checked; DefaultSettings.Instance.DomainOverride = DomainOverrideCheckBox.Checked; DefaultSettings.Instance.DatabaseUserDataXmlMappingsString = DbUserMetaMappingsTextBox.Text; if (CodePageComboBox.SelectedIndex > 0) { string selText = CodePageComboBox.SelectedItem.ToString(); DefaultSettings.Instance.CodePage = Int32.Parse(selText.Substring(0, selText.IndexOf(':'))); } else { DefaultSettings.Instance.CodePage = -1; } if (FontTextBox.Text.Trim() != string.Empty) { try { Font f = new Font(FontTextBox.Text, 12); DefaultSettings.Instance.FontFamily = f.FontFamily.Name; } catch { } } else { DefaultSettings.Instance.FontFamily = string.Empty; } DefaultSettings.Instance.DefaultTemplateDirectory = DefaultTemplatePathTextBox.Text; DefaultSettings.Instance.DefaultOutputDirectory = OutputPathTextBox.Text; if (DisableTimeoutCheckBox.Checked) { DefaultSettings.Instance.ScriptTimeout = -1; } else { DefaultSettings.Instance.ScriptTimeout = Convert.ToInt32(TimeoutTextBox.Text); } DefaultSettings.Instance.UseProxyServer = UseProxyServerCheckBox.Checked; DefaultSettings.Instance.ProxyServerUri = ProxyServerTextBox.Text; DefaultSettings.Instance.ProxyAuthUsername = ProxyUserTextBox.Text; DefaultSettings.Instance.ProxyAuthPassword = ProxyPasswordTextBox.Text; DefaultSettings.Instance.ProxyAuthDomain = ProxyDomainTextBox.Text; InternalDriver internalDriver = InternalDriver.Get(DefaultSettings.Instance.DbDriver); if (internalDriver != null) { internalDriver.ConnectString = ConnectionStringTextBox.Text; DefaultSettings.Instance.SetSetting(internalDriver.DriverId, ConnectionStringTextBox.Text); } else { MessageBox.Show(this, "Choosing '<None>' will eliminate your ability to run 99.9% of the MyGeneration templates. " + "Most templates will crash if you run them", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } public string TextContent { get { return DefaultSettings.Instance.ConnectionString; } } private bool DbConnectionOk(bool silent) { var dbDriver = string.Empty; var connectionString = string.Empty; try { if (DbDriverComboBox.SelectedValue != null) dbDriver = DbDriverComboBox.SelectedValue as string; connectionString = ConnectionStringTextBox.Text; if (string.IsNullOrWhiteSpace(dbDriver)) { MessageBox.Show("You must choose a DB driver", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (connectionString == string.Empty && dbDriver != "NONE") { MessageBox.Show("Please enter a connection string", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (dbDriver.ToUpper() != "NONE") { return DbConnectionOk(dbDriver, connectionString, silent); } return true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Unable to connect", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } private bool DbConnectionOk(string dbDriver, string connectionString, bool silent) { var testConnectionForm = new TestConnectionForm(dbDriver, connectionString, silent); testConnectionForm.ShowDialog(this); return TestConnectionForm.State != ConnectionTestState.Error; } #region Control Event Handlers private void SettingsCancelButton_OnClicked(object sender, EventArgs e) { ParentForm.Close(); } private void SettingsSaveButton_OnClicked(object sender, EventArgs e) { if (Save()) { _mdi.SendAlert(ParentForm as IMyGenContent, "UpdateDefaultSettings"); OnAfterSave(); } } private void OleDbButton_OnClick(object sender, System.EventArgs e) { try { var dbDriver = string.Empty; var connectionString = string.Empty; if (DbDriverComboBox.SelectedValue != null) dbDriver = DbDriverComboBox.SelectedValue as string; connectionString = ConnectionStringTextBox.Text; if (string.IsNullOrWhiteSpace(dbDriver)) { MessageBox.Show("You Must Choose Driver", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } dbDriver = dbDriver.ToUpper(); InternalDriver drv = InternalDriver.Get(dbDriver); if (ShowOleDbDialog != null) drv.ShowOLEDBDialog = new ShowOleDbDialogHandler(ShowOleDbDialog); if (drv != null) { if (string.Empty == connectionString) { connectionString = (drv != null) ? drv.ConnectString : string.Empty; } connectionString = drv.BrowseConnectionString(connectionString); if (connectionString == null) return; try { if (DbConnectionOk(dbDriver, connectionString, silent: true)) { ConnectionStringTextBox.Text = connectionString; return; } } catch (Exception) { } } } catch { } } private void LanguageFileBrowseButton_OnClicked(object sender, System.EventArgs e) { string fileName = PickFile("Langauge File (*.xml)|*.xml"); if (string.Empty != fileName) { LanguageFileTextBox.Text = fileName; _myMeta.LanguageMappingFileName = fileName; PopulateLanguages(); } } private void DbTargetFileBrowseButton_OnClicked(object sender, System.EventArgs e) { string fileName = PickFile("Database Target File (*.xml)|*.xml"); if (string.Empty != fileName) { DbTargetFileTextBox.Text = fileName; _myMeta.DbTargetMappingFileName = fileName; PopulateDbTargets(); } } private void DbDriverComboBox_OnSelectionChanged(object sender, System.EventArgs e) { ConnectionStringTextBox.Text = string.Empty; ConnectionStringTextBox.Enabled = true; LanguageComboBox.Enabled = true; TargetDbComboBox.Enabled = true; PopulateLanguages(); PopulateDbTargets(); var dbDriver = string.Empty; if (DbDriverComboBox.SelectedValue != null) dbDriver = DbDriverComboBox.SelectedValue as string; dbDriver = dbDriver.ToUpper(); OleDbButton.BackColor = _defaultOleDbButtonColor; OleDbButton.Enabled = true; TestConnectionButton.Enabled = true; InternalDriver internalDriver = InternalDriver.Get(dbDriver); if (internalDriver != null) { bool oleDB = internalDriver.IsOleDB; OleDbButton.Enabled = oleDB; if (oleDB) { OleDbButton.BackColor = System.Drawing.Color.LightBlue; } ConnectionStringTextBox.Text = DefaultSettings.Instance.GetSetting(internalDriver.DriverId, internalDriver.ConnectString); } else { TestConnectionButton.Enabled = false; } } private void DefaultTemplatePathBrowseButton_OnClicked(object sender, System.EventArgs e) { var folderDialog = new FolderBrowserDialog { SelectedPath = DefaultSettings.Instance.DefaultTemplateDirectory, Description = "Select Default Template Directory", RootFolder = Environment.SpecialFolder.MyComputer, ShowNewFolderButton = true }; if (folderDialog.ShowDialog() == DialogResult.OK) { DefaultSettings.Instance.DefaultTemplateDirectory = folderDialog.SelectedPath; DefaultTemplatePathTextBox.Text = DefaultSettings.Instance.DefaultTemplateDirectory; } } private void OutputPathBrowseButton_OnClicked(object sender, System.EventArgs e) { FolderBrowserDialog folderDialog = new FolderBrowserDialog(); folderDialog.SelectedPath = DefaultSettings.Instance.DefaultOutputDirectory; folderDialog.Description = "Select Default Output Directory"; folderDialog.RootFolder = Environment.SpecialFolder.MyComputer; folderDialog.ShowNewFolderButton = true; if (folderDialog.ShowDialog() == DialogResult.OK) { DefaultSettings.Instance.DefaultOutputDirectory = folderDialog.SelectedPath; OutputPathTextBox.Text = DefaultSettings.Instance.DefaultOutputDirectory; } } private void DisableTimeoutCheckBox_OnCheckedStateChanged(object sender, System.EventArgs e) { bool isChecked = DisableTimeoutCheckBox.Checked; if (isChecked) { TimeoutTextBox.Text = ""; } TimeoutTextBox.Enabled = !isChecked; TimeoutTextBox.ReadOnly = isChecked; label9.Enabled = !isChecked; } private void UseProxyServerCheckBox_OnCheckedStateChanged(object sender, System.EventArgs e) { bool isChecked = UseProxyServerCheckBox.Checked; ProxyServerTextBox.Enabled = isChecked; ProxyServerTextBox.ReadOnly = !isChecked; labelProxyServer.Enabled = isChecked; ProxyUserTextBox.Enabled = isChecked; ProxyUserTextBox.ReadOnly = !isChecked; labelProxyUser.Enabled = isChecked; ProxyPasswordTextBox.Enabled = isChecked; ProxyPasswordTextBox.ReadOnly = !isChecked; labelProxyPassword.Enabled = isChecked; ProxyDomainTextBox.Enabled = isChecked; ProxyDomainTextBox.ReadOnly = !isChecked; labelProxyDomain.Enabled = isChecked; } private void TestConnectionButton_OnClicked(object sender, System.EventArgs e) { DbConnectionOk(false); } private void DbDriverComboBox_OnSelectedIndexChanged(object sender, System.EventArgs e) { DbDriverComboBox_OnSelectionChanged(sender, e); } private void SavedConnectionsSaveButton_OnClicked(object sender, System.EventArgs e) { string text = SavedConnectionComboBox.Text.Trim(); if (text == string.Empty) { MessageBox.Show("Please Enter a Name for this Saved Connection. Type the Name Directly into the ComboBox.", "Saved Connection Name Required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); SavedConnectionComboBox.Focus(); } else { _lastLoadedConnection = text; ConnectionInfo info = null; info = DefaultSettings.Instance.SavedConnections[text] as ConnectionInfo; if (info == null) { info = new ConnectionInfo(); info.Name = SavedConnectionComboBox.Text; DefaultSettings.Instance.SavedConnections[info.Name] = info; } info.Driver = DbDriverComboBox.SelectedValue.ToString(); info.ConnectionString = ConnectionStringTextBox.Text; info.UserMetaDataPath = UserMetaDataFileTextBox.Text; info.Language = LanguageComboBox.Text; info.DbTarget = TargetDbComboBox.Text; info.LanguagePath = LanguageFileTextBox.Text; info.DbTargetPath = DbTargetFileTextBox.Text; info.DatabaseUserDataXmlMappingsString = DbUserMetaMappingsTextBox.Text; ReloadSavedDbConnections(); } } private void SavedConnectionLoadButton_OnClicked(object sender, System.EventArgs e) { ConnectionInfo info = SavedConnectionComboBox.SelectedItem as ConnectionInfo; if (info != null) { _lastLoadedConnection = info.Name; DefaultSettings.Instance.DbDriver = info.Driver; DefaultSettings.Instance.ConnectionString = info.ConnectionString; DefaultSettings.Instance.UserMetaDataFileName = info.UserMetaDataPath; DefaultSettings.Instance.Language = info.Language; DefaultSettings.Instance.LanguageMappingFile = info.LanguagePath; DefaultSettings.Instance.DbTarget = info.DbTarget; DefaultSettings.Instance.DbTargetMappingFile = info.DbTargetPath; DbDriverComboBox.SelectedValue = DefaultSettings.Instance.DbDriver; ConnectionStringTextBox.Text = DefaultSettings.Instance.ConnectionString; LanguageFileTextBox.Text = DefaultSettings.Instance.LanguageMappingFile; DbTargetFileTextBox.Text = DefaultSettings.Instance.DbTargetMappingFile; UserMetaDataFileTextBox.Text = DefaultSettings.Instance.UserMetaDataFileName; _myMeta.LanguageMappingFileName = DefaultSettings.Instance.LanguageMappingFile; _myMeta.DbTargetMappingFileName = DefaultSettings.Instance.DbTargetMappingFile; LanguageComboBox.Enabled = true; TargetDbComboBox.Enabled = true; PopulateLanguages(); PopulateDbTargets(); LanguageComboBox.SelectedItem = DefaultSettings.Instance.Language; TargetDbComboBox.SelectedItem = DefaultSettings.Instance.DbTarget; DbUserMetaMappingsTextBox.Text = info.DatabaseUserDataXmlMappingsString; DefaultSettings.Instance.DatabaseUserDataXmlMappings.Clear(); foreach (string key in info.DatabaseUserDataXmlMappings.Keys) { DefaultSettings.Instance.DatabaseUserDataXmlMappings[key] = info.DatabaseUserDataXmlMappings[key]; } } else { MessageBox.Show("You Must Select a Saved Connection to Load", "No Saved Connection Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void SavedConnectionDeleteButton_OnClicked(object sender, System.EventArgs e) { ConnectionInfo info = SavedConnectionComboBox.SelectedItem as ConnectionInfo; if (info != null) { DefaultSettings.Instance.SavedConnections.Remove(info.Name); ReloadSavedDbConnections(); if (SavedConnectionComboBox.Items.Count > 0) SavedConnectionComboBox.SelectedIndex = 0; else { SavedConnectionComboBox.SelectedIndex = -1; SavedConnectionComboBox.Text = string.Empty; } } else { MessageBox.Show("You Must Select a Saved Connection to Delete", "No Saved Connection Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void FontButton_OnClicked(object sender, EventArgs e) { try { Font f = new Font(FontTextBox.Text, 12); fontDialog1.Font = f; } catch { FontTextBox.Text = string.Empty; } fontDialog1.ShowColor = false; fontDialog1.ShowEffects = false; if (fontDialog1.ShowDialog() == DialogResult.OK) { FontTextBox.Text = fontDialog1.Font.FontFamily.Name; } else if (fontDialog1.ShowDialog() == DialogResult.None) { FontTextBox.Text = string.Empty; } } private void UserMetadataFileBrowseButton_OnClicked(object sender, System.EventArgs e) { var fileName = PickFile("Language File (*.xml)|*.xml"); if (!string.IsNullOrWhiteSpace(fileName)) { UserMetaDataFileTextBox.Text = fileName; } } #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookNamedItemRequest. /// </summary> public partial class WorkbookNamedItemRequest : BaseRequest, IWorkbookNamedItemRequest { /// <summary> /// Constructs a new WorkbookNamedItemRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookNamedItemRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookNamedItem using POST. /// </summary> /// <param name="workbookNamedItemToCreate">The WorkbookNamedItem to create.</param> /// <returns>The created WorkbookNamedItem.</returns> public System.Threading.Tasks.Task<WorkbookNamedItem> CreateAsync(WorkbookNamedItem workbookNamedItemToCreate) { return this.CreateAsync(workbookNamedItemToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookNamedItem using POST. /// </summary> /// <param name="workbookNamedItemToCreate">The WorkbookNamedItem to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookNamedItem.</returns> public async System.Threading.Tasks.Task<WorkbookNamedItem> CreateAsync(WorkbookNamedItem workbookNamedItemToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookNamedItem>(workbookNamedItemToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookNamedItem. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookNamedItem. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookNamedItem>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookNamedItem. /// </summary> /// <returns>The WorkbookNamedItem.</returns> public System.Threading.Tasks.Task<WorkbookNamedItem> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookNamedItem. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookNamedItem.</returns> public async System.Threading.Tasks.Task<WorkbookNamedItem> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookNamedItem>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookNamedItem using PATCH. /// </summary> /// <param name="workbookNamedItemToUpdate">The WorkbookNamedItem to update.</param> /// <returns>The updated WorkbookNamedItem.</returns> public System.Threading.Tasks.Task<WorkbookNamedItem> UpdateAsync(WorkbookNamedItem workbookNamedItemToUpdate) { return this.UpdateAsync(workbookNamedItemToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookNamedItem using PATCH. /// </summary> /// <param name="workbookNamedItemToUpdate">The WorkbookNamedItem to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookNamedItem.</returns> public async System.Threading.Tasks.Task<WorkbookNamedItem> UpdateAsync(WorkbookNamedItem workbookNamedItemToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookNamedItem>(workbookNamedItemToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamedItemRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamedItemRequest Expand(Expression<Func<WorkbookNamedItem, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamedItemRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookNamedItemRequest Select(Expression<Func<WorkbookNamedItem, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookNamedItemToInitialize">The <see cref="WorkbookNamedItem"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookNamedItem workbookNamedItemToInitialize) { } } }
using System; using System.Collections; using System.Runtime.InteropServices; #pragma warning disable 1717 #pragma warning disable 0219 #pragma warning disable 1718 public enum TestEnum { red = 1, green = 2, blue = 4, } public class AA { public double[][] m_adblField1; public static ulong[] Static1() { for (App.m_xFwd1=App.m_xFwd1; App.m_bFwd2; App.m_shFwd3-=((short)(121.0))) { if (App.m_bFwd2) do { try { uint[,][] local1 = (new uint[88u, 43u][]); do { } while(App.m_bFwd2); } catch (Exception) { AA local2 = new AA(); } try { bool local3 = false; } finally { char local4 = '\x5d'; } } while(App.m_bFwd2); throw new DivideByZeroException(); } try { } catch (IndexOutOfRangeException) { byte local5 = ((byte)(26.0)); } return (new ulong[3u]); } public static ushort[] Static2() { for (App.m_ushFwd4*=App.m_ushFwd4; App.m_bFwd2; App.m_dblFwd5-=66.0) { float local6 = 112.0f; do { goto label1; } while(App.m_bFwd2); local6 = local6; label1: try { Array local7 = ((Array)(null)); } catch (Exception) { } } try { } catch (IndexOutOfRangeException) { } while (App.m_bFwd2) { } return App.m_aushFwd6; } public static long[] Static3() { for (App.m_sbyFwd7*=((sbyte)(70)); (null == new AA()); App.m_dblFwd5+=97.0) { double local8 = 20.0; for (App.m_iFwd8*=119; App.m_bFwd2; App.m_lFwd9--) { short local9 = App.m_shFwd3; return (new long[111u]); } local8 = local8; if (App.m_bFwd2) continue; } return App.m_alFwd10; } public static short[] Static4() { byte local10 = ((byte)(55u)); for (App.m_dblFwd5=App.m_dblFwd5; App.m_bFwd2; App.m_ulFwd11--) { sbyte[][,,][,] local11 = (new sbyte[91u][,,][,]); break; } while (App.m_bFwd2) { char local12 = '\x48'; while ((null != new AA())) { double local13 = 55.0; try { while ((local10 != local10)) { sbyte[,,] local14 = (new sbyte[97u, 62u, 10u]); } } catch (Exception) { } if (App.m_bFwd2) for (App.m_sbyFwd7/=((sbyte)(local10)); App.m_bFwd2; App.m_lFwd9/=App. m_lFwd9) { } } } return (new short[16u]); } public static long[][] Static5() { byte[,,] local15 = (new byte[7u, 92u, 57u]); return new long[][]{(new long[33u]), (new long[60u]), /*2 REFS*/(new long[61u] ), /*2 REFS*/(new long[61u]), (new long[22u]) }; } public static TestEnum Static6() { int local16 = 105; do { ulong local17 = ((ulong)(54)); for (local16+=(local16 *= local16); App.m_bFwd2; App.m_dblFwd5++) { int local18 = 90; try { int local19 = 45; if ((new AA() == null)) try { } catch (Exception) { } else { } } catch (InvalidOperationException) { } local17 += local17; goto label2; } } while(App.m_bFwd2); local16 -= ((int)(18u)); label2: return 0; } public static double Static7() { for (App.m_sbyFwd7=App.m_sbyFwd7; App.m_bFwd2; App.m_chFwd12++) { object local20 = null; for (App.m_iFwd8++; ((bool)(local20)); local20=local20) { AA.Static1( ); } } return 82.0; } public static byte Static8() { while (App.m_bFwd2) { short local21 = App.m_shFwd3; while (Convert.ToBoolean(local21)) { local21 *= (local21 -= local21); goto label3; } if (App.m_bFwd2) local21 /= local21; local21 = (local21 += local21); } if (App.m_bFwd2) for (App.m_lFwd9--; App.m_bFwd2; App.m_dblFwd5-=AA.Static7()) { TestEnum[][,,,][,] local22 = (new TestEnum[102u][,,,][,]); } label3: return App.m_byFwd13; } } [StructLayout(LayoutKind.Sequential)] public class App { public static int Main() { try { AA.Static1( ); } catch (Exception ) { } try { AA.Static2( ); } catch (Exception ) { } try { AA.Static3( ); } catch (Exception ) { } try { AA.Static4( ); } catch (Exception ) { } try { AA.Static5( ); } catch (Exception ) { } try { AA.Static6( ); } catch (Exception ) { } try { AA.Static7( ); } catch (Exception ) { } try { AA.Static8( ); } catch (Exception ) { } return 100; } public static Array m_xFwd1; public static bool m_bFwd2; public static short m_shFwd3; public static ushort m_ushFwd4; public static double m_dblFwd5; public static ushort[] m_aushFwd6; public static sbyte m_sbyFwd7; public static int m_iFwd8; public static long m_lFwd9; public static long[] m_alFwd10; public static ulong m_ulFwd11; public static char m_chFwd12; public static byte m_byFwd13; }
using Bytes2you.Validation; using SocialServicesManager.Data.Factories.Contracts; using SocialServicesManager.Data.Models; using System.Collections.Generic; using System.Linq; namespace SocialServicesManager.Data.Factories { public class DataFactory : IDataFactory { private readonly SQLServerDbContext sqlDbContext; private readonly PostgreDbContext postgreDbContext; private readonly SqliteDbContext sqliteDbContext; public DataFactory(SQLServerDbContext sqlDbContext, PostgreDbContext postgreDbContext, SqliteDbContext sqliteDbContext) { Guard.WhenArgument(sqlDbContext, "sqlDbContext").IsNull().Throw(); this.sqlDbContext = sqlDbContext; Guard.WhenArgument(postgreDbContext, "postgreDbContext").IsNull().Throw(); this.postgreDbContext = postgreDbContext; Guard.WhenArgument(sqliteDbContext, "sqliteDbContext").IsNull().Throw(); this.sqliteDbContext = sqliteDbContext; } private SQLServerDbContext SqlDbContext { get { return this.sqlDbContext; } } private PostgreDbContext PostgreDbContext { get { return this.postgreDbContext; } } private SqliteDbContext SqliteDbContext { get { return this.sqliteDbContext; } } // CREATING public void AddAddress(Address address) { this.SqlDbContext.Addresses.Add(address); } public void AddChild(Child child) { this.SqlDbContext.Children.Add(child); } public void AddFamily(Family family) { this.SqlDbContext.Families.Add(family); } public void AddFamilyMember(FamilyMember familyMember) { this.SqlDbContext.FamilyMembers.Add(familyMember); } public void AddMedicalDoctor(MedicalDoctor doctor) { this.SqliteDbContext.MedicalDoctors.Add(doctor); } public void AddMedicalRecord(MedicalRecord record) { this.SqliteDbContext.MedicalRecords.Add(record); } public void AddMunicipality(Municipality municipality) { this.SqlDbContext.Municipalities.Add(municipality); } public void AddTown(Town town) { this.SqlDbContext.Towns.Add(town); } public void AddUser(User user) { this.SqlDbContext.Users.Add(user); } public void AddVisit(Visit visit) { this.PostgreDbContext.Visits.Add(visit); } public void AddVisitType(VisitType visitType) { this.PostgreDbContext.VisitTypes.Add(visitType); } // TODO Research if this creates issues public void SaveAllChanges() { this.SqlDbContext.SaveChanges(); this.PostgreDbContext.SaveChanges(); this.SqliteDbContext.SaveChanges(); } // READING public Address FindAddress(int id) { var addressFound = this.SqlDbContext.Addresses.Find(id); return addressFound; } public Child FindChild(int id) { var childFound = this.SqlDbContext.Children .Where(c => c.Id == id) .Where(c => c.Deleted == false) .FirstOrDefault(); return childFound; } public Family FindFamily(int id) { var familyFound = this.SqlDbContext.Families .Where(f => f.Id == id) .Where(f => f.Deleted == false) .FirstOrDefault(); return familyFound; } public string GetFamilyName(int id) { var nameFound = this.sqlDbContext.Families .Where(f => f.Id == id) .Where(f => f.Deleted == false) .Select(f => f.Name) .FirstOrDefault(); return nameFound; } public Gender GetGender(string gender) { var genderFound = this.SqlDbContext.Genders .FirstOrDefault(g => g.Name.ToLower() == gender.ToLower()); return genderFound; } public MedicalDoctor FindMedicalDoctor(int id) { var doctorFound = this.SqliteDbContext.MedicalDoctors .Where(d => d.Id == id) .Where(d => d.Deleted == false) .FirstOrDefault(); return doctorFound; } public Town FindTown(int id) { var townFound = this.SqlDbContext.Towns.Find(id); return townFound; } public User FindUser(int id) { var userFound = this.SqlDbContext.Users .Where(u => u.Id == id) .Where(u => u.Deleted == false) .FirstOrDefault(); return userFound; } public string GetUserByUsername(string username) { var usernameFound = this.sqlDbContext.Users .Where(u => u.UserName == username) .Where(u => u.Deleted == false) .Select(u => u.UserName) .FirstOrDefault(); return usernameFound; } public VisitType GetVisitType(string type) { var typeFound = this.PostgreDbContext.VisitTypes .Where(v => v.Name == type) .FirstOrDefault(); return typeFound; } public Visit FindVisit(int id) { return this.postgreDbContext.Visits.Find(id); } public ICollection<Child> GetAllChildren() { return this.SqlDbContext.Children .Where(c => c.Deleted == false) .ToList(); } public ICollection<Family> GetAllFamilies() { return this.SqlDbContext.Families .Where(f => f.Deleted == false) .ToList(); } public ICollection<User> GetAllUsers() { return this.SqlDbContext.Users .Where(u => u.Deleted == false) .ToList(); } public ICollection<Visit> GetUserVisits(int userId) { var userVisits = this.PostgreDbContext.Visits .Where(v => v.UserId == userId) .Where(v => v.Deleted == false) .ToList(); return userVisits; } public ICollection<Visit> GetFamilyVisits(Family family) { return this.PostgreDbContext.Visits .Where(v => v.FamilyId == family.Id) .Where(v => v.Deleted == false) .ToList(); } public ICollection<VisitType> GetAllVisitTypes() { return this.postgreDbContext.VisitTypes .ToList(); } // UPDATING public void UpdateChild(Child oldChild, Child newChild) { oldChild.FirstName = newChild.FirstName ?? oldChild.FirstName; oldChild.LastName = newChild.LastName ?? oldChild.LastName; oldChild.Gender = newChild.Gender ?? oldChild.Gender; oldChild.BirthDate = newChild.BirthDate ?? oldChild.BirthDate; oldChild.Family = newChild.Family ?? oldChild.Family; } public void UpdateFamilyName(Family family, string newName) { family.Name = newName; } public void UpdateFamilyStaff(Family family, User newStaff) { family.AssignedStaffMember = newStaff; } public void UpdateVisit(Visit oldVisit, Visit newVisit) { oldVisit.Date = newVisit.Date; oldVisit.UserId = newVisit.UserId; oldVisit.FamilyId = newVisit.FamilyId; oldVisit.VisitType = newVisit.VisitType; oldVisit.Description = newVisit.Description; } // DELETING public void DeleteChild(Child child) { child.Deleted = true; } public void DeleteFamily(Family family) { family.Deleted = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime; namespace System.Runtime { public enum RhFailFastReason { Unknown = 0, InternalError = 1, // "Runtime internal error" UnhandledException_ExceptionDispatchNotAllowed = 2, // "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope." UnhandledException_CallerDidNotHandle = 3, // "Unhandled exception: no handler found in calling method." ClassLibDidNotTranslateExceptionID = 4, // "Unable to translate failure into a classlib-specific exception object." IllegalNativeCallableEntry = 5, // "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code." PN_UnhandledException = 6, // ProjectN: "unhandled exception" PN_UnhandledExceptionFromPInvoke = 7, // ProjectN: "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition." Max } // Keep this synchronized with the duplicate definition in DebugEventSource.cpp [Flags] internal enum ExceptionEventKind { Thrown = 1, CatchHandlerFound = 2, Unhandled = 4, FirstPassFrameEntered = 8 } internal static unsafe class DebuggerNotify { // We cache the events a debugger is interested on the C# side to avoid p/invokes when the // debugger isn't attached. // // Ideally we would like the managed debugger to start toggling this directly so that // it stays perfectly up-to-date. However as a reasonable approximation we fetch // the value from native code at the beginning of each exception dispatch. If the debugger // attempts to enroll in more events mid-exception handling we aren't going to see it. private static ExceptionEventKind s_cachedEventMask; internal static void BeginFirstPass(object exceptionObj, byte* faultingIP, UIntPtr faultingFrameSP) { s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents(); if ((s_cachedEventMask & ExceptionEventKind.Thrown) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Thrown, faultingIP, faultingFrameSP); } internal static void FirstPassFrameEntered(object exceptionObj, byte* enteredFrameIP, UIntPtr enteredFrameSP) { s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents(); if ((s_cachedEventMask & ExceptionEventKind.FirstPassFrameEntered) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.FirstPassFrameEntered, enteredFrameIP, enteredFrameSP); } internal static void EndFirstPass(object exceptionObj, byte* handlerIP, UIntPtr handlingFrameSP) { if (handlerIP == null) { if ((s_cachedEventMask & ExceptionEventKind.Unhandled) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Unhandled, null, UIntPtr.Zero); } else { if ((s_cachedEventMask & ExceptionEventKind.CatchHandlerFound) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.CatchHandlerFound, handlerIP, handlingFrameSP); } } internal static void BeginSecondPass() { //desktop debugging has an unwind begin event, however it appears that is unneeded for now, and possibly // will never be needed? } } internal static unsafe class EH { internal static UIntPtr MaxSP { get { return (UIntPtr)(void*)(-1); } } private enum RhEHClauseKind { RH_EH_CLAUSE_TYPED = 0, RH_EH_CLAUSE_FAULT = 1, RH_EH_CLAUSE_FILTER = 2, RH_EH_CLAUSE_UNUSED = 3, } private struct RhEHClause { internal RhEHClauseKind _clauseKind; internal uint _tryStartOffset; internal uint _tryEndOffset; internal byte* _filterAddress; internal byte* _handlerAddress; internal void* _pTargetType; ///<summary> /// We expect the stackwalker to adjust return addresses to point at 'return address - 1' so that we /// can use an interval here that is closed at the start and open at the end. When a hardware fault /// occurs, the IP is pointing at the start of the instruction and will not be adjusted by the /// stackwalker. Therefore, it will naturally work with an interval that has a closed start and open /// end. ///</summary> public bool ContainsCodeOffset(uint codeOffset) { return ((codeOffset >= _tryStartOffset) && (codeOffset < _tryEndOffset)); } } [StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__EHEnum)] private struct EHEnum { [FieldOffset(0)] private IntPtr _dummy; // For alignment } // This is a fail-fast function used by the runtime as a last resort that will terminate the process with // as little effort as possible. No guarantee is made about the semantics of this fail-fast. internal static void FallbackFailFast(RhFailFastReason reason, object unhandledException) { InternalCalls.RhpFallbackFailFast(); } // Constants used with RhpGetClasslibFunction, to indicate which classlib function // we are interested in. // Note: make sure you change the def in EHHelpers.cpp if you change this! internal enum ClassLibFunctionId { GetRuntimeException = 0, FailFast = 1, // UnhandledExceptionHandler = 2, // unused AppendExceptionStackFrame = 3, CheckStaticClassConstruction = 4, GetSystemArrayEEType = 5, OnFirstChance = 6, } // Given an address pointing somewhere into a managed module, get the classlib-defined fail-fast // function and invoke it. Any failure to find and invoke the function, or if it returns, results in // MRT-defined fail-fast behavior. internal static void FailFastViaClasslib(RhFailFastReason reason, object unhandledException, IntPtr classlibAddress) { // Find the classlib function that will fail fast. This is a RuntimeExport function from the // classlib module, and is therefore managed-callable. IntPtr pFailFastFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(classlibAddress, ClassLibFunctionId.FailFast); if (pFailFastFunction == IntPtr.Zero) { // The classlib didn't provide a function, so we fail our way... FallbackFailFast(reason, unhandledException); } try { // Invoke the classlib fail fast function. CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, IntPtr.Zero, IntPtr.Zero); } catch { // disallow all exceptions leaking out of callbacks } // The classlib's function should never return and should not throw. If it does, then we fail our way... FallbackFailFast(reason, unhandledException); } #if AMD64 [StructLayout(LayoutKind.Explicit, Size = 0x4d0)] #elif ARM [StructLayout(LayoutKind.Explicit, Size=0x1a0)] #elif X86 [StructLayout(LayoutKind.Explicit, Size=0x2cc)] #else [StructLayout(LayoutKind.Explicit, Size = 0x10)] // this is small enough that it should trip an assert in RhpCopyContextFromExInfo #endif private struct OSCONTEXT { } internal static unsafe void* PointerAlign(void* ptr, int alignmentInBytes) { int alignMask = alignmentInBytes - 1; #if BIT64 return (void*)((((long)ptr) + alignMask) & ~alignMask); #else return (void*)((((int)ptr) + alignMask) & ~alignMask); #endif } private static void OnFirstChanceExceptionViaClassLib(object exception) { IntPtr pOnFirstChanceFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromEEType((IntPtr)exception.m_pEEType, ClassLibFunctionId.OnFirstChance); if (pOnFirstChanceFunction == IntPtr.Zero) { return; } try { CalliIntrinsics.CallVoid(pOnFirstChanceFunction, exception); } catch { // disallow all exceptions leaking out of callbacks } } [MethodImpl(MethodImplOptions.NoInlining)] internal static unsafe void UnhandledExceptionFailFastViaClasslib( RhFailFastReason reason, object unhandledException, IntPtr classlibAddress, ref ExInfo exInfo) { IntPtr pFailFastFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(classlibAddress, ClassLibFunctionId.FailFast); if (pFailFastFunction == IntPtr.Zero) { FailFastViaClasslib( reason, unhandledException, classlibAddress); } // 16-byte align the context. This is overkill on x86 and ARM, but simplifies things slightly. const int contextAlignment = 16; byte* pbBuffer = stackalloc byte[sizeof(OSCONTEXT) + contextAlignment]; void* pContext = PointerAlign(pbBuffer, contextAlignment); InternalCalls.RhpCopyContextFromExInfo(pContext, sizeof(OSCONTEXT), exInfo._pExContext); try { CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, exInfo._pExContext->IP, (IntPtr)pContext); } catch { // disallow all exceptions leaking out of callbacks } // The classlib's funciton should never return and should not throw. If it does, then we fail our way... FallbackFailFast(reason, unhandledException); } private enum RhEHFrameType { RH_EH_FIRST_FRAME = 1, RH_EH_FIRST_RETHROW_FRAME = 2, } private static void AppendExceptionStackFrameViaClasslib(object exception, IntPtr IP, ref bool isFirstRethrowFrame, ref bool isFirstFrame) { IntPtr pAppendStackFrame = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(IP, ClassLibFunctionId.AppendExceptionStackFrame); if (pAppendStackFrame != IntPtr.Zero) { int flags = (isFirstFrame ? (int)RhEHFrameType.RH_EH_FIRST_FRAME : 0) | (isFirstRethrowFrame ? (int)RhEHFrameType.RH_EH_FIRST_RETHROW_FRAME : 0); try { CalliIntrinsics.CallVoid(pAppendStackFrame, exception, IP, flags); } catch { // disallow all exceptions leaking out of callbacks } // Clear flags only if we called the function isFirstRethrowFrame = false; isFirstFrame = false; } } // Given an ExceptionID and an address pointing somewhere into a managed module, get // an exception object of a type that the module containing the given address will understand. // This finds the classlib-defined GetRuntimeException function and asks it for the exception object. internal static Exception GetClasslibException(ExceptionIDs id, IntPtr address) { // Find the classlib function that will give us the exception object we want to throw. This // is a RuntimeExport function from the classlib module, and is therefore managed-callable. IntPtr pGetRuntimeExceptionFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(address, ClassLibFunctionId.GetRuntimeException); // Return the exception object we get from the classlib. Exception e = null; try { e = CalliIntrinsics.Call<Exception>(pGetRuntimeExceptionFunction, id); } catch { // disallow all exceptions leaking out of callbacks } // If the helper fails to yield an object, then we fail-fast. if (e == null) { FailFastViaClasslib( RhFailFastReason.ClassLibDidNotTranslateExceptionID, null, address); } return e; } // Given an ExceptionID and an EEType address, get an exception object of a type that the module containing // the given address will understand. This finds the classlib-defined GetRuntimeException function and asks // it for the exception object. internal static Exception GetClasslibExceptionFromEEType(ExceptionIDs id, IntPtr pEEType) { // Find the classlib function that will give us the exception object we want to throw. This // is a RuntimeExport function from the classlib module, and is therefore managed-callable. IntPtr pGetRuntimeExceptionFunction = IntPtr.Zero; if (pEEType != IntPtr.Zero) { pGetRuntimeExceptionFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromEEType(pEEType, ClassLibFunctionId.GetRuntimeException); } // Return the exception object we get from the classlib. Exception e = null; try { e = CalliIntrinsics.Call<Exception>(pGetRuntimeExceptionFunction, id); } catch { // disallow all exceptions leaking out of callbacks } // If the helper fails to yield an object, then we fail-fast. if (e == null) { FailFastViaClasslib( RhFailFastReason.ClassLibDidNotTranslateExceptionID, null, pEEType); } return e; } // RhExceptionHandling_ functions are used to throw exceptions out of our asm helpers. We tail-call from // the asm helpers to these functions, which performs the throw. The tail-call is important: it ensures that // the stack is crawlable from within these functions. [RuntimeExport("RhExceptionHandling_ThrowClasslibOverflowException")] public static void ThrowClasslibOverflowException(IntPtr address) { // Throw the overflow exception defined by the classlib, using the return address of the asm helper // to find the correct classlib. throw GetClasslibException(ExceptionIDs.Overflow, address); } [RuntimeExport("RhExceptionHandling_ThrowClasslibDivideByZeroException")] public static void ThrowClasslibDivideByZeroException(IntPtr address) { // Throw the divide by zero exception defined by the classlib, using the return address of the asm helper // to find the correct classlib. throw GetClasslibException(ExceptionIDs.DivideByZero, address); } [RuntimeExport("RhExceptionHandling_FailedAllocation")] public static void FailedAllocation(EETypePtr pEEType, bool fIsOverflow) { ExceptionIDs exID = fIsOverflow ? ExceptionIDs.Overflow : ExceptionIDs.OutOfMemory; // Throw the out of memory exception defined by the classlib, using the input EEType* // to find the correct classlib. throw pEEType.ToPointer()->GetClasslibException(exID); } #if !INPLACE_RUNTIME private static OutOfMemoryException s_theOOMException = new OutOfMemoryException(); // MRT exports GetRuntimeException for the few cases where we have a helper that throws an exception // and may be called by either MRT or other classlibs and that helper needs to throw an exception. // There are only a few cases where this happens now (the fast allocation helpers), so we limit the // exception types that MRT will return. [RuntimeExport("GetRuntimeException")] public static Exception GetRuntimeException(ExceptionIDs id) { switch (id) { case ExceptionIDs.OutOfMemory: // Throw a preallocated exception to avoid infinite recursion. return s_theOOMException; case ExceptionIDs.Overflow: return new OverflowException(); case ExceptionIDs.InvalidCast: return new InvalidCastException(); default: Debug.Assert(false, "unexpected ExceptionID"); FallbackFailFast(RhFailFastReason.InternalError, null); return null; } } #endif private enum HwExceptionCode : uint { STATUS_REDHAWK_NULL_REFERENCE = 0x00000000u, STATUS_REDHAWK_WRITE_BARRIER_NULL_REFERENCE = 0x00000042u, STATUS_REDHAWK_THREAD_ABORT = 0x00000043u, STATUS_DATATYPE_MISALIGNMENT = 0x80000002u, STATUS_ACCESS_VIOLATION = 0xC0000005u, STATUS_INTEGER_DIVIDE_BY_ZERO = 0xC0000094u, STATUS_INTEGER_OVERFLOW = 0xC0000095u, } [StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__PAL_LIMITED_CONTEXT)] public struct PAL_LIMITED_CONTEXT { [FieldOffset(AsmOffsets.OFFSETOF__PAL_LIMITED_CONTEXT__IP)] internal IntPtr IP; // the rest of the struct is left unspecified. } // N.B. -- These values are burned into the throw helper assembly code and are also known the the // StackFrameIterator code. [Flags] internal enum ExKind : byte { None = 0, Throw = 1, HardwareFault = 2, KindMask = 3, RethrowFlag = 4, SupersededFlag = 8, InstructionFaultFlag = 0x10 } [StructLayout(LayoutKind.Explicit)] public ref struct ExInfo { internal void Init(object exceptionObj, bool instructionFault = false) { // _pPrevExInfo -- set by asm helper // _pExContext -- set by asm helper // _passNumber -- set by asm helper // _kind -- set by asm helper // _idxCurClause -- set by asm helper // _frameIter -- initialized explicitly during dispatch _exception = exceptionObj; if (instructionFault) _kind |= ExKind.InstructionFaultFlag; _notifyDebuggerSP = UIntPtr.Zero; } internal void Init(object exceptionObj, ref ExInfo rethrownExInfo) { // _pPrevExInfo -- set by asm helper // _pExContext -- set by asm helper // _passNumber -- set by asm helper // _idxCurClause -- set by asm helper // _frameIter -- initialized explicitly during dispatch _exception = exceptionObj; _kind = rethrownExInfo._kind | ExKind.RethrowFlag; _notifyDebuggerSP = UIntPtr.Zero; } internal object ThrownException { get { return _exception; } } [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pPrevExInfo)] internal void* _pPrevExInfo; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pExContext)] internal PAL_LIMITED_CONTEXT* _pExContext; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_exception)] private object _exception; // actual object reference, specially reported by GcScanRootsWorker [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_kind)] internal ExKind _kind; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_passNumber)] internal byte _passNumber; // BEWARE: This field is used by the stackwalker to know if the dispatch code has reached the // point at which a handler is called. In other words, it serves as an "is a handler // active" state where '_idxCurClause == MaxTryRegionIdx' means 'no'. [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_idxCurClause)] internal uint _idxCurClause; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_frameIter)] internal StackFrameIterator _frameIter; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_notifyDebuggerSP)] volatile internal UIntPtr _notifyDebuggerSP; } // // Called by RhpThrowHwEx // [RuntimeExport("RhThrowHwEx")] public static void RhThrowHwEx(uint exceptionCode, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); IntPtr faultingCodeAddress = exInfo._pExContext->IP; bool instructionFault = true; ExceptionIDs exceptionId = default(ExceptionIDs); Exception exceptionToThrow = null; switch (exceptionCode) { case (uint)HwExceptionCode.STATUS_REDHAWK_NULL_REFERENCE: exceptionId = ExceptionIDs.NullReference; break; case (uint)HwExceptionCode.STATUS_REDHAWK_WRITE_BARRIER_NULL_REFERENCE: // The write barrier where the actual fault happened has been unwound already. // The IP of this fault needs to be treated as return address, not as IP of // faulting instruction. instructionFault = false; exceptionId = ExceptionIDs.NullReference; break; case (uint)HwExceptionCode.STATUS_REDHAWK_THREAD_ABORT: exceptionToThrow = InternalCalls.RhpGetThreadAbortException(); break; case (uint)HwExceptionCode.STATUS_DATATYPE_MISALIGNMENT: exceptionId = ExceptionIDs.DataMisaligned; break; // N.B. -- AVs that have a read/write address lower than 64k are already transformed to // HwExceptionCode.REDHAWK_NULL_REFERENCE prior to calling this routine. case (uint)HwExceptionCode.STATUS_ACCESS_VIOLATION: exceptionId = ExceptionIDs.AccessViolation; break; case (uint)HwExceptionCode.STATUS_INTEGER_DIVIDE_BY_ZERO: exceptionId = ExceptionIDs.DivideByZero; break; case (uint)HwExceptionCode.STATUS_INTEGER_OVERFLOW: exceptionId = ExceptionIDs.Overflow; break; default: // We don't wrap SEH exceptions from foreign code like CLR does, so we believe that we // know the complete set of HW faults generated by managed code and do not need to handle // this case. FailFastViaClasslib(RhFailFastReason.InternalError, null, faultingCodeAddress); break; } if (exceptionId != default(ExceptionIDs)) { exceptionToThrow = GetClasslibException(exceptionId, faultingCodeAddress); } exInfo.Init(exceptionToThrow, instructionFault); DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx); FallbackFailFast(RhFailFastReason.InternalError, null); } private const uint MaxTryRegionIdx = 0xFFFFFFFFu; [RuntimeExport("RhThrowEx")] public static void RhThrowEx(object exceptionObj, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); // Transform attempted throws of null to a throw of NullReferenceException. if (exceptionObj == null) { IntPtr faultingCodeAddress = exInfo._pExContext->IP; exceptionObj = GetClasslibException(ExceptionIDs.NullReference, faultingCodeAddress); } exInfo.Init(exceptionObj); DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx); FallbackFailFast(RhFailFastReason.InternalError, null); } [RuntimeExport("RhRethrow")] public static void RhRethrow(ref ExInfo activeExInfo, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); // We need to copy the exception object to this stack location because collided unwinds // will cause the original stack location to go dead. object rethrownException = activeExInfo.ThrownException; exInfo.Init(rethrownException, ref activeExInfo); DispatchEx(ref exInfo._frameIter, ref exInfo, activeExInfo._idxCurClause); FallbackFailFast(RhFailFastReason.InternalError, null); } private static void DispatchEx(ref StackFrameIterator frameIter, ref ExInfo exInfo, uint startIdx) { Debug.Assert(exInfo._passNumber == 1, "expected asm throw routine to set the pass"); object exceptionObj = exInfo.ThrownException; // ------------------------------------------------ // // First pass // // ------------------------------------------------ UIntPtr handlingFrameSP = MaxSP; byte* pCatchHandler = null; uint catchingTryRegionIdx = MaxTryRegionIdx; bool isFirstRethrowFrame = (startIdx != MaxTryRegionIdx); bool isFirstFrame = true; byte* prevControlPC = null; UIntPtr prevFramePtr = UIntPtr.Zero; bool unwoundReversePInvoke = false; bool isValid = frameIter.Init(exInfo._pExContext, (exInfo._kind & ExKind.InstructionFaultFlag) != 0); Debug.Assert(isValid, "RhThrowEx called with an unexpected context"); OnFirstChanceExceptionViaClassLib(exceptionObj); DebuggerNotify.BeginFirstPass(exceptionObj, frameIter.ControlPC, frameIter.SP); for (; isValid; isValid = frameIter.Next(out startIdx, out unwoundReversePInvoke)) { // For GC stackwalking, we'll happily walk across native code blocks, but for EH dispatch, we // disallow dispatching exceptions across native code. if (unwoundReversePInvoke) break; prevControlPC = frameIter.ControlPC; DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP); // A debugger can subscribe to get callbacks at a specific frame of exception dispatch // exInfo._notifyDebuggerSP can be populated by the debugger from out of process // at any time. if (exInfo._notifyDebuggerSP == frameIter.SP) DebuggerNotify.FirstPassFrameEntered(exceptionObj, frameIter.ControlPC, frameIter.SP); UpdateStackTrace(exceptionObj, ref exInfo, ref isFirstRethrowFrame, ref prevFramePtr, ref isFirstFrame); byte* pHandler; if (FindFirstPassHandler(exceptionObj, startIdx, ref frameIter, out catchingTryRegionIdx, out pHandler)) { handlingFrameSP = frameIter.SP; pCatchHandler = pHandler; DebugVerifyHandlingFrame(handlingFrameSP); break; } } DebuggerNotify.EndFirstPass(exceptionObj, pCatchHandler, handlingFrameSP); if (pCatchHandler == null) { UnhandledExceptionFailFastViaClasslib( RhFailFastReason.PN_UnhandledException, exceptionObj, (IntPtr)prevControlPC, // IP of the last frame that did not handle the exception ref exInfo); } // We FailFast above if the exception goes unhandled. Therefore, we cannot run the second pass // without a catch handler. Debug.Assert(pCatchHandler != null, "We should have a handler if we're starting the second pass"); DebuggerNotify.BeginSecondPass(); // ------------------------------------------------ // // Second pass // // ------------------------------------------------ // Due to the stackwalker logic, we cannot tolerate triggering a GC from the dispatch code once we // are in the 2nd pass. This is because the stackwalker applies a particular unwind semantic to // 'collapse' funclets which gets confused when we walk out of the dispatch code and encounter the // 'main body' without first encountering the funclet. The thunks used to invoke 2nd-pass // funclets will always toggle this mode off before invoking them. InternalCalls.RhpSetThreadDoNotTriggerGC(); exInfo._passNumber = 2; startIdx = MaxTryRegionIdx; isValid = frameIter.Init(exInfo._pExContext, (exInfo._kind & ExKind.InstructionFaultFlag) != 0); for (; isValid && ((byte*)frameIter.SP <= (byte*)handlingFrameSP); isValid = frameIter.Next(out startIdx)) { Debug.Assert(isValid, "second-pass EH unwind failed unexpectedly"); DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP); if (frameIter.SP == handlingFrameSP) { // invoke only a partial second-pass here... InvokeSecondPass(ref exInfo, startIdx, catchingTryRegionIdx); break; } InvokeSecondPass(ref exInfo, startIdx); } // ------------------------------------------------ // // Call the handler and resume execution // // ------------------------------------------------ exInfo._idxCurClause = catchingTryRegionIdx; InternalCalls.RhpCallCatchFunclet( exceptionObj, pCatchHandler, frameIter.RegisterSet, ref exInfo); // currently, RhpCallCatchFunclet will resume after the catch Debug.Assert(false, "unreachable"); FallbackFailFast(RhFailFastReason.InternalError, null); } [System.Diagnostics.Conditional("DEBUG")] private static void DebugScanCallFrame(int passNumber, byte* ip, UIntPtr sp) { Debug.Assert(ip != null, "IP address must not be null"); } [System.Diagnostics.Conditional("DEBUG")] private static void DebugVerifyHandlingFrame(UIntPtr handlingFrameSP) { Debug.Assert(handlingFrameSP != MaxSP, "Handling frame must have an SP value"); Debug.Assert(((UIntPtr*)handlingFrameSP) > &handlingFrameSP, "Handling frame must have a valid stack frame pointer"); } private static void UpdateStackTrace(object exceptionObj, ref ExInfo exInfo, ref bool isFirstRethrowFrame, ref UIntPtr prevFramePtr, ref bool isFirstFrame) { // We use the fact that all funclet stack frames belonging to the same logical method activation // will have the same FramePointer value. Additionally, the stackwalker will return a sequence of // callbacks for all the funclet stack frames, one right after the other. The classlib doesn't // want to know about funclets, so we strip them out by only reporting the first frame of a // sequence of funclets. This is correct because the leafmost funclet is first in the sequence // and corresponds to the current 'IP state' of the method. UIntPtr curFramePtr = exInfo._frameIter.FramePointer; if ((prevFramePtr == UIntPtr.Zero) || (curFramePtr != prevFramePtr)) { AppendExceptionStackFrameViaClasslib(exceptionObj, (IntPtr)exInfo._frameIter.ControlPC, ref isFirstRethrowFrame, ref isFirstFrame); } prevFramePtr = curFramePtr; } private static bool FindFirstPassHandler(object exception, uint idxStart, ref StackFrameIterator frameIter, out uint tryRegionIdx, out byte* pHandler) { pHandler = null; tryRegionIdx = MaxTryRegionIdx; EHEnum ehEnum; byte* pbMethodStartAddress; if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref frameIter, &pbMethodStartAddress, &ehEnum)) return false; byte* pbControlPC = frameIter.ControlPC; uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress); uint lastTryStart = 0, lastTryEnd = 0; // Search the clauses for one that contains the current offset. RhEHClause ehClause; for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause); curIdx++) { // // Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where // the previous dispatch left off. // if (idxStart != MaxTryRegionIdx) { if (curIdx <= idxStart) { lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset; continue; } // Now, we continue skipping while the try region is identical to the one that invoked the // previous dispatch. if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd)) continue; // We are done skipping. This is required to handle empty finally block markers that are used // to separate runs of different try blocks with same native code offsets. idxStart = MaxTryRegionIdx; } RhEHClauseKind clauseKind = ehClause._clauseKind; if (((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_TYPED) && (clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FILTER)) || !ehClause.ContainsCodeOffset(codeOffset)) { continue; } // Found a containing clause. Because of the order of the clauses, we know this is the // most containing. if (clauseKind == RhEHClauseKind.RH_EH_CLAUSE_TYPED) { if (ShouldTypedClauseCatchThisException(exception, (EEType*)ehClause._pTargetType)) { pHandler = ehClause._handlerAddress; tryRegionIdx = curIdx; return true; } } else { byte* pFilterFunclet = ehClause._filterAddress; bool shouldInvokeHandler = InternalCalls.RhpCallFilterFunclet(exception, pFilterFunclet, frameIter.RegisterSet); if (shouldInvokeHandler) { pHandler = ehClause._handlerAddress; tryRegionIdx = curIdx; return true; } } } return false; } private static EEType* s_pLowLevelObjectType; private static bool ShouldTypedClauseCatchThisException(object exception, EEType* pClauseType) { if (TypeCast.IsInstanceOfClass(exception, pClauseType) != null) return true; if (s_pLowLevelObjectType == null) { // TODO: Avoid allocating here as that may fail s_pLowLevelObjectType = new System.Object().EEType; } // This allows the typical try { } catch { }--which expands to a typed catch of System.Object--to work on // all objects when the clause is in the low level runtime code. This special case is needed because // objects from foreign type systems are sometimes throw back up at runtime code and this is the only way // to catch them outside of having a filter with no type check in it, which isn't currently possible to // write in C#. See https://github.com/dotnet/roslyn/issues/4388 if (pClauseType->IsEquivalentTo(s_pLowLevelObjectType)) return true; return false; } private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart) { InvokeSecondPass(ref exInfo, idxStart, MaxTryRegionIdx); } private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart, uint idxLimit) { EHEnum ehEnum; byte* pbMethodStartAddress; if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref exInfo._frameIter, &pbMethodStartAddress, &ehEnum)) return; byte* pbControlPC = exInfo._frameIter.ControlPC; uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress); uint lastTryStart = 0, lastTryEnd = 0; // Search the clauses for one that contains the current offset. RhEHClause ehClause; for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause) && curIdx < idxLimit; curIdx++) { // // Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where // the previous dispatch left off. // if (idxStart != MaxTryRegionIdx) { if (curIdx <= idxStart) { lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset; continue; } // Now, we continue skipping while the try region is identical to the one that invoked the // previous dispatch. if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd)) continue; // We are done skipping. This is required to handle empty finally block markers that are used // to separate runs of different try blocks with same native code offsets. idxStart = MaxTryRegionIdx; } RhEHClauseKind clauseKind = ehClause._clauseKind; if ((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FAULT) || !ehClause.ContainsCodeOffset(codeOffset)) { continue; } // Found a containing clause. Because of the order of the clauses, we know this is the // most containing. // N.B. -- We need to suppress GC "in-between" calls to finallys in this loop because we do // not have the correct next-execution point live on the stack and, therefore, may cause a GC // hole if we allow a GC between invocation of finally funclets (i.e. after one has returned // here to the dispatcher, but before the next one is invoked). Once they are running, it's // fine for them to trigger a GC, obviously. // // As a result, RhpCallFinallyFunclet will set this state in the runtime upon return from the // funclet, and we need to reset it if/when we fall out of the loop and we know that the // method will no longer get any more GC callbacks. byte* pFinallyHandler = ehClause._handlerAddress; exInfo._idxCurClause = curIdx; InternalCalls.RhpCallFinallyFunclet(pFinallyHandler, exInfo._frameIter.RegisterSet); exInfo._idxCurClause = MaxTryRegionIdx; } } [NativeCallable(EntryPoint = "RhpFailFastForPInvokeExceptionPreemp", CallingConvention = CallingConvention.Cdecl)] public static void RhpFailFastForPInvokeExceptionPreemp(IntPtr PInvokeCallsiteReturnAddr, void* pExceptionRecord, void* pContextRecord) { FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, PInvokeCallsiteReturnAddr); } [RuntimeExport("RhpFailFastForPInvokeExceptionCoop")] public static void RhpFailFastForPInvokeExceptionCoop(IntPtr classlibBreadcrumb, void* pExceptionRecord, void* pContextRecord) { FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, classlibBreadcrumb); } } // static class EH }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Accord.Math; using Python.Runtime; using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Scheduling; using QuantConnect.Util; namespace QuantConnect.Algorithm.Framework.Portfolio { /// <summary> /// Provides an implementation of Mean-Variance portfolio optimization based on modern portfolio theory. /// The interval of weights in optimization method can be changed based on the long-short algorithm. /// The default model uses the last three months daily price to calculate the optimal weight /// with the weight range from -1 to 1 and minimize the portfolio variance with a target return of 2% /// </summary> public class MeanVarianceOptimizationPortfolioConstructionModel : PortfolioConstructionModel { private readonly int _lookback; private readonly int _period; private readonly Resolution _resolution; private readonly PortfolioBias _portfolioBias; private readonly IPortfolioOptimizer _optimizer; private readonly Dictionary<Symbol, ReturnsSymbolData> _symbolDataDict; /// <summary> /// Initialize the model /// </summary> /// <param name="rebalancingDateRules">The date rules used to define the next expected rebalance time /// in UTC</param> /// <param name="portfolioBias">Specifies the bias of the portfolio (Short, Long/Short, Long)</param> /// <param name="lookback">Historical return lookback period</param> /// <param name="period">The time interval of history price to calculate the weight</param> /// <param name="resolution">The resolution of the history price</param> /// <param name="targetReturn">The target portfolio return</param> /// <param name="optimizer">The portfolio optimization algorithm. If the algorithm is not provided then the default will be mean-variance optimization.</param> public MeanVarianceOptimizationPortfolioConstructionModel(IDateRule rebalancingDateRules, PortfolioBias portfolioBias = PortfolioBias.LongShort, int lookback = 1, int period = 63, Resolution resolution = Resolution.Daily, double targetReturn = 0.02, IPortfolioOptimizer optimizer = null) : this(rebalancingDateRules.ToFunc(), portfolioBias, lookback, period, resolution, targetReturn, optimizer) { } /// <summary> /// Initialize the model /// </summary> /// <param name="rebalanceResolution">Rebalancing frequency</param> /// <param name="portfolioBias">Specifies the bias of the portfolio (Short, Long/Short, Long)</param> /// <param name="lookback">Historical return lookback period</param> /// <param name="period">The time interval of history price to calculate the weight</param> /// <param name="resolution">The resolution of the history price</param> /// <param name="targetReturn">The target portfolio return</param> /// <param name="optimizer">The portfolio optimization algorithm. If the algorithm is not provided then the default will be mean-variance optimization.</param> public MeanVarianceOptimizationPortfolioConstructionModel(Resolution rebalanceResolution = Resolution.Daily, PortfolioBias portfolioBias = PortfolioBias.LongShort, int lookback = 1, int period = 63, Resolution resolution = Resolution.Daily, double targetReturn = 0.02, IPortfolioOptimizer optimizer = null) : this(rebalanceResolution.ToTimeSpan(), portfolioBias, lookback, period, resolution, targetReturn, optimizer) { } /// <summary> /// Initialize the model /// </summary> /// <param name="timeSpan">Rebalancing frequency</param> /// <param name="portfolioBias">Specifies the bias of the portfolio (Short, Long/Short, Long)</param> /// <param name="lookback">Historical return lookback period</param> /// <param name="period">The time interval of history price to calculate the weight</param> /// <param name="resolution">The resolution of the history price</param> /// <param name="targetReturn">The target portfolio return</param> /// <param name="optimizer">The portfolio optimization algorithm. If the algorithm is not provided then the default will be mean-variance optimization.</param> public MeanVarianceOptimizationPortfolioConstructionModel(TimeSpan timeSpan, PortfolioBias portfolioBias = PortfolioBias.LongShort, int lookback = 1, int period = 63, Resolution resolution = Resolution.Daily, double targetReturn = 0.02, IPortfolioOptimizer optimizer = null) : this(dt => dt.Add(timeSpan), portfolioBias, lookback, period, resolution, targetReturn, optimizer) { } /// <summary> /// Initialize the model /// </summary> /// <param name="rebalance">Rebalancing func or if a date rule, timedelta will be converted into func. /// For a given algorithm UTC DateTime the func returns the next expected rebalance time /// or null if unknown, in which case the function will be called again in the next loop. Returning current time /// will trigger rebalance. If null will be ignored</param> /// <param name="portfolioBias">Specifies the bias of the portfolio (Short, Long/Short, Long)</param> /// <param name="lookback">Historical return lookback period</param> /// <param name="period">The time interval of history price to calculate the weight</param> /// <param name="resolution">The resolution of the history price</param> /// <param name="targetReturn">The target portfolio return</param> /// <param name="optimizer">The portfolio optimization algorithm. If the algorithm is not provided then the default will be mean-variance optimization.</param> /// <remarks>This is required since python net can not convert python methods into func nor resolve the correct /// constructor for the date rules parameter. /// For performance we prefer python algorithms using the C# implementation</remarks> public MeanVarianceOptimizationPortfolioConstructionModel(PyObject rebalance, PortfolioBias portfolioBias = PortfolioBias.LongShort, int lookback = 1, int period = 63, Resolution resolution = Resolution.Daily, double targetReturn = 0.02, IPortfolioOptimizer optimizer = null) : this((Func<DateTime, DateTime?>)null, portfolioBias, lookback, period, resolution, targetReturn, optimizer) { SetRebalancingFunc(rebalance); } /// <summary> /// Initialize the model /// </summary> /// <param name="rebalancingFunc">For a given algorithm UTC DateTime returns the next expected rebalance UTC time. /// Returning current time will trigger rebalance. If null will be ignored</param> /// <param name="portfolioBias">Specifies the bias of the portfolio (Short, Long/Short, Long)</param> /// <param name="lookback">Historical return lookback period</param> /// <param name="period">The time interval of history price to calculate the weight</param> /// <param name="resolution">The resolution of the history price</param> /// <param name="targetReturn">The target portfolio return</param> /// <param name="optimizer">The portfolio optimization algorithm. If the algorithm is not provided then the default will be mean-variance optimization.</param> public MeanVarianceOptimizationPortfolioConstructionModel(Func<DateTime, DateTime> rebalancingFunc, PortfolioBias portfolioBias = PortfolioBias.LongShort, int lookback = 1, int period = 63, Resolution resolution = Resolution.Daily, double targetReturn = 0.02, IPortfolioOptimizer optimizer = null) : this(rebalancingFunc != null ? (Func<DateTime, DateTime?>)(timeUtc => rebalancingFunc(timeUtc)) : null, portfolioBias, lookback, period, resolution, targetReturn, optimizer) { } /// <summary> /// Initialize the model /// </summary> /// <param name="rebalancingFunc">For a given algorithm UTC DateTime returns the next expected rebalance time /// or null if unknown, in which case the function will be called again in the next loop. Returning current time /// will trigger rebalance.</param> /// <param name="portfolioBias">Specifies the bias of the portfolio (Short, Long/Short, Long)</param> /// <param name="lookback">Historical return lookback period</param> /// <param name="period">The time interval of history price to calculate the weight</param> /// <param name="resolution">The resolution of the history price</param> /// <param name="targetReturn">The target portfolio return</param> /// <param name="optimizer">The portfolio optimization algorithm. If the algorithm is not provided then the default will be mean-variance optimization.</param> public MeanVarianceOptimizationPortfolioConstructionModel(Func<DateTime, DateTime?> rebalancingFunc, PortfolioBias portfolioBias = PortfolioBias.LongShort, int lookback = 1, int period = 63, Resolution resolution = Resolution.Daily, double targetReturn = 0.02, IPortfolioOptimizer optimizer = null) : base(rebalancingFunc) { _lookback = lookback; _period = period; _resolution = resolution; _portfolioBias = portfolioBias; var lower = portfolioBias == PortfolioBias.Long ? 0 : -1; var upper = portfolioBias == PortfolioBias.Short ? 0 : 1; _optimizer = optimizer ?? new MinimumVariancePortfolioOptimizer(lower, upper, targetReturn); _symbolDataDict = new Dictionary<Symbol, ReturnsSymbolData>(); } /// <summary> /// Method that will determine if the portfolio construction model should create a /// target for this insight /// </summary> /// <param name="insight">The insight to create a target for</param> /// <returns>True if the portfolio should create a target for the insight</returns> protected override bool ShouldCreateTargetForInsight(Insight insight) { var filteredInsight = FilterInvalidInsightMagnitude(Algorithm, new[] { insight }).FirstOrDefault(); if (filteredInsight == null) { return false; } ReturnsSymbolData data; if (_symbolDataDict.TryGetValue(insight.Symbol, out data)) { if (!insight.Magnitude.HasValue) { Algorithm.SetRunTimeError( new ArgumentNullException( insight.Symbol.Value, "MeanVarianceOptimizationPortfolioConstructionModel does not accept 'null' as Insight.Magnitude. " + "Please checkout the selected Alpha Model specifications: " + insight.SourceModel)); return false; } data.Add(Algorithm.Time, insight.Magnitude.Value.SafeDecimalCast()); } return true; } /// <summary> /// Will determine the target percent for each insight /// </summary> /// <param name="activeInsights">The active insights to generate a target for</param> /// <returns>A target percent for each insight</returns> protected override Dictionary<Insight, double> DetermineTargetPercent(List<Insight> activeInsights) { var targets = new Dictionary<Insight, double>(); // If we have no insights just return an empty target list if (activeInsights.IsNullOrEmpty()) { return targets; } var symbols = activeInsights.Select(x => x.Symbol).ToList(); // Get symbols' returns var returns = _symbolDataDict.FormReturnsMatrix(symbols); // Calculate rate of returns var rreturns = returns.Apply(e => Math.Pow(1.0 + e, 252.0) - 1.0); // The optimization method processes the data frame var w = _optimizer.Optimize(rreturns); // process results if (w.Length > 0) { var sidx = 0; foreach (var symbol in symbols) { var weight = w[sidx]; // don't trust the optimizer if (_portfolioBias != PortfolioBias.LongShort && Math.Sign(weight) != (int)_portfolioBias) { weight = 0; } targets[activeInsights.First(insight => insight.Symbol == symbol)] = weight; sidx++; } } return targets; } /// <summary> /// Event fired each time the we add/remove securities from the data feed /// </summary> /// <param name="algorithm">The algorithm instance that experienced the change in securities</param> /// <param name="changes">The security additions and removals from the algorithm</param> public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes) { base.OnSecuritiesChanged(algorithm, changes); // clean up data for removed securities foreach (var removed in changes.RemovedSecurities) { ReturnsSymbolData data; if (_symbolDataDict.TryGetValue(removed.Symbol, out data)) { _symbolDataDict.Remove(removed.Symbol); } } if (changes.AddedSecurities.Count == 0) return; // initialize data for added securities foreach (var added in changes.AddedSecurities) { if (!_symbolDataDict.ContainsKey(added.Symbol)) { var symbolData = new ReturnsSymbolData(added.Symbol, _lookback, _period); _symbolDataDict[added.Symbol] = symbolData; } } // warmup our indicators by pushing history through the consolidators algorithm.History(changes.AddedSecurities.Select(security => security.Symbol), _lookback * _period, _resolution) .PushThrough(bar => { ReturnsSymbolData symbolData; if (_symbolDataDict.TryGetValue(bar.Symbol, out symbolData)) { symbolData.Update(bar.EndTime, bar.Value); } }); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SQLite; using System.Linq; using System.Reflection; using System.Text; using DatabaseApi.Logging; namespace DatabaseApi.SqlLite.Api { public abstract class SqlTable<T> : ISqlTable { protected List<ISqlColumn> Columns; protected List<SqlForeignKey> ForeignKeys = new List<SqlForeignKey>(); protected DatabaseSchema DatabaseSchema { get; } protected SqlTable(DatabaseSchema databaseSchema) { DatabaseSchema = databaseSchema; } #region SqlTable Creation public string BuildCreateQuery() { List<string> columnsAndKeys = new List<string>(); columnsAndKeys.AddRange(Columns.Select(c => c.BuildCreateQuery())); columnsAndKeys.AddRange(ForeignKeys.Select(f => f.BuildCreateQuery())); string columns = columnsAndKeys.Implode(", "); string creationQuery = $"CREATE TABLE IF NOT EXISTS {GetTableName()} ({columns});"; return creationQuery; } #endregion public abstract string GetTableName(); #region SqlTable Data Retrieval public List<K> GetAll<K>() { var sqlColumnBindings = GetColumnBindings(typeof(K)); string columnNames = sqlColumnBindings.Select(b => b.Column.Name).Implode(", "); string query = $"SELECT {columnNames} FROM {GetTableName()}"; SQLiteDataReader result = DatabaseSchema.ExecuteQuery(query); var allTableData = new List<K>(); while (result.Read()) { K dataObject = Activator.CreateInstance<K>(); sqlColumnBindings.ForEach(b => { string columnName = b.Column.Name; var value = b.Column.ParseValue(result[columnName]); b.PropertyInfo.SetValue(dataObject, value); }); allTableData.Add(dataObject); } return allTableData; } #endregion #region SqlTable Data Creation public void Create(List<T> dataObjects) { if (dataObjects.Any()) { var sqlColumnBindings = GetColumnBindings(dataObjects[0].GetType()); string columnNames = sqlColumnBindings.Where(b => !b.Column.IsPrimaryKey).Select(b => b.Column.Name).Implode(", "); var stringBuilder = new StringBuilder(); stringBuilder.Append($"INSERT INTO {GetTableName()} "); stringBuilder.Append($"({columnNames}) "); string data = dataObjects.Select(p => CreateQueryForSingleInsert(p, sqlColumnBindings)).Implode(", "); stringBuilder.Append($" VALUES ({data})"); stringBuilder.Append(";"); var query = stringBuilder.ToString(); DatabaseSchema.ExecuteNonQuery(query); dataObjects.ForEach(d => GetPrimaryKeyFor(d, sqlColumnBindings)); } } private static string CreateQueryForSingleInsert(object dataObject, List<SqlColumnBinding> sqlColumnBindings) { return sqlColumnBindings .Where(b => !b.Column.IsPrimaryKey) .Select(b => { var value = b.PropertyInfo.GetValue(dataObject); return b.Column.EncapsulateValue(value); }) .Implode(", "); } #endregion #region SqlTable Utility Methods private void GetPrimaryKeyFor(T dataObject, List<SqlColumnBinding> sqlColumnBindings) { var primaryKeyColumn = sqlColumnBindings.FirstOrDefault(b => b.Column.IsPrimaryKey); var stringBuilder = new StringBuilder(); stringBuilder.Append("SELECT "); stringBuilder.Append(primaryKeyColumn.Column.Name); stringBuilder.Append(" FROM "); stringBuilder.Append(GetTableName()); stringBuilder.Append(" WHERE "); List<string> columnNameValuePairs = new List<string>(); foreach (var sqlColumnBinding in sqlColumnBindings) { if (!sqlColumnBinding.Column.IsPrimaryKey) { string columnName = sqlColumnBinding.Column.Name; string value = sqlColumnBinding.EncapsulateValue(dataObject); string eq = value.Equals("NULL") ? "IS" : "="; columnNameValuePairs.Add($"{columnName} {eq} {value}"); } } string conditions = columnNameValuePairs.Implode(" AND "); stringBuilder.Append(conditions); stringBuilder.Append(";"); string query = stringBuilder.ToString(); var result = DatabaseSchema.ExecuteScalar(query); int pkValue = int.Parse(result.ToString()); primaryKeyColumn.SetValue(dataObject, pkValue); } private SqlColumnBinding GetPrimaryKeyBinding(List<SqlColumnBinding> sqlColumnBindings) { var primaryKeyBinding = sqlColumnBindings.FirstOrDefault(b => b.Column.IsPrimaryKey); if (primaryKeyBinding == null) { string errorMessage = $"Attempted to use primary key " + $"in table '{GetTableName()}', but the table schema has no primary key " + $"column or one is not defined on the model class."; throw new InvalidSqlBindingException(errorMessage); } return primaryKeyBinding; } private List<SqlColumnBinding> GetColumnBindings(Type objectType) { var sqlColumnBindings = new List<SqlColumnBinding>(); var properties = objectType.GetProperties(); foreach (PropertyInfo propertyInfo in properties) { var customAttributes = propertyInfo.GetCustomAttributes(true); foreach (var customAttribute in customAttributes) { var bindingAttribute = customAttribute as SqlColumnBindingAttribute; if (bindingAttribute != null) { ISqlColumn column = FindColumn(bindingAttribute); if (column != null) { bool isNullable = propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>); if (column.IsPrimaryKey && !isNullable) { string errorMessage = $"The Property {propertyInfo.Name} is attempting to bind to column " + $"{column.Name} in table {GetTableName()}. This column is" + $"designated as the primary key, but the property is not nullable. This is required" + $"for detecting insertions and updates."; throw new InvalidSqlBindingException(errorMessage); } sqlColumnBindings.Add(new SqlColumnBinding(bindingAttribute, propertyInfo, column)); } else { var errorMessage = $"Invalid binding: The table {GetTableName()} could not find a column " + $"definition for the SqlColumnBindingAttribute of'{bindingAttribute.ColumnName}'"; throw new InvalidSqlBindingException(errorMessage); } } } } return sqlColumnBindings; } private ISqlColumn FindColumn(SqlColumnBindingAttribute bindingAttribute) { return Columns.FirstOrDefault(c => c.Name.Equals(bindingAttribute.ColumnName)); } #endregion #region SqlTable Data Update public void SaveAll(List<T> dataObjects) { dataObjects.ForEach(Save); } public void Save(T dataObject) { var sqlColumnBindings = GetColumnBindings(dataObject.GetType()); var primaryKeyBinding = GetPrimaryKeyBinding(sqlColumnBindings); var primaryKeyValue = primaryKeyBinding.PropertyInfo.GetValue(dataObject); var pkColumnName = primaryKeyBinding.Column.Name; if (primaryKeyValue == null) { Create(new List<T> { dataObject }); } else { var primaryKeyValueString = primaryKeyBinding.Column.EncapsulateValue(primaryKeyValue); string query = BuildUpdateQuery(dataObject, sqlColumnBindings, pkColumnName, primaryKeyValueString); DatabaseSchema.ExecuteNonQuery(query); } } private string BuildUpdateQuery(T dataObject, List<SqlColumnBinding> sqlColumnBindings, string pkColumnName, string primaryKeyValue) { string setters = sqlColumnBindings .Where(b => !b.Column.IsPrimaryKey) .Select(b => { var columnName = b.Column.Name; var value = b.Column.EncapsulateValue(b.PropertyInfo.GetValue(dataObject)); return $"{columnName} = {value}"; }) .Implode(", "); string query = $"UPDATE {GetTableName()} SET {setters} WHERE {pkColumnName} = {primaryKeyValue}"; return query; } public void DataChanged(object valueObject, PropertyChangedEventArgs e) { try { if (!typeof(T).Equals(valueObject.GetType())) { string errorMessage = $"Attempted to update table {GetTableName()} with an object of type {valueObject.GetType()}, " + $"however this table is bound to objects of type {typeof(T)}"; throw new InvalidSqlBindingException(errorMessage); } var propertyName = e.PropertyName; var propertyThatChanged = valueObject.GetType().GetProperty(propertyName); var newValue = propertyThatChanged.GetValue(valueObject); var sqlColumnBindings = GetColumnBindings(valueObject.GetType()); var sqlColumnBinding = sqlColumnBindings.FirstOrDefault(b => b.PropertyInfo.Equals(propertyThatChanged)); var primaryKeyBinding = GetPrimaryKeyBinding(sqlColumnBindings); if (sqlColumnBinding == null) { string errorMessage = $"Attepted to update a property, but table '{GetTableName()}' does not have a column bound " + $"to the property '{propertyName}'"; throw new InvalidSqlBindingException(errorMessage); } var valueString = primaryKeyBinding?.Column.EncapsulateValue(newValue); var columnName = sqlColumnBinding?.Column.Name; var primaryKey = primaryKeyBinding?.Column.Name; var pkValue = primaryKeyBinding?.PropertyInfo.GetValue(valueObject); string query = $"UPDATE {GetTableName()} SET {columnName} = {valueString} WHERE {primaryKey} = {pkValue}"; int result = DatabaseSchema.ExecuteNonQuery(query); } catch (InvalidSqlBindingException exception) { DatabaseLogger.Instance.Log(exception); } } #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.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class ReadChar : PortsTest { //The number of random bytes to receive for large input buffer testing // This was 4096, but the largest buffer setting on FTDI USB-Serial devices is "4096", which actually only allows a read of 4094 or 4095 bytes // The test code assumes that we will be able to do this transfer as a single read, so 4000 is safer and would seem to be about // as rigourous a test private const int largeNumRndBytesToRead = 4000; //The number of random characters to receive private const int numRndChar = 8; private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; #region Test Cases [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ASCIIEncoding() { Debug.WriteLine("Verifying read with bytes encoded with ASCIIEncoding"); VerifyRead(new ASCIIEncoding()); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void UTF8Encoding() { Debug.WriteLine("Verifying read with bytes encoded with UTF8Encoding"); VerifyRead(new UTF8Encoding()); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void UTF32Encoding() { Debug.WriteLine("Verifying read with bytes encoded with UTF32Encoding"); VerifyRead(new UTF32Encoding()); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_ReadBufferedData() { VerifyRead(Encoding.ASCII, ReadDataFromEnum.Buffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_IterativeReadBufferedData() { VerifyRead(Encoding.ASCII, ReadDataFromEnum.Buffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_ReadBufferedAndNonBufferedData() { VerifyRead(Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_IterativeReadBufferedAndNonBufferedData() { VerifyRead(Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadTimeout_Zero_ResizeBuffer() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { byte[] byteXmitBuffer = new byte[1024]; char utf32Char = 'A'; byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); char[] charXmitBuffer = TCSupport.GetRandomChars(16, false); char[] expectedChars = new char[charXmitBuffer.Length + 1]; Debug.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer"); expectedChars[0] = utf32Char; Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); //Put the first byte of the utf32 encoder char in the last byte of this buffer //when we read this later the buffer will have to be resized byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; com1.ReadTimeout = 0; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length); //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so //the other 3 bytes of the ut32 encoded char can be in the buffer com1.Read(new char[1023], 0, 1023); Assert.Equal(1, com1.BytesToRead); com1.Encoding = Encoding.UTF32; byteXmitBuffer = Encoding.UTF32.GetBytes(charXmitBuffer); Assert.Throws<TimeoutException>(() => com1.ReadChar()); Assert.Equal(1, com1.BytesToRead); com2.Write(utf32CharBytes, 1, 3); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length); PerformReadOnCom1FromCom2(com1, com2, expectedChars); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadTimeout_NonZero_ResizeBuffer() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { byte[] byteXmitBuffer = new byte[1024]; char utf32Char = 'A'; byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); char[] charXmitBuffer = TCSupport.GetRandomChars(16, false); char[] expectedChars = new char[charXmitBuffer.Length + 1]; Debug.WriteLine("Verifying Read method with non zero timeout that resizes SerialPort's buffer"); expectedChars[0] = utf32Char; Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); //Put the first byte of the utf32 encoder char in the last byte of this buffer //when we read this later the buffer will have to be resized byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; com1.ReadTimeout = 500; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length); //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so //the other 3 bytes of the ut32 encoded char can be in the buffer com1.Read(new char[1023], 0, 1023); Assert.Equal(1, com1.BytesToRead); com1.Encoding = Encoding.UTF32; byteXmitBuffer = Encoding.UTF32.GetBytes(charXmitBuffer); Assert.Throws<TimeoutException>(() => com1.ReadChar()); Assert.Equal(1, com1.BytesToRead); com2.Write(utf32CharBytes, 1, 3); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length); PerformReadOnCom1FromCom2(com1, com2, expectedChars); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void GreedyRead() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { byte[] byteXmitBuffer = new byte[1024]; char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); int charRead; Debug.WriteLine("Verifying that ReadChar() will read everything from internal buffer and drivers buffer"); //Put the first byte of the utf32 encoder char in the last byte of this buffer //when we read this later the buffer will have to be resized byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; TCSupport.SetHighSpeed(com1, com2); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length); //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so //the other 3 bytes of the ut32 encoded char can be in the buffer com1.Read(new char[1023], 0, 1023); Assert.Equal(1, com1.BytesToRead); com1.Encoding = Encoding.UTF32; com2.Write(utf32CharBytes, 1, 3); TCSupport.WaitForReadBufferToLoad(com1, 4); if (utf32Char != (charRead = com1.ReadChar())) { Fail("Err_6481sfadw ReadChar() returned={0} expected={1}", charRead, utf32Char); } Assert.Equal(0, com1.BytesToRead); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void LargeInputBuffer() { Debug.WriteLine("Verifying read with large input buffer"); VerifyRead(Encoding.ASCII, largeNumRndBytesToRead); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadTimeout_Zero_Bytes() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char utf32Char = (char)0x254b; //Box drawing char byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); int readChar; Debug.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer"); com1.Encoding = Encoding.UTF32; com1.ReadTimeout = 0; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); //[] Try ReadChar with no bytes available Assert.Throws<TimeoutException>(() => com1.ReadChar()); Assert.Equal(0, com1.BytesToRead); //[] Try ReadChar with 1 byte available com2.Write(utf32CharBytes, 0, 1); TCSupport.WaitForPredicate(() => com1.BytesToRead == 1, 2000, "Err_28292aheid Expected BytesToRead to be 1"); Assert.Throws<TimeoutException>(() => com1.ReadChar()); Assert.Equal(1, com1.BytesToRead); //[] Try ReadChar with the bytes in the buffer and in available in the SerialPort com2.Write(utf32CharBytes, 1, 3); TCSupport.WaitForPredicate(() => com1.BytesToRead == 4, 2000, "Err_415568haikpas Expected BytesToRead to be 4"); readChar = com1.ReadChar(); Assert.Equal(utf32Char, readChar); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Read_DataReceivedBeforeTimeout() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); char[] charRcvBuffer = new char[charXmitBuffer.Length]; ASyncRead asyncRead = new ASyncRead(com1); var asyncReadTask = new Task(asyncRead.Read); Debug.WriteLine( "Verifying that ReadChar will read characters that have been received after the call to Read was made"); com1.Encoding = Encoding.UTF8; com2.Encoding = Encoding.UTF8; com1.ReadTimeout = 20000; // 20 seconds com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); asyncReadTask.Start(); asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); asyncRead.ReadCompletedEvent.WaitOne(); Assert.Null(asyncRead.Exception); if (asyncRead.Result != charXmitBuffer[0]) { Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], asyncRead.Result); } else { charRcvBuffer[0] = (char)asyncRead.Result; int receivedLength = 1; while (receivedLength < charXmitBuffer.Length) { receivedLength += com1.Read(charRcvBuffer, receivedLength, charRcvBuffer.Length - receivedLength); } Assert.Equal(receivedLength, charXmitBuffer.Length); Assert.Equal(charXmitBuffer, charRcvBuffer); } TCSupport.WaitForTaskCompletion(asyncReadTask); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Read_Timeout() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); byte[] byteXmitBuffer = new UTF32Encoding().GetBytes(charXmitBuffer); char[] charRcvBuffer = new char[charXmitBuffer.Length]; int result; Debug.WriteLine( "Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown"); com1.Encoding = new UTF32Encoding(); com2.Encoding = new UTF32Encoding(); com1.ReadTimeout = 500; // 20 seconds com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); //Write the first 3 bytes of a character com2.Write(byteXmitBuffer, 0, 3); Assert.Throws<TimeoutException>(() => com1.ReadChar()); Assert.Equal(3, com1.BytesToRead); com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3); TCSupport.WaitForExpected(() => com1.BytesToRead, byteXmitBuffer.Length, 5000, "Err_91818aheid BytesToRead"); result = com1.ReadChar(); if (result != charXmitBuffer[0]) { Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], result); } else { charRcvBuffer[0] = (char)result; int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1); if (readResult + 1 != charXmitBuffer.Length) { Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length - 1, readResult); } else { for (int i = 0; i < charXmitBuffer.Length; ++i) { if (charRcvBuffer[i] != charXmitBuffer[i]) { Fail("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X})", i, charXmitBuffer[i], charRcvBuffer[i]); } } } } VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Read_Surrogate() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] surrogateChars = { (char)0xDB26, (char)0xDC49 }; char[] additionalChars = TCSupport.GetRandomChars(32, TCSupport.CharacterOptions.None); char[] charRcvBuffer = new char[2]; Debug.WriteLine("Verifying that ReadChar works correctly when trying to read surrogate characters"); com1.Encoding = new UTF32Encoding(); com2.Encoding = new UTF32Encoding(); com1.ReadTimeout = 500; // 20 seconds com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); int numBytes = com2.Encoding.GetByteCount(surrogateChars); numBytes += com2.Encoding.GetByteCount(additionalChars); com2.Write(surrogateChars, 0, 2); com2.Write(additionalChars, 0, additionalChars.Length); TCSupport.WaitForExpected(() => com1.BytesToRead, numBytes, 5000, "Err_91818aheid BytesToRead"); // We expect this to fail, because it can't read a surrogate // parameter name can be different on different platforms Assert.Throws<ArgumentException>(() => com1.ReadChar()); int result = com1.Read(charRcvBuffer, 0, 2); Assert.Equal(2, result); if (charRcvBuffer[0] != surrogateChars[0]) { Fail("Err_12929anied Expected first char read={0}({1:X}) actually read={2}({3:X})", surrogateChars[0], (int)surrogateChars[0], charRcvBuffer[0], (int)charRcvBuffer[0]); } else if (charRcvBuffer[1] != surrogateChars[1]) { Fail("Err_12929anied Expected second char read={0}({1:X}) actually read={2}({3:X})", surrogateChars[1], (int)surrogateChars[1], charRcvBuffer[1], (int)charRcvBuffer[1]); } PerformReadOnCom1FromCom2(com1, com2, additionalChars); } } #endregion #region Verification for Test Cases private void VerifyRead(Encoding encoding) { VerifyRead(encoding, ReadDataFromEnum.NonBuffered); } private void VerifyRead(Encoding encoding, int bufferSize) { VerifyRead(encoding, ReadDataFromEnum.NonBuffered, bufferSize); } private void VerifyRead(Encoding encoding, ReadDataFromEnum readDataFrom) { VerifyRead(encoding, readDataFrom, numRndChar); } private void VerifyRead(Encoding encoding, ReadDataFromEnum readDataFrom, int bufferSize) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(bufferSize, false); byte[] byteXmitBuffer = encoding.GetBytes(charXmitBuffer); com1.ReadTimeout = 500; com1.Encoding = encoding; TCSupport.SetHighSpeed(com1, com2); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); switch (readDataFrom) { case ReadDataFromEnum.NonBuffered: VerifyReadNonBuffered(com1, com2, byteXmitBuffer); break; case ReadDataFromEnum.Buffered: VerifyReadBuffered(com1, com2, byteXmitBuffer); break; case ReadDataFromEnum.BufferedAndNonBuffered: VerifyReadBufferedAndNonBuffered(com1, com2, byteXmitBuffer); break; default: throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); } } } private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); } private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); BufferData(com1, com2, bytesToWrite); PerformReadOnCom1FromCom2(com1, com2, expectedChars); } private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char[] expectedChars = new char[com1.Encoding.GetCharCount(bytesToWrite, 0, bytesToWrite.Length) * 2]; char[] encodedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); Array.Copy(encodedChars, 0, expectedChars, 0, bytesToWrite.Length); Array.Copy(encodedChars, 0, expectedChars, encodedChars.Length, encodedChars.Length); BufferData(com1, com2, bytesToWrite); VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); } private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer Assert.Equal(bytesToWrite.Length, com1.BytesToRead); } private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250); PerformReadOnCom1FromCom2(com1, com2, expectedChars); } private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars) { int bytesToRead = com1.Encoding.GetByteCount(expectedChars); char[] charRcvBuffer = new char[expectedChars.Length]; int rcvBufferSize = 0; int i; i = 0; while (true) { int readInt; try { readInt = com1.ReadChar(); } catch (TimeoutException) { Assert.Equal(expectedChars.Length, i); break; } //While there are more characters to be read if (expectedChars.Length <= i) { //If we have read in more characters then were actually sent Fail("ERROR!!!: We have received more characters then were sent"); } charRcvBuffer[i] = (char)readInt; rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1); int com1ToRead = com1.BytesToRead; if (bytesToRead - rcvBufferSize != com1ToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1} at {2}", bytesToRead - rcvBufferSize, com1ToRead, i); } if (readInt != expectedChars[i]) { //If the character read is not the expected character Fail("ERROR!!!: Expected to read {0} actual read char {1} at {2}", (int)expectedChars[i], readInt, i); } i++; } Assert.Equal(0, com1.BytesToRead); } public class ASyncRead { private readonly SerialPort _com; private int _result; private readonly AutoResetEvent _readCompletedEvent; private readonly AutoResetEvent _readStartedEvent; private Exception _exception; public ASyncRead(SerialPort com) { _com = com; _result = int.MinValue; _readCompletedEvent = new AutoResetEvent(false); _readStartedEvent = new AutoResetEvent(false); _exception = null; } public void Read() { try { _readStartedEvent.Set(); _result = _com.ReadChar(); } catch (Exception e) { _exception = e; } finally { _readCompletedEvent.Set(); } } public AutoResetEvent ReadStartedEvent => _readStartedEvent; public AutoResetEvent ReadCompletedEvent => _readCompletedEvent; public int Result => _result; public Exception Exception => _exception; } #endregion } }
// Classes used to create objects to display. using System.Collections.Generic; namespace DisplayHelperDemo { public class DemoClass1 { public int Class1IntField = 1111; public MyLittleObject Class1ObjectField = new MyLittleObject(11111, "Object field string"); public int Class1IntProperty { get { return 1; } } public string Class1StringProperty1 { get { return "First string property"; } } public string Class1StringProperty2 { get { return null; } } public DemoClass2 Class1ObjectProperty1 { get { return new DemoClass2(11, "First Instance String Property 1", new MyLittleObject(21, "MySubObject1"), new int[] { 11, 12, 13 }, new string[] { "First Instance String Array Element 1", "First Instance String Array Element 2" }, new List<MyLittleObject>(new MyLittleObject[] { new MyLittleObject(1, "ListObject1"), new MyLittleObject(2, "ListObject2") }), new List<string>(new string[] { "String list item 1", "String list item 2" }), new List<int>(new int[] { 10, 20 }) ); } } public DemoClass2[] Class1ObjectArrayProperty1 { get { DemoClass2[] objectArray = { new DemoClass2(111, "First Element String Property 1", new MyLittleObject(121, "MySubObject11"), new int[] { 111, 112, 113 }, new string[] { "First Element String Array Element 1", "First Element String Array Element 2" }, new List<MyLittleObject>( new MyLittleObject[] { new MyLittleObject(101, "Element 1 ListObject1"), new MyLittleObject(102, "Element 1 ListObject2") } ), new List<string>( new string[] { "Element 1 String list item 1", "Element 1 String list item 2" } ), new List<int>( new int[] { 110, 120 })), new DemoClass2(211, "Second Element String Property 1", new MyLittleObject(221, "MySubObject21"), new int[] { 211, 212, 213 }, new string[] { "Second Element String Array Element 1", "Second Element String Array Element 2" }, new List<MyLittleObject>( new MyLittleObject[] { new MyLittleObject(201, "Element 2 ListObject1"), new MyLittleObject(202, "Element 2 ListObject2") } ), new List<string>( new string[] { "Element 2 String list item 1", "Element 2 String list item 2" } ), new List<int>( new int[] { 210, 220 })) }; return objectArray; } } public DemoClass2[] Class1ObjectArrayProperty2 { get { return null; } } public DemoClass2[] Class1ObjectArrayProperty3 { get { return new DemoClass2[0]; } } } public class DemoClass2 { public DemoClass2(int intProperty, string stringProperty1, MyLittleObject objectProperty, int[] intArrayProperty, string[] stringArrayProperty, List<MyLittleObject> objectListProperty, List<string> stringListProperty, List<int> intListProperty) { _int = intProperty; _string1 = stringProperty1; _string2 = null; _parameter = objectProperty; _parameter2 = null; _intArray = intArrayProperty; _intArray2 = null; _intArray3 = new int[0]; _stringArray = stringArrayProperty; _stringArray2 = null; _stringArray3 = new string[0]; _objectList1 = objectListProperty; _objectList2 = null; _objectList3 = new List<MyLittleObject>(); _stringList1 = stringListProperty; _stringList2 = null; _stringList3 = new List<string>(); _intList1 = intListProperty; _intList2 = null; _intList3 = new List<int>(); } private int _int; public int IntProperty { get { return _int; } } private string _string1; public string StringProperty1 { get { return _string1; } } private string _string2; public string StringProperty2 { get { return _string2; } } private MyLittleObject _parameter; public MyLittleObject ObjectProperty { get { return _parameter; } } private MyLittleObject _parameter2; public MyLittleObject ObjectProperty2 { get { return _parameter2; } } private int[] _intArray; public int[] IntArrayProperty { get { return _intArray; } } private int[] _intArray2; public int[] IntArrayProperty2 { get { return _intArray2; } } private int[] _intArray3; public int[] IntArrayProperty3 { get { return _intArray3; } } private string[] _stringArray; public string[] StringArrayProperty { get { return _stringArray; } } private string[] _stringArray2; public string[] StringArrayProperty2 { get { return _stringArray2; } } private string[] _stringArray3; public string[] StringArrayProperty3 { get { return _stringArray3; } } private List<MyLittleObject> _objectList1; public List<MyLittleObject> ObjectList1 { get { return _objectList1; } } private List<MyLittleObject> _objectList2; public List<MyLittleObject> ObjectList2 { get { return _objectList2; } } private List<MyLittleObject> _objectList3; public List<MyLittleObject> ObjectList3 { get { return _objectList3; } } private List<string> _stringList1; public List<string> StringList1 { get { return _stringList1; } } private List<string> _stringList2; public List<string> StringList2 { get { return _stringList2; } } private List<string> _stringList3; public List<string> StringList3 { get { return _stringList3; } } private List<int> _intList1; public List<int> IntList1 { get { return _intList1; } } private List<int> _intList2; public List<int> IntList2 { get { return _intList2; } } private List<int> _intList3; public List<int> IntList3 { get { return _intList3; } } } public class MyLittleObject { private int _myInt; public int MyProperty { get { return _myInt; } } private string _myString; public string MyStringProperty { get { return _myString; } } public MyLittleObject(int myInt, string myString) { _myInt = myInt; _myString = myString; } } public class RecursiveObject { public RecursiveObject(int integerProperty) { _integerProperty = integerProperty; } public static RecursiveObject StaticRecursiveField = new RecursiveObject(-1); private int _integerProperty; public int IntegerProperty { get { return _integerProperty; } } public RecursiveObject RecursiveProperty { get { return new RecursiveObject(_integerProperty + 1); } } public RecursiveObject2 ObjectProperty { get { return new RecursiveObject2(_integerProperty); } } public static RecursiveObject StaticRecursiveProperty { get { return new RecursiveObject(-2); } } } public class RecursiveObject2 { public RecursiveObject2(int integerProperty2) { _integerProperty2 = integerProperty2; } private int _integerProperty2; public int IntegerProperty2 { get { return _integerProperty2; } } public RecursiveObject RecursiveProperty2 { get { return new RecursiveObject(_integerProperty2 + 1); } } } }
using System; using System.IO; using Raksha.Utilities; namespace Raksha.Asn1 { /** * Base class for an application specific object */ public class DerApplicationSpecific : Asn1Object { private readonly bool isConstructed; private readonly int tag; private readonly byte[] octets; internal DerApplicationSpecific( bool isConstructed, int tag, byte[] octets) { this.isConstructed = isConstructed; this.tag = tag; this.octets = octets; } public DerApplicationSpecific( int tag, byte[] octets) : this(false, tag, octets) { } public DerApplicationSpecific( int tag, Asn1Encodable obj) : this(true, tag, obj) { } public DerApplicationSpecific( bool isExplicit, int tag, Asn1Encodable obj) { byte[] data = obj.GetDerEncoded(); this.isConstructed = isExplicit; this.tag = tag; if (isExplicit) { this.octets = data; } else { int lenBytes = GetLengthOfLength(data); byte[] tmp = new byte[data.Length - lenBytes]; Array.Copy(data, lenBytes, tmp, 0, tmp.Length); this.octets = tmp; } } public DerApplicationSpecific( int tagNo, Asn1EncodableVector vec) { this.tag = tagNo; this.isConstructed = true; MemoryStream bOut = new MemoryStream(); for (int i = 0; i != vec.Count; i++) { try { byte[] bs = vec[i].GetEncoded(); bOut.Write(bs, 0, bs.Length); } catch (IOException e) { throw new InvalidOperationException("malformed object", e); } } this.octets = bOut.ToArray(); } private int GetLengthOfLength( byte[] data) { int count = 2; // TODO: assumes only a 1 byte tag number while((data[count - 1] & 0x80) != 0) { count++; } return count; } public bool IsConstructed() { return isConstructed; } public byte[] GetContents() { return octets; } public int ApplicationTag { get { return tag; } } /** * Return the enclosed object assuming explicit tagging. * * @return the resulting object * @throws IOException if reconstruction fails. */ public Asn1Object GetObject() { return FromByteArray(GetContents()); } /** * Return the enclosed object assuming implicit tagging. * * @param derTagNo the type tag that should be applied to the object's contents. * @return the resulting object * @throws IOException if reconstruction fails. */ public Asn1Object GetObject( int derTagNo) { if (derTagNo >= 0x1f) throw new IOException("unsupported tag number"); byte[] orig = this.GetEncoded(); byte[] tmp = ReplaceTagNumber(derTagNo, orig); if ((orig[0] & Asn1Tags.Constructed) != 0) { tmp[0] |= Asn1Tags.Constructed; } return FromByteArray(tmp);; } internal override void Encode( DerOutputStream derOut) { int classBits = Asn1Tags.Application; if (isConstructed) { classBits |= Asn1Tags.Constructed; } derOut.WriteEncoded(classBits, tag, octets); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerApplicationSpecific other = asn1Object as DerApplicationSpecific; if (other == null) return false; return this.isConstructed == other.isConstructed && this.tag == other.tag && Arrays.AreEqual(this.octets, other.octets); } protected override int Asn1GetHashCode() { return isConstructed.GetHashCode() ^ tag.GetHashCode() ^ Arrays.GetHashCode(octets); } private byte[] ReplaceTagNumber( int newTag, byte[] input) { int tagNo = input[0] & 0x1f; int index = 1; // // with tagged object tag number is bottom 5 bits, or stored at the start of the content // if (tagNo == 0x1f) { tagNo = 0; int b = input[index++] & 0xff; // X.690-0207 8.1.2.4.2 // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." if ((b & 0x7f) == 0) // Note: -1 will pass { throw new InvalidOperationException("corrupted stream - invalid high tag number found"); } while ((b >= 0) && ((b & 0x80) != 0)) { tagNo |= (b & 0x7f); tagNo <<= 7; b = input[index++] & 0xff; } tagNo |= (b & 0x7f); } byte[] tmp = new byte[input.Length - index + 1]; Array.Copy(input, index, tmp, 1, tmp.Length - 1); tmp[0] = (byte)newTag; return tmp; } } }
#region Copyright (c) 2003, newtelligence AG. All rights reserved. /* // Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com) // Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // (2) 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. // (3) Neither the name of the newtelligence AG nor the names of its contributors may be used // to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER // IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ------------------------------------------------------------------------- // // Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com) // // newtelligence is a registered trademark of newtelligence Aktiengesellschaft. // // For portions of this software, the some additional copyright notices may apply // which can either be found in the license.txt file included in the source distribution // or following this notice. // */ #endregion using System; using System.Diagnostics; using System.IO; using System.Threading; using System.Xml.Serialization; namespace newtelligence.DasBlog.Runtime { /// <summary> /// Comments collections stored on the file system. /// </summary> /// <remarks>This class uses the allcomments.xml file in the root. The user of the class /// is expected to use the add and/or add range methods to (re)create the file.</remarks> internal sealed class CommentFile { /* : ICommentCollection */ private CommentCollection _commentCache; private DateTime _lastUpdated = DateTime.UtcNow; /// <summary> /// Creates a new instance of the <see cref="CommentFile" /> class. /// </summary> /// <param name="contentBaseDirectory">The directory to load the content from.</param> public CommentFile(string contentBaseDirectory) { // set fields this.contentBaseDirectory = contentBaseDirectory; Rebuild(); } public void Rebuild() { // get the lock fileLock.AcquireWriterLock(100); try { XmlSerializer x = new XmlSerializer(typeof(DayExtra)); CommentCollection rebuiltCollection = new CommentCollection(); DirectoryInfo di = new DirectoryInfo(this.contentBaseDirectory); foreach (FileInfo file in di.GetFiles("*dayfeedback.xml")) { using(FileStream fs = file.OpenRead()) { DayExtra de = (DayExtra)x.Deserialize(fs); rebuiltCollection.AddRange(de.Comments); } } _commentCache = rebuiltCollection; } catch(Exception e) { // report error ErrorTrace.Trace(TraceLevel.Error,e); } finally { // release the lock fileLock.ReleaseWriterLock(); } } // METHODS // note: simple implementation: // we don't want to load the collection, remove 1 comment and save it again // but until we have hard numbers this is too slow, let's use this /// <summary> /// Adds the comment to the all comments file. /// </summary> /// <param name="comment">The comment to add.</param> public void AddComment( Comment comment ){ // parameter check if(comment== null){ throw new ArgumentNullException( "comment"); } // get the lock fileLock.AcquireWriterLock(100); try{ // check for exiting comment if( _commentCache[comment.EntryId] != null ){ throw new ArgumentException("Comment all ready exists in the allcomments file, use the update comment method to update.", "comment"); } // add the comment _commentCache.Add( comment ); _lastUpdated = DateTime.UtcNow; } catch(Exception e) { // report error ErrorTrace.Trace(TraceLevel.Error,e); } finally { // release the lock fileLock.ReleaseWriterLock(); } } /// <summary> /// Updates a comment in the all comments file. /// </summary> /// <param name="comment">The new version of the comment.</param> public void UpdateComment( Comment comment ){ // parameter check if(comment== null){ throw new ArgumentNullException( "comment"); } // get the lock fileLock.AcquireWriterLock(100); try{ // check for exiting comment Comment oldComment = _commentCache[comment.EntryId]; if( oldComment == null ){ throw new ArgumentException("Comment does not exist in the allcomments file, use the add comment method to add a new comment.", "comment"); } // replace the old comment _commentCache.Remove(oldComment); _commentCache.Add( comment ); _lastUpdated = DateTime.UtcNow; } catch(Exception e) { // report error ErrorTrace.Trace(TraceLevel.Error,e); } finally { // release the lock fileLock.ReleaseWriterLock(); } } public void DeleteComment( string commentId ){ if( commentId == null || commentId.Length == 0 ){ throw new ArgumentNullException( "commentId" ); } // get the lock fileLock.AcquireWriterLock(100); try{ // find the comment to delete Comment deletedComment = _commentCache[commentId]; // did we get a comment? if( deletedComment != null ){ // remove from collection _commentCache.Remove(deletedComment ); _lastUpdated = DateTime.UtcNow; } } catch(Exception e) { // report error ErrorTrace.Trace(TraceLevel.Error,e); } finally { // release the lock fileLock.ReleaseWriterLock(); } } /// <summary> /// Loads the comment collection from the file system. /// </summary> /// <returns>A colletion of all comments on the blog.</returns> public CommentCollection LoadComments(){ return _commentCache; } /// <summary> /// Saves the comment collection to the file system as a new file. /// </summary> /// <param name="comments">The commentcollection to save.</param> [Obsolete("Comments are automatically cached in memory now")] public void SaveComments( CommentCollection comments ){ } /// <summary> /// Returns the last time the allcomments.xml file was writen too in UTC. /// </summary> /// <returns></returns> public DateTime GetLastCommentUpdate(){ return _lastUpdated; } // some locking to prevent 2 threads from writing to the file at the same time // this will cause all kinds of nastiness; a static lock is visible to all threads, // which makes sense since we're only protecting one file private static ReaderWriterLock fileLock = new ReaderWriterLock(); private string contentBaseDirectory; } }
///////////////////////////////////// // GENERATED CODE -- DO NOT MODIFY // ///////////////////////////////////// using PatternBuffer; using System.Text; using System; using System.Collections.Generic; namespace Test.Enum { public class EnumTestPatternBuffer { private static readonly ulong[] vuBoundaries = new ulong[] { 128, 16384, 2097152, 268435456, 34359738368, 4398046511104, 562949953421312, 72057594037927936, 9223372036854775808 }; public static readonly Dictionary<string, Dictionary<byte, string>> enumIndexValueMap = new Dictionary<string, Dictionary<byte, string>>() { { "SomeEnum", new Dictionary<byte,string>() { {(byte)1, "value1"}, {(byte)2, "value2"}, {(byte)3, "value3"} } }, { "SomeEnum2", new Dictionary<byte,string>() { {(byte)1, "value4"}, {(byte)2, "value5"}, {(byte)3, "value6"} } } }; public static readonly Dictionary<string, Dictionary<string, byte>> enumValueIndexMap = new Dictionary<string, Dictionary<string, byte>> { { "SomeEnum", new Dictionary<string,byte>() { {"value1", (byte)1}, {"value2", (byte)2}, {"value3", (byte)3} } }, { "SomeEnum2", new Dictionary<string,byte>() { {"value4", (byte)1}, {"value5", (byte)2}, {"value6", (byte)3} } } }; private byte[] bytes; private IEnumTestInstantiator instantiator; public EnumTestPatternBuffer() : this(4096, new DefaultEnumTestInstantiator()) { } public EnumTestPatternBuffer(uint bufferSize) : this (bufferSize, new DefaultEnumTestInstantiator()) { } public EnumTestPatternBuffer(IEnumTestInstantiator instantiator) : this (4096, instantiator) { } public EnumTestPatternBuffer(uint bufferSize, IEnumTestInstantiator instantiator) { this.bytes = new byte[bufferSize]; this.instantiator = instantiator; } /////////////////////////////////////// // TO BYTES /////////////////////////////////////// public byte[] Energize(EnumObject o) { int index = 0; Energize(o, bytes, ref index, true); byte[] result = this.instantiator.AcquireByteArray(index); Buffer.BlockCopy(bytes, 0, result, 0, index); return result; } public byte[] Energize(EnumListObject o) { int index = 0; Energize(o, bytes, ref index, true); byte[] result = this.instantiator.AcquireByteArray(index); Buffer.BlockCopy(bytes, 0, result, 0, index); return result; } public byte[] Energize(EnumMapObject o) { int index = 0; Energize(o, bytes, ref index, true); byte[] result = this.instantiator.AcquireByteArray(index); Buffer.BlockCopy(bytes, 0, result, 0, index); return result; } public byte[] Energize(EnumMap2Object o) { int index = 0; Energize(o, bytes, ref index, true); byte[] result = this.instantiator.AcquireByteArray(index); Buffer.BlockCopy(bytes, 0, result, 0, index); return result; } public byte[] Energize(EnumSetObject o) { int index = 0; Energize(o, bytes, ref index, true); byte[] result = this.instantiator.AcquireByteArray(index); Buffer.BlockCopy(bytes, 0, result, 0, index); return result; } public void Energize(EnumObject o, byte[] bytes, ref int index, bool writeTypeId) { if (writeTypeId) { bytes[index++] = 11; } // NULL FLAGS int nullFlagsIndex = index - 1; bytes[index++] = 0; nullFlagsIndex++; // REFERENCE: SomeEnumValue bytes[index++] = enumValueIndexMap["SomeEnum"][o.SomeEnumValue.ToString()]; ; } public void Energize(EnumListObject o, byte[] bytes, ref int index, bool writeTypeId) { if (writeTypeId) { bytes[index++] = 12; } // NULL FLAGS int nullFlagsIndex = index - 1; bytes[index++] = 0; nullFlagsIndex++; // LIST: SomeEnumListValue if (o.SomeEnumListValue != null) { bytes[nullFlagsIndex] |= (byte)(128); if (o.SomeEnumListValue == null || o.SomeEnumListValue == null || o.SomeEnumListValue.Count == 0) { bytes[index++] = 0; } else { if (o.SomeEnumListValue.Count == 0) { bytes[index++] = (byte)0; } else { int byteCount; ulong value = (ulong)o.SomeEnumListValue.Count; int i_vxqVMwooIKPT; for (i_vxqVMwooIKPT = 0; i_vxqVMwooIKPT < 2; i_vxqVMwooIKPT++) { if ((ulong)o.SomeEnumListValue.Count < vuBoundaries[i_vxqVMwooIKPT]) { byteCount = (int)(i_vxqVMwooIKPT + 1); goto guvsgoto_hZt6GSimdLFQ; } } byteCount = (int)i_vxqVMwooIKPT + 1; guvsgoto_hZt6GSimdLFQ: for (int i_ceHGCHHOzSMw = 0; i_ceHGCHHOzSMw < byteCount; i_ceHGCHHOzSMw++) { if (i_ceHGCHHOzSMw < byteCount - 1) { byte b = (byte)(value & 127); if (i_ceHGCHHOzSMw < byteCount - 1) { b += 128; } bytes[index++] = b; value = value >> 7; } else { bytes[index++] = (byte)value; value = value >> 8; } } } foreach (SomeEnum enumValue in o.SomeEnumListValue) { bytes[index++] = enumValueIndexMap["SomeEnum"][enumValue.ToString()]; ; } } } } public void Energize(EnumMapObject o, byte[] bytes, ref int index, bool writeTypeId) { if (writeTypeId) { bytes[index++] = 13; } // NULL FLAGS int nullFlagsIndex = index - 1; bytes[index++] = 0; nullFlagsIndex++; // MAP: IntSomeEnumMapValue if (o.IntSomeEnumMapValue != null) { bytes[nullFlagsIndex] |= (byte)(128); if (o.IntSomeEnumMapValue == null || o.IntSomeEnumMapValue.Keys == null || o.IntSomeEnumMapValue.Keys.Count == 0) { bytes[index++] = 0; } else { if (o.IntSomeEnumMapValue.Keys.Count == 0) { bytes[index++] = (byte)0; } else { int byteCount; ulong value = (ulong)o.IntSomeEnumMapValue.Keys.Count; int i_fdOorHlQjJ0C; for (i_fdOorHlQjJ0C = 0; i_fdOorHlQjJ0C < 2; i_fdOorHlQjJ0C++) { if ((ulong)o.IntSomeEnumMapValue.Keys.Count < vuBoundaries[i_fdOorHlQjJ0C]) { byteCount = (int)(i_fdOorHlQjJ0C + 1); goto guvsgoto_d98MGshsUiMz; } } byteCount = (int)i_fdOorHlQjJ0C + 1; guvsgoto_d98MGshsUiMz: for (int i_eLTFd0qgU3NN = 0; i_eLTFd0qgU3NN < byteCount; i_eLTFd0qgU3NN++) { if (i_eLTFd0qgU3NN < byteCount - 1) { byte b = (byte)(value & 127); if (i_eLTFd0qgU3NN < byteCount - 1) { b += 128; } bytes[index++] = b; value = value >> 7; } else { bytes[index++] = (byte)value; value = value >> 8; } } } foreach (int primitive in o.IntSomeEnumMapValue.Keys) { bytes[index++] = (byte)((primitive >> 24) & 255); bytes[index++] = (byte)((primitive >> 16) & 255); bytes[index++] = (byte)((primitive >> 8) & 255); bytes[index++] = (byte)(primitive & 255); } } if (o.IntSomeEnumMapValue == null || o.IntSomeEnumMapValue.Values == null || o.IntSomeEnumMapValue.Values.Count == 0) { bytes[index++] = 0; } else { if (o.IntSomeEnumMapValue.Values.Count == 0) { bytes[index++] = (byte)0; } else { int byteCount; ulong value = (ulong)o.IntSomeEnumMapValue.Values.Count; int i_xtx2H6mIiGB4; for (i_xtx2H6mIiGB4 = 0; i_xtx2H6mIiGB4 < 2; i_xtx2H6mIiGB4++) { if ((ulong)o.IntSomeEnumMapValue.Values.Count < vuBoundaries[i_xtx2H6mIiGB4]) { byteCount = (int)(i_xtx2H6mIiGB4 + 1); goto guvsgoto_jLSqDx97Biuz; } } byteCount = (int)i_xtx2H6mIiGB4 + 1; guvsgoto_jLSqDx97Biuz: for (int i_oLo31GOsAa0Q = 0; i_oLo31GOsAa0Q < byteCount; i_oLo31GOsAa0Q++) { if (i_oLo31GOsAa0Q < byteCount - 1) { byte b = (byte)(value & 127); if (i_oLo31GOsAa0Q < byteCount - 1) { b += 128; } bytes[index++] = b; value = value >> 7; } else { bytes[index++] = (byte)value; value = value >> 8; } } } foreach (SomeEnum enumValue in o.IntSomeEnumMapValue.Values) { bytes[index++] = enumValueIndexMap["SomeEnum"][enumValue.ToString()]; ; } } } } public void Energize(EnumMap2Object o, byte[] bytes, ref int index, bool writeTypeId) { if (writeTypeId) { bytes[index++] = 14; } // NULL FLAGS int nullFlagsIndex = index - 1; bytes[index++] = 0; nullFlagsIndex++; // MAP: SomeEnumIntMapValue if (o.SomeEnumIntMapValue != null) { bytes[nullFlagsIndex] |= (byte)(128); if (o.SomeEnumIntMapValue == null || o.SomeEnumIntMapValue.Keys == null || o.SomeEnumIntMapValue.Keys.Count == 0) { bytes[index++] = 0; } else { if (o.SomeEnumIntMapValue.Keys.Count == 0) { bytes[index++] = (byte)0; } else { int byteCount; ulong value = (ulong)o.SomeEnumIntMapValue.Keys.Count; int i_myJYReE1jXR2; for (i_myJYReE1jXR2 = 0; i_myJYReE1jXR2 < 2; i_myJYReE1jXR2++) { if ((ulong)o.SomeEnumIntMapValue.Keys.Count < vuBoundaries[i_myJYReE1jXR2]) { byteCount = (int)(i_myJYReE1jXR2 + 1); goto guvsgoto_v5mWK2acrtMU; } } byteCount = (int)i_myJYReE1jXR2 + 1; guvsgoto_v5mWK2acrtMU: for (int i_dgg5Eb92CQdL = 0; i_dgg5Eb92CQdL < byteCount; i_dgg5Eb92CQdL++) { if (i_dgg5Eb92CQdL < byteCount - 1) { byte b = (byte)(value & 127); if (i_dgg5Eb92CQdL < byteCount - 1) { b += 128; } bytes[index++] = b; value = value >> 7; } else { bytes[index++] = (byte)value; value = value >> 8; } } } foreach (SomeEnum enumValue in o.SomeEnumIntMapValue.Keys) { bytes[index++] = enumValueIndexMap["SomeEnum"][enumValue.ToString()]; ; } } if (o.SomeEnumIntMapValue == null || o.SomeEnumIntMapValue.Values == null || o.SomeEnumIntMapValue.Values.Count == 0) { bytes[index++] = 0; } else { if (o.SomeEnumIntMapValue.Values.Count == 0) { bytes[index++] = (byte)0; } else { int byteCount; ulong value = (ulong)o.SomeEnumIntMapValue.Values.Count; int i_yZLvG8GbouOD; for (i_yZLvG8GbouOD = 0; i_yZLvG8GbouOD < 2; i_yZLvG8GbouOD++) { if ((ulong)o.SomeEnumIntMapValue.Values.Count < vuBoundaries[i_yZLvG8GbouOD]) { byteCount = (int)(i_yZLvG8GbouOD + 1); goto guvsgoto_tz8pGzMp8EzD; } } byteCount = (int)i_yZLvG8GbouOD + 1; guvsgoto_tz8pGzMp8EzD: for (int i_ueHquUrXu7fs = 0; i_ueHquUrXu7fs < byteCount; i_ueHquUrXu7fs++) { if (i_ueHquUrXu7fs < byteCount - 1) { byte b = (byte)(value & 127); if (i_ueHquUrXu7fs < byteCount - 1) { b += 128; } bytes[index++] = b; value = value >> 7; } else { bytes[index++] = (byte)value; value = value >> 8; } } } foreach (int primitive in o.SomeEnumIntMapValue.Values) { bytes[index++] = (byte)((primitive >> 24) & 255); bytes[index++] = (byte)((primitive >> 16) & 255); bytes[index++] = (byte)((primitive >> 8) & 255); bytes[index++] = (byte)(primitive & 255); } } } } public void Energize(EnumSetObject o, byte[] bytes, ref int index, bool writeTypeId) { if (writeTypeId) { bytes[index++] = 15; } // NULL FLAGS int nullFlagsIndex = index - 1; bytes[index++] = 0; nullFlagsIndex++; // SET: SomeEnumSetValue if (o.SomeEnumSetValue != null) { bytes[nullFlagsIndex] |= (byte)(128); if (o.SomeEnumSetValue == null || o.SomeEnumSetValue == null || o.SomeEnumSetValue.Count == 0) { bytes[index++] = 0; } else { if (o.SomeEnumSetValue.Count == 0) { bytes[index++] = (byte)0; } else { int byteCount; ulong value = (ulong)o.SomeEnumSetValue.Count; int i_lNvDkbxyVEDB; for (i_lNvDkbxyVEDB = 0; i_lNvDkbxyVEDB < 2; i_lNvDkbxyVEDB++) { if ((ulong)o.SomeEnumSetValue.Count < vuBoundaries[i_lNvDkbxyVEDB]) { byteCount = (int)(i_lNvDkbxyVEDB + 1); goto guvsgoto_covUkB3NRM8P; } } byteCount = (int)i_lNvDkbxyVEDB + 1; guvsgoto_covUkB3NRM8P: for (int i_ww4nmMi9Ttpr = 0; i_ww4nmMi9Ttpr < byteCount; i_ww4nmMi9Ttpr++) { if (i_ww4nmMi9Ttpr < byteCount - 1) { byte b = (byte)(value & 127); if (i_ww4nmMi9Ttpr < byteCount - 1) { b += 128; } bytes[index++] = b; value = value >> 7; } else { bytes[index++] = (byte)value; value = value >> 8; } } } foreach (SomeEnum enumValue in o.SomeEnumSetValue) { bytes[index++] = enumValueIndexMap["SomeEnum"][enumValue.ToString()]; ; } } } } public void Energize(IEnumTestObject o, byte[] bytes, ref int index, bool writeTypeId) { switch (o.TypeId) { case 11: Energize((EnumObject)o, bytes, ref index, writeTypeId); break; case 12: Energize((EnumListObject)o, bytes, ref index, writeTypeId); break; case 13: Energize((EnumMapObject)o, bytes, ref index, writeTypeId); break; case 14: Energize((EnumMap2Object)o, bytes, ref index, writeTypeId); break; case 15: Energize((EnumSetObject)o, bytes, ref index, writeTypeId); break; default: throw new EnumTestPatternBufferException("Unrecognized type ID: "+o.TypeId+" "); } } /////////////////////////////////////// // FROM BYTES /////////////////////////////////////// public object Energize(byte[] bytes) { int index = 0; ulong vuread_qW0WAaWjg1ZQ = 0; for (int i_kXMtKQHLV31Y = 0; i_kXMtKQHLV31Y < 9; i_kXMtKQHLV31Y++) { byte b = bytes[index++]; if (i_kXMtKQHLV31Y < 8) { vuread_qW0WAaWjg1ZQ += (((ulong)b & (ulong)127) << (7 * i_kXMtKQHLV31Y)); if ((int)(b & 128) == 0) { break; } } else { vuread_qW0WAaWjg1ZQ += (ulong)b << (7 * i_kXMtKQHLV31Y); break; } } ushort typeId = (ushort)vuread_qW0WAaWjg1ZQ; switch (typeId) { case 11: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumObject o = this.instantiator.AcquireEnumObject(); nullFlagsIndex++; // REFERENCE: SomeEnumValue byte enumValue_nPBeE85hye0y; enumValue_nPBeE85hye0y = bytes[index++]; o.SomeEnumValue = (SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][enumValue_nPBeE85hye0y]); return o; } case 12: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumListObject o = this.instantiator.AcquireEnumListObject(); nullFlagsIndex++; // LIST: SomeEnumListValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { // Read list item count ushort count_eK8USuvaGoYy; ulong vuread_zZzdWNFU4cpV = 0; for (int i_oROh6Sru7oi9 = 0; i_oROh6Sru7oi9 < 9; i_oROh6Sru7oi9++) { byte b = bytes[index++]; if (i_oROh6Sru7oi9 < 8) { vuread_zZzdWNFU4cpV += (((ulong)b & (ulong)127) << (7 * i_oROh6Sru7oi9)); if ((int)(b & 128) == 0) { break; } } else { vuread_zZzdWNFU4cpV += (ulong)b << (7 * i_oROh6Sru7oi9); break; } } count_eK8USuvaGoYy = (ushort)vuread_zZzdWNFU4cpV; // Read list items if (count_eK8USuvaGoYy > 0) { o.SomeEnumListValue = this.instantiator.AcquireListOfSomeEnum(); for (int i_sW2BI1rs0cfP = 0; i_sW2BI1rs0cfP < count_eK8USuvaGoYy; i_sW2BI1rs0cfP++) { o.SomeEnumListValue.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } } return o; } case 13: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumMapObject o = this.instantiator.AcquireEnumMapObject(); nullFlagsIndex++; // MAP: IntSomeEnumMapValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { List<int> intSomeEnumMapValueKeys = this.instantiator.AcquireListOfInt(); List<SomeEnum> intSomeEnumMapValueValues = this.instantiator.AcquireListOfSomeEnum(); // Read list item count ushort count_o2vUIgEiumla; ulong vuread_rneY6EBVQzv9 = 0; for (int i_telcU64GM9Ie = 0; i_telcU64GM9Ie < 9; i_telcU64GM9Ie++) { byte b = bytes[index++]; if (i_telcU64GM9Ie < 8) { vuread_rneY6EBVQzv9 += (((ulong)b & (ulong)127) << (7 * i_telcU64GM9Ie)); if ((int)(b & 128) == 0) { break; } } else { vuread_rneY6EBVQzv9 += (ulong)b << (7 * i_telcU64GM9Ie); break; } } count_o2vUIgEiumla = (ushort)vuread_rneY6EBVQzv9; // Read list items if (count_o2vUIgEiumla > 0) { intSomeEnumMapValueKeys = this.instantiator.AcquireListOfInt(); int listValue_jHV1T9OFL2Vu; for (int i_uDwvLt8jHv9E = 0; i_uDwvLt8jHv9E < count_o2vUIgEiumla; i_uDwvLt8jHv9E++) { // Read Int list item listValue_jHV1T9OFL2Vu = (int)( ((int)bytes[index++] << 24) | ((int)bytes[index++] << 16) | ((int)bytes[index++] << 8) | (int)bytes[index++] ); intSomeEnumMapValueKeys.Add(listValue_jHV1T9OFL2Vu); } } // Read list item count ushort count_xBxysOyPP9Bz; ulong vuread_tJbRVZy2s1pr = 0; for (int i_pI5tbzHbHr7s = 0; i_pI5tbzHbHr7s < 9; i_pI5tbzHbHr7s++) { byte b = bytes[index++]; if (i_pI5tbzHbHr7s < 8) { vuread_tJbRVZy2s1pr += (((ulong)b & (ulong)127) << (7 * i_pI5tbzHbHr7s)); if ((int)(b & 128) == 0) { break; } } else { vuread_tJbRVZy2s1pr += (ulong)b << (7 * i_pI5tbzHbHr7s); break; } } count_xBxysOyPP9Bz = (ushort)vuread_tJbRVZy2s1pr; // Read list items if (count_xBxysOyPP9Bz > 0) { intSomeEnumMapValueValues = this.instantiator.AcquireListOfSomeEnum(); for (int i_pqn7EgOXc7Mb = 0; i_pqn7EgOXc7Mb < count_xBxysOyPP9Bz; i_pqn7EgOXc7Mb++) { intSomeEnumMapValueValues.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } o.IntSomeEnumMapValue = this.instantiator.AcquireDictionaryOfIntToSomeEnum(); for (int i_hryR7glcmgXT = 0; i_hryR7glcmgXT < intSomeEnumMapValueKeys.Count; i_hryR7glcmgXT++) { o.IntSomeEnumMapValue[intSomeEnumMapValueKeys[i_hryR7glcmgXT]] = intSomeEnumMapValueValues[i_hryR7glcmgXT]; } this.instantiator.DiscardListOfInt(intSomeEnumMapValueKeys); this.instantiator.DiscardListOfSomeEnum(intSomeEnumMapValueValues); intSomeEnumMapValueKeys = null; intSomeEnumMapValueValues = null; } return o; } case 14: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumMap2Object o = this.instantiator.AcquireEnumMap2Object(); nullFlagsIndex++; // MAP: SomeEnumIntMapValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { List<SomeEnum> someEnumIntMapValueKeys = this.instantiator.AcquireListOfSomeEnum(); List<int> someEnumIntMapValueValues = this.instantiator.AcquireListOfInt(); // Read list item count ushort count_seOqCz1CMTfE; ulong vuread_qAymmBpN64bU = 0; for (int i_aZdAg4fFDDoz = 0; i_aZdAg4fFDDoz < 9; i_aZdAg4fFDDoz++) { byte b = bytes[index++]; if (i_aZdAg4fFDDoz < 8) { vuread_qAymmBpN64bU += (((ulong)b & (ulong)127) << (7 * i_aZdAg4fFDDoz)); if ((int)(b & 128) == 0) { break; } } else { vuread_qAymmBpN64bU += (ulong)b << (7 * i_aZdAg4fFDDoz); break; } } count_seOqCz1CMTfE = (ushort)vuread_qAymmBpN64bU; // Read list items if (count_seOqCz1CMTfE > 0) { someEnumIntMapValueKeys = this.instantiator.AcquireListOfSomeEnum(); for (int i_lyuMfkzIl3fG = 0; i_lyuMfkzIl3fG < count_seOqCz1CMTfE; i_lyuMfkzIl3fG++) { someEnumIntMapValueKeys.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } // Read list item count ushort count_s8ZV0kXYd4pN; ulong vuread_jAwROJbil9UY = 0; for (int i_cNHWFDIgTGSh = 0; i_cNHWFDIgTGSh < 9; i_cNHWFDIgTGSh++) { byte b = bytes[index++]; if (i_cNHWFDIgTGSh < 8) { vuread_jAwROJbil9UY += (((ulong)b & (ulong)127) << (7 * i_cNHWFDIgTGSh)); if ((int)(b & 128) == 0) { break; } } else { vuread_jAwROJbil9UY += (ulong)b << (7 * i_cNHWFDIgTGSh); break; } } count_s8ZV0kXYd4pN = (ushort)vuread_jAwROJbil9UY; // Read list items if (count_s8ZV0kXYd4pN > 0) { someEnumIntMapValueValues = this.instantiator.AcquireListOfInt(); int listValue_cuPtPAvHjQqP; for (int i_uR4M26uTobOn = 0; i_uR4M26uTobOn < count_s8ZV0kXYd4pN; i_uR4M26uTobOn++) { // Read Int list item listValue_cuPtPAvHjQqP = (int)( ((int)bytes[index++] << 24) | ((int)bytes[index++] << 16) | ((int)bytes[index++] << 8) | (int)bytes[index++] ); someEnumIntMapValueValues.Add(listValue_cuPtPAvHjQqP); } } o.SomeEnumIntMapValue = this.instantiator.AcquireDictionaryOfSomeEnumToInt(); for (int i_qbsKwi3ZSpMt = 0; i_qbsKwi3ZSpMt < someEnumIntMapValueKeys.Count; i_qbsKwi3ZSpMt++) { o.SomeEnumIntMapValue[someEnumIntMapValueKeys[i_qbsKwi3ZSpMt]] = someEnumIntMapValueValues[i_qbsKwi3ZSpMt]; } this.instantiator.DiscardListOfSomeEnum(someEnumIntMapValueKeys); this.instantiator.DiscardListOfInt(someEnumIntMapValueValues); someEnumIntMapValueKeys = null; someEnumIntMapValueValues = null; } return o; } case 15: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumSetObject o = this.instantiator.AcquireEnumSetObject(); nullFlagsIndex++; // SET: SomeEnumSetValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { // Read list item count ushort count_xSCVNmPzw28X; ulong vuread_o5oXl92dPCQO = 0; for (int i_dVlaXB6IeKSk = 0; i_dVlaXB6IeKSk < 9; i_dVlaXB6IeKSk++) { byte b = bytes[index++]; if (i_dVlaXB6IeKSk < 8) { vuread_o5oXl92dPCQO += (((ulong)b & (ulong)127) << (7 * i_dVlaXB6IeKSk)); if ((int)(b & 128) == 0) { break; } } else { vuread_o5oXl92dPCQO += (ulong)b << (7 * i_dVlaXB6IeKSk); break; } } count_xSCVNmPzw28X = (ushort)vuread_o5oXl92dPCQO; // Read list items if (count_xSCVNmPzw28X > 0) { o.SomeEnumSetValue = this.instantiator.AcquireHashSetOfSomeEnum(); for (int i_mJfcwo0UdFaA = 0; i_mJfcwo0UdFaA < count_xSCVNmPzw28X; i_mJfcwo0UdFaA++) { o.SomeEnumSetValue.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } } return o; } default: throw new EnumTestPatternBufferException("Unrecognized type ID: "+typeId+" "); } } public object Energize(byte[] bytes, ref int index) { ulong vuread_xgNSwJOBbYM1 = 0; for (int i_aOM55zS9ndtM = 0; i_aOM55zS9ndtM < 9; i_aOM55zS9ndtM++) { byte b = bytes[index++]; if (i_aOM55zS9ndtM < 8) { vuread_xgNSwJOBbYM1 += (((ulong)b & (ulong)127) << (7 * i_aOM55zS9ndtM)); if ((int)(b & 128) == 0) { break; } } else { vuread_xgNSwJOBbYM1 += (ulong)b << (7 * i_aOM55zS9ndtM); break; } } ushort typeId = (ushort)vuread_xgNSwJOBbYM1; switch (typeId) { case 11: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumObject o = this.instantiator.AcquireEnumObject(); nullFlagsIndex++; // REFERENCE: SomeEnumValue byte enumValue_x0RBL6LNUVgQ; enumValue_x0RBL6LNUVgQ = bytes[index++]; o.SomeEnumValue = (SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][enumValue_x0RBL6LNUVgQ]); return o; } case 12: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumListObject o = this.instantiator.AcquireEnumListObject(); nullFlagsIndex++; // LIST: SomeEnumListValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { // Read list item count ushort count_vomF6qjP6nbR; ulong vuread_p4YOWbn1XbYG = 0; for (int i_wm0en9hpI5hR = 0; i_wm0en9hpI5hR < 9; i_wm0en9hpI5hR++) { byte b = bytes[index++]; if (i_wm0en9hpI5hR < 8) { vuread_p4YOWbn1XbYG += (((ulong)b & (ulong)127) << (7 * i_wm0en9hpI5hR)); if ((int)(b & 128) == 0) { break; } } else { vuread_p4YOWbn1XbYG += (ulong)b << (7 * i_wm0en9hpI5hR); break; } } count_vomF6qjP6nbR = (ushort)vuread_p4YOWbn1XbYG; // Read list items if (count_vomF6qjP6nbR > 0) { o.SomeEnumListValue = this.instantiator.AcquireListOfSomeEnum(); for (int i_fnc64NPQZ9ZQ = 0; i_fnc64NPQZ9ZQ < count_vomF6qjP6nbR; i_fnc64NPQZ9ZQ++) { o.SomeEnumListValue.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } } return o; } case 13: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumMapObject o = this.instantiator.AcquireEnumMapObject(); nullFlagsIndex++; // MAP: IntSomeEnumMapValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { List<int> intSomeEnumMapValueKeys = this.instantiator.AcquireListOfInt(); List<SomeEnum> intSomeEnumMapValueValues = this.instantiator.AcquireListOfSomeEnum(); // Read list item count ushort count_d60SIp3XzPOT; ulong vuread_leC6gViPXhBI = 0; for (int i_zq6jviR1xj7q = 0; i_zq6jviR1xj7q < 9; i_zq6jviR1xj7q++) { byte b = bytes[index++]; if (i_zq6jviR1xj7q < 8) { vuread_leC6gViPXhBI += (((ulong)b & (ulong)127) << (7 * i_zq6jviR1xj7q)); if ((int)(b & 128) == 0) { break; } } else { vuread_leC6gViPXhBI += (ulong)b << (7 * i_zq6jviR1xj7q); break; } } count_d60SIp3XzPOT = (ushort)vuread_leC6gViPXhBI; // Read list items if (count_d60SIp3XzPOT > 0) { intSomeEnumMapValueKeys = this.instantiator.AcquireListOfInt(); int listValue_dyRtcurHJtG0; for (int i_eSJd1j3aFsTr = 0; i_eSJd1j3aFsTr < count_d60SIp3XzPOT; i_eSJd1j3aFsTr++) { // Read Int list item listValue_dyRtcurHJtG0 = (int)( ((int)bytes[index++] << 24) | ((int)bytes[index++] << 16) | ((int)bytes[index++] << 8) | (int)bytes[index++] ); intSomeEnumMapValueKeys.Add(listValue_dyRtcurHJtG0); } } // Read list item count ushort count_hTBr8WvqhmXR; ulong vuread_bZNCZ39PUg8N = 0; for (int i_oNanq6U0Ozbt = 0; i_oNanq6U0Ozbt < 9; i_oNanq6U0Ozbt++) { byte b = bytes[index++]; if (i_oNanq6U0Ozbt < 8) { vuread_bZNCZ39PUg8N += (((ulong)b & (ulong)127) << (7 * i_oNanq6U0Ozbt)); if ((int)(b & 128) == 0) { break; } } else { vuread_bZNCZ39PUg8N += (ulong)b << (7 * i_oNanq6U0Ozbt); break; } } count_hTBr8WvqhmXR = (ushort)vuread_bZNCZ39PUg8N; // Read list items if (count_hTBr8WvqhmXR > 0) { intSomeEnumMapValueValues = this.instantiator.AcquireListOfSomeEnum(); for (int i_xaIW8pS8419b = 0; i_xaIW8pS8419b < count_hTBr8WvqhmXR; i_xaIW8pS8419b++) { intSomeEnumMapValueValues.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } o.IntSomeEnumMapValue = this.instantiator.AcquireDictionaryOfIntToSomeEnum(); for (int i_nAkLseHlUXSv = 0; i_nAkLseHlUXSv < intSomeEnumMapValueKeys.Count; i_nAkLseHlUXSv++) { o.IntSomeEnumMapValue[intSomeEnumMapValueKeys[i_nAkLseHlUXSv]] = intSomeEnumMapValueValues[i_nAkLseHlUXSv]; } this.instantiator.DiscardListOfInt(intSomeEnumMapValueKeys); this.instantiator.DiscardListOfSomeEnum(intSomeEnumMapValueValues); intSomeEnumMapValueKeys = null; intSomeEnumMapValueValues = null; } return o; } case 14: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumMap2Object o = this.instantiator.AcquireEnumMap2Object(); nullFlagsIndex++; // MAP: SomeEnumIntMapValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { List<SomeEnum> someEnumIntMapValueKeys = this.instantiator.AcquireListOfSomeEnum(); List<int> someEnumIntMapValueValues = this.instantiator.AcquireListOfInt(); // Read list item count ushort count_uhakB7dOXuJZ; ulong vuread_inQEx9TQO8RZ = 0; for (int i_tiIK20Igrna0 = 0; i_tiIK20Igrna0 < 9; i_tiIK20Igrna0++) { byte b = bytes[index++]; if (i_tiIK20Igrna0 < 8) { vuread_inQEx9TQO8RZ += (((ulong)b & (ulong)127) << (7 * i_tiIK20Igrna0)); if ((int)(b & 128) == 0) { break; } } else { vuread_inQEx9TQO8RZ += (ulong)b << (7 * i_tiIK20Igrna0); break; } } count_uhakB7dOXuJZ = (ushort)vuread_inQEx9TQO8RZ; // Read list items if (count_uhakB7dOXuJZ > 0) { someEnumIntMapValueKeys = this.instantiator.AcquireListOfSomeEnum(); for (int i_gIH7Yvnm1vqf = 0; i_gIH7Yvnm1vqf < count_uhakB7dOXuJZ; i_gIH7Yvnm1vqf++) { someEnumIntMapValueKeys.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } // Read list item count ushort count_jcXUdbQWAkzs; ulong vuread_kDV7VDHhm0pZ = 0; for (int i_mW2sVF8z1Dm0 = 0; i_mW2sVF8z1Dm0 < 9; i_mW2sVF8z1Dm0++) { byte b = bytes[index++]; if (i_mW2sVF8z1Dm0 < 8) { vuread_kDV7VDHhm0pZ += (((ulong)b & (ulong)127) << (7 * i_mW2sVF8z1Dm0)); if ((int)(b & 128) == 0) { break; } } else { vuread_kDV7VDHhm0pZ += (ulong)b << (7 * i_mW2sVF8z1Dm0); break; } } count_jcXUdbQWAkzs = (ushort)vuread_kDV7VDHhm0pZ; // Read list items if (count_jcXUdbQWAkzs > 0) { someEnumIntMapValueValues = this.instantiator.AcquireListOfInt(); int listValue_bXcqGnAeioIv; for (int i_opAxYj2HW7sr = 0; i_opAxYj2HW7sr < count_jcXUdbQWAkzs; i_opAxYj2HW7sr++) { // Read Int list item listValue_bXcqGnAeioIv = (int)( ((int)bytes[index++] << 24) | ((int)bytes[index++] << 16) | ((int)bytes[index++] << 8) | (int)bytes[index++] ); someEnumIntMapValueValues.Add(listValue_bXcqGnAeioIv); } } o.SomeEnumIntMapValue = this.instantiator.AcquireDictionaryOfSomeEnumToInt(); for (int i_eyb4l9A5q458 = 0; i_eyb4l9A5q458 < someEnumIntMapValueKeys.Count; i_eyb4l9A5q458++) { o.SomeEnumIntMapValue[someEnumIntMapValueKeys[i_eyb4l9A5q458]] = someEnumIntMapValueValues[i_eyb4l9A5q458]; } this.instantiator.DiscardListOfSomeEnum(someEnumIntMapValueKeys); this.instantiator.DiscardListOfInt(someEnumIntMapValueValues); someEnumIntMapValueKeys = null; someEnumIntMapValueValues = null; } return o; } case 15: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumSetObject o = this.instantiator.AcquireEnumSetObject(); nullFlagsIndex++; // SET: SomeEnumSetValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { // Read list item count ushort count_lrK8AlQooGTF; ulong vuread_cLLSKPeeFVgi = 0; for (int i_fF2jXNfPuB6H = 0; i_fF2jXNfPuB6H < 9; i_fF2jXNfPuB6H++) { byte b = bytes[index++]; if (i_fF2jXNfPuB6H < 8) { vuread_cLLSKPeeFVgi += (((ulong)b & (ulong)127) << (7 * i_fF2jXNfPuB6H)); if ((int)(b & 128) == 0) { break; } } else { vuread_cLLSKPeeFVgi += (ulong)b << (7 * i_fF2jXNfPuB6H); break; } } count_lrK8AlQooGTF = (ushort)vuread_cLLSKPeeFVgi; // Read list items if (count_lrK8AlQooGTF > 0) { o.SomeEnumSetValue = this.instantiator.AcquireHashSetOfSomeEnum(); for (int i_o4gLrddNOGYK = 0; i_o4gLrddNOGYK < count_lrK8AlQooGTF; i_o4gLrddNOGYK++) { o.SomeEnumSetValue.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } } return o; } default: throw new EnumTestPatternBufferException("Unrecognized type ID: "+typeId+" "); } } public object Energize(byte[] bytes, ref int index, ushort typeId) { switch (typeId) { case 11: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumObject o = this.instantiator.AcquireEnumObject(); nullFlagsIndex++; // REFERENCE: SomeEnumValue byte enumValue_kSvK00DPkCW4; enumValue_kSvK00DPkCW4 = bytes[index++]; o.SomeEnumValue = (SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][enumValue_kSvK00DPkCW4]); return o; } case 12: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumListObject o = this.instantiator.AcquireEnumListObject(); nullFlagsIndex++; // LIST: SomeEnumListValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { // Read list item count ushort count_hHALBekNOekP; ulong vuread_oCXBSDDQRrVf = 0; for (int i_hEYD8qwfimtU = 0; i_hEYD8qwfimtU < 9; i_hEYD8qwfimtU++) { byte b = bytes[index++]; if (i_hEYD8qwfimtU < 8) { vuread_oCXBSDDQRrVf += (((ulong)b & (ulong)127) << (7 * i_hEYD8qwfimtU)); if ((int)(b & 128) == 0) { break; } } else { vuread_oCXBSDDQRrVf += (ulong)b << (7 * i_hEYD8qwfimtU); break; } } count_hHALBekNOekP = (ushort)vuread_oCXBSDDQRrVf; // Read list items if (count_hHALBekNOekP > 0) { o.SomeEnumListValue = this.instantiator.AcquireListOfSomeEnum(); for (int i_qBlKvk6tHPcx = 0; i_qBlKvk6tHPcx < count_hHALBekNOekP; i_qBlKvk6tHPcx++) { o.SomeEnumListValue.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } } return o; } case 13: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumMapObject o = this.instantiator.AcquireEnumMapObject(); nullFlagsIndex++; // MAP: IntSomeEnumMapValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { List<int> intSomeEnumMapValueKeys = this.instantiator.AcquireListOfInt(); List<SomeEnum> intSomeEnumMapValueValues = this.instantiator.AcquireListOfSomeEnum(); // Read list item count ushort count_bb7R8gnaVvs7; ulong vuread_gRPxReHwjdYq = 0; for (int i_h3uGvBHMBBA6 = 0; i_h3uGvBHMBBA6 < 9; i_h3uGvBHMBBA6++) { byte b = bytes[index++]; if (i_h3uGvBHMBBA6 < 8) { vuread_gRPxReHwjdYq += (((ulong)b & (ulong)127) << (7 * i_h3uGvBHMBBA6)); if ((int)(b & 128) == 0) { break; } } else { vuread_gRPxReHwjdYq += (ulong)b << (7 * i_h3uGvBHMBBA6); break; } } count_bb7R8gnaVvs7 = (ushort)vuread_gRPxReHwjdYq; // Read list items if (count_bb7R8gnaVvs7 > 0) { intSomeEnumMapValueKeys = this.instantiator.AcquireListOfInt(); int listValue_hPhc9s8rjovN; for (int i_nIMDhPoanRAf = 0; i_nIMDhPoanRAf < count_bb7R8gnaVvs7; i_nIMDhPoanRAf++) { // Read Int list item listValue_hPhc9s8rjovN = (int)( ((int)bytes[index++] << 24) | ((int)bytes[index++] << 16) | ((int)bytes[index++] << 8) | (int)bytes[index++] ); intSomeEnumMapValueKeys.Add(listValue_hPhc9s8rjovN); } } // Read list item count ushort count_tRPtYQFYrSec; ulong vuread_yFx1eGhcHQaW = 0; for (int i_vdFWmATLobqr = 0; i_vdFWmATLobqr < 9; i_vdFWmATLobqr++) { byte b = bytes[index++]; if (i_vdFWmATLobqr < 8) { vuread_yFx1eGhcHQaW += (((ulong)b & (ulong)127) << (7 * i_vdFWmATLobqr)); if ((int)(b & 128) == 0) { break; } } else { vuread_yFx1eGhcHQaW += (ulong)b << (7 * i_vdFWmATLobqr); break; } } count_tRPtYQFYrSec = (ushort)vuread_yFx1eGhcHQaW; // Read list items if (count_tRPtYQFYrSec > 0) { intSomeEnumMapValueValues = this.instantiator.AcquireListOfSomeEnum(); for (int i_qOCCTHwWDKGL = 0; i_qOCCTHwWDKGL < count_tRPtYQFYrSec; i_qOCCTHwWDKGL++) { intSomeEnumMapValueValues.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } o.IntSomeEnumMapValue = this.instantiator.AcquireDictionaryOfIntToSomeEnum(); for (int i_hw5QKxHeQ2EU = 0; i_hw5QKxHeQ2EU < intSomeEnumMapValueKeys.Count; i_hw5QKxHeQ2EU++) { o.IntSomeEnumMapValue[intSomeEnumMapValueKeys[i_hw5QKxHeQ2EU]] = intSomeEnumMapValueValues[i_hw5QKxHeQ2EU]; } this.instantiator.DiscardListOfInt(intSomeEnumMapValueKeys); this.instantiator.DiscardListOfSomeEnum(intSomeEnumMapValueValues); intSomeEnumMapValueKeys = null; intSomeEnumMapValueValues = null; } return o; } case 14: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumMap2Object o = this.instantiator.AcquireEnumMap2Object(); nullFlagsIndex++; // MAP: SomeEnumIntMapValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { List<SomeEnum> someEnumIntMapValueKeys = this.instantiator.AcquireListOfSomeEnum(); List<int> someEnumIntMapValueValues = this.instantiator.AcquireListOfInt(); // Read list item count ushort count_eSL19DX4pfoz; ulong vuread_bOtauntpH3E0 = 0; for (int i_mcb0ElLUkRsa = 0; i_mcb0ElLUkRsa < 9; i_mcb0ElLUkRsa++) { byte b = bytes[index++]; if (i_mcb0ElLUkRsa < 8) { vuread_bOtauntpH3E0 += (((ulong)b & (ulong)127) << (7 * i_mcb0ElLUkRsa)); if ((int)(b & 128) == 0) { break; } } else { vuread_bOtauntpH3E0 += (ulong)b << (7 * i_mcb0ElLUkRsa); break; } } count_eSL19DX4pfoz = (ushort)vuread_bOtauntpH3E0; // Read list items if (count_eSL19DX4pfoz > 0) { someEnumIntMapValueKeys = this.instantiator.AcquireListOfSomeEnum(); for (int i_yFXaWLwmiFM6 = 0; i_yFXaWLwmiFM6 < count_eSL19DX4pfoz; i_yFXaWLwmiFM6++) { someEnumIntMapValueKeys.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } // Read list item count ushort count_cHUCJonqoVw7; ulong vuread_l7AdEEowvseY = 0; for (int i_lsD5HrR9zfV6 = 0; i_lsD5HrR9zfV6 < 9; i_lsD5HrR9zfV6++) { byte b = bytes[index++]; if (i_lsD5HrR9zfV6 < 8) { vuread_l7AdEEowvseY += (((ulong)b & (ulong)127) << (7 * i_lsD5HrR9zfV6)); if ((int)(b & 128) == 0) { break; } } else { vuread_l7AdEEowvseY += (ulong)b << (7 * i_lsD5HrR9zfV6); break; } } count_cHUCJonqoVw7 = (ushort)vuread_l7AdEEowvseY; // Read list items if (count_cHUCJonqoVw7 > 0) { someEnumIntMapValueValues = this.instantiator.AcquireListOfInt(); int listValue_lik6EbVkjZIZ; for (int i_etSOqqKWC6cq = 0; i_etSOqqKWC6cq < count_cHUCJonqoVw7; i_etSOqqKWC6cq++) { // Read Int list item listValue_lik6EbVkjZIZ = (int)( ((int)bytes[index++] << 24) | ((int)bytes[index++] << 16) | ((int)bytes[index++] << 8) | (int)bytes[index++] ); someEnumIntMapValueValues.Add(listValue_lik6EbVkjZIZ); } } o.SomeEnumIntMapValue = this.instantiator.AcquireDictionaryOfSomeEnumToInt(); for (int i_tsT7dwHwlEMw = 0; i_tsT7dwHwlEMw < someEnumIntMapValueKeys.Count; i_tsT7dwHwlEMw++) { o.SomeEnumIntMapValue[someEnumIntMapValueKeys[i_tsT7dwHwlEMw]] = someEnumIntMapValueValues[i_tsT7dwHwlEMw]; } this.instantiator.DiscardListOfSomeEnum(someEnumIntMapValueKeys); this.instantiator.DiscardListOfInt(someEnumIntMapValueValues); someEnumIntMapValueKeys = null; someEnumIntMapValueValues = null; } return o; } case 15: { // NULL FLAGS int nullFlagsIndex = index - 1; index += 1; EnumSetObject o = this.instantiator.AcquireEnumSetObject(); nullFlagsIndex++; // SET: SomeEnumSetValue if ((bytes[nullFlagsIndex] & (byte)128) > 0) { // Read list item count ushort count_is1tG4PLUOUn; ulong vuread_odTjE9EEg4kl = 0; for (int i_hYhWslNQRwu7 = 0; i_hYhWslNQRwu7 < 9; i_hYhWslNQRwu7++) { byte b = bytes[index++]; if (i_hYhWslNQRwu7 < 8) { vuread_odTjE9EEg4kl += (((ulong)b & (ulong)127) << (7 * i_hYhWslNQRwu7)); if ((int)(b & 128) == 0) { break; } } else { vuread_odTjE9EEg4kl += (ulong)b << (7 * i_hYhWslNQRwu7); break; } } count_is1tG4PLUOUn = (ushort)vuread_odTjE9EEg4kl; // Read list items if (count_is1tG4PLUOUn > 0) { o.SomeEnumSetValue = this.instantiator.AcquireHashSetOfSomeEnum(); for (int i_kqpIqAFhIGx9 = 0; i_kqpIqAFhIGx9 < count_is1tG4PLUOUn; i_kqpIqAFhIGx9++) { o.SomeEnumSetValue.Add((SomeEnum)System.Enum.Parse(typeof(SomeEnum), enumIndexValueMap["SomeEnum"][bytes[index++]])); } } } return o; } default: throw new EnumTestPatternBufferException("Unrecognized type ID: "+typeId+" "); } } /////////////////////////////////////// // FROM BYTES (TYPED) /////////////////////////////////////// public TYPE Energize< TYPE > (byte[] bytes) { object o = this.Energize(bytes); if (!(o is TYPE)) { throw new EnumTestPatternBufferException("Deserialized type (" + o.GetType().Name + ") does not match expected type (" + typeof(TYPE).Name + ")."); } return (TYPE)o; } /////////////////////////////////////// // RECLAIM /////////////////////////////////////// public void Reclaim(EnumObject o) { if (o != null) { o.SomeEnumValue = default(SomeEnum); this.instantiator.DiscardEnumObject(o); } } public void Reclaim(EnumListObject o) { if (o != null) { this.instantiator.DiscardEnumListObject(o); } } public void Reclaim(EnumMapObject o) { if (o != null) { if (o.IntSomeEnumMapValue != null) { this.instantiator.DiscardDictionaryOfIntToSomeEnum((Dictionary<int,SomeEnum>)o.IntSomeEnumMapValue); } this.instantiator.DiscardEnumMapObject(o); } } public void Reclaim(EnumMap2Object o) { if (o != null) { if (o.SomeEnumIntMapValue != null) { this.instantiator.DiscardDictionaryOfSomeEnumToInt((Dictionary<SomeEnum,int>)o.SomeEnumIntMapValue); } this.instantiator.DiscardEnumMap2Object(o); } } public void Reclaim(EnumSetObject o) { if (o != null) { this.instantiator.DiscardEnumSetObject(o); } } } }
using System; using System.IO; using System.Text; using Hydra.Framework.Mapping.Geometries; namespace Hydra.Framework.Mapping.Converters.WellKnownText { // // ********************************************************************** /// <summary> /// Outputs the textual representation of a <see cref="Hydra.Framework.Mapping.Geometries.AbstractGeometry"/> instance. /// </summary> /// <remarks> /// <para>The Well-Known Text (WKT) representation of AbstractGeometry is designed to exchange geometry data in ASCII form.</para> /// Examples of WKT representations of geometry objects are: /// <list type="table"> /// <listheader><term>AbstractGeometry </term><description>WKT Representation</description></listheader> /// <item><term>A Point</term> /// <description>POINT(15 20)<br/> Note that point coordinates are specified with no separating comma.</description></item> /// <item><term>A LineString with four points:</term> /// <description>LINESTRING(0 0, 10 10, 20 25, 50 60)</description></item> /// <item><term>A Polygon with one exterior ring and one interior ring:</term> /// <description>POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))</description></item> /// <item><term>A MultiPoint with three Point values:</term> /// <description>MULTIPOINT(0 0, 20 20, 60 60)</description></item> /// <item><term>A MultiLineString with two LineString values:</term> /// <description>MULTILINESTRING((10 10, 20 20), (15 15, 30 15))</description></item> /// <item><term>A MultiPolygon with two Polygon values:</term> /// <description>MULTIPOLYGON(((0 0,10 0,10 10,0 10,0 0)),((5 5,7 5,7 7,5 7, 5 5)))</description></item> /// <item><term>A GeometryCollection consisting of two Point values and one LineString:</term> /// <description>GEOMETRYCOLLECTION(POINT(10 10), POINT(30 30), LINESTRING(15 15, 20 20))</description></item> /// </list> /// </remarks> // ********************************************************************** // public class GeometryToWKT { #region Static Methods // // ********************************************************************** /// <summary> /// Converts a AbstractGeometry to its Well-known Text representation. /// </summary> /// <param name="geometry">A AbstractGeometry to write.</param> /// <returns> /// A &lt;AbstractGeometry Tagged Text&gt; string (see the OpenGIS Simple /// Features Specification) /// </returns> // ********************************************************************** // public static string Write(IGeometry geometry) { StringWriter sw = new StringWriter(); Write(geometry, sw); return sw.ToString(); } // // ********************************************************************** /// <summary> /// Converts a AbstractGeometry to its Well-known Text representation. /// </summary> /// <param name="geometry">A geometry to process.</param> /// <param name="writer">Stream to write out the geometry's text representation.</param> /// <remarks> /// AbstractGeometry is written to the output stream as &lt;Gemoetry Tagged Text&gt; string (see the OpenGIS /// Simple Features Specification). /// </remarks> // ********************************************************************** // public static void Write(IGeometry geometry, StringWriter writer) { AppendGeometryTaggedText(geometry, writer); } #endregion #region Private Static Methods // // ********************************************************************** /// <summary> /// Converts a AbstractGeometry to &lt;AbstractGeometry Tagged Text &gt; format, then Appends it to the writer. /// </summary> /// <param name="geometry">The AbstractGeometry to process.</param> /// <param name="writer">The output stream to Append to.</param> // ********************************************************************** // private static void AppendGeometryTaggedText(IGeometry geometry, StringWriter writer) { if (geometry == null) throw new NullReferenceException("Cannot write Well-Known Text: geometry was null"); if (geometry is Point) { Point point = geometry as Point; AppendPointTaggedText(point, writer); } else if (geometry is LineString) AppendLineStringTaggedText(geometry as LineString, writer); else if (geometry is Polygon) AppendPolygonTaggedText(geometry as Polygon, writer); else if (geometry is MultiPoint) AppendMultiPointTaggedText(geometry as MultiPoint, writer); else if (geometry is MultiLineString) AppendMultiLineStringTaggedText(geometry as MultiLineString, writer); else if (geometry is MultiPolygon) AppendMultiPolygonTaggedText(geometry as MultiPolygon, writer); else if (geometry is GeometryCollection) AppendGeometryCollectionTaggedText(geometry as GeometryCollection, writer); else throw new NotSupportedException("Unsupported AbstractGeometry implementation:" + geometry.GetType().Name); } // // ********************************************************************** /// <summary> /// Converts a Coordinate to &lt;Point Tagged Text&gt; format, /// then Appends it to the writer. /// </summary> /// <param name="coordinate">the <code>Coordinate</code> to process</param> /// <param name="writer">the output writer to Append to</param> // ********************************************************************** // private static void AppendPointTaggedText(Point coordinate, StringWriter writer) { writer.Write("POINT "); AppendPointText(coordinate, writer); } // // ********************************************************************** /// <summary> /// Converts a LineString to LineString tagged text format, /// </summary> /// <param name="lineString">The LineString to process.</param> /// <param name="writer">The output stream writer to Append to.</param> // ********************************************************************** // private static void AppendLineStringTaggedText(LineString lineString, StringWriter writer) { writer.Write("LINESTRING "); AppendLineStringText(lineString, writer); } // // ********************************************************************** /// <summary> /// Converts a Polygon to &lt;Polygon Tagged Text&gt; format, /// then Appends it to the writer. /// </summary> /// <param name="polygon">Th Polygon to process.</param> /// <param name="writer">The stream writer to Append to.</param> // ********************************************************************** // private static void AppendPolygonTaggedText(Polygon polygon, StringWriter writer) { writer.Write("POLYGON "); AppendPolygonText(polygon, writer); } // // ********************************************************************** /// <summary> /// Converts a MultiPoint to &lt;MultiPoint Tagged Text&gt; /// format, then Appends it to the writer. /// </summary> /// <param name="multipoint">The MultiPoint to process.</param> /// <param name="writer">The output writer to Append to.</param> // ********************************************************************** // private static void AppendMultiPointTaggedText(MultiPoint multipoint, StringWriter writer) { writer.Write("MULTIPOINT "); AppendMultiPointText(multipoint, writer); } // // ********************************************************************** /// <summary> /// Converts a MultiLineString to &lt;MultiLineString Tagged /// Text&gt; format, then Appends it to the writer. /// </summary> /// <param name="multiLineString">The MultiLineString to process</param> /// <param name="writer">The output stream writer to Append to.</param> // ********************************************************************** // private static void AppendMultiLineStringTaggedText(MultiLineString multiLineString, StringWriter writer) { writer.Write("MULTILINESTRING "); AppendMultiLineStringText(multiLineString, writer); } // // ********************************************************************** /// <summary> /// Converts a MultiPolygon to &lt;MultiPolygon Tagged /// Text&gt; format, then Appends it to the writer. /// </summary> /// <param name="multiPolygon">The MultiPolygon to process</param> /// <param name="writer">The output stream writer to Append to.</param> // ********************************************************************** // private static void AppendMultiPolygonTaggedText(MultiPolygon multiPolygon, StringWriter writer) { writer.Write("MULTIPOLYGON "); AppendMultiPolygonText(multiPolygon, writer); } // // ********************************************************************** /// <summary> /// Converts a GeometryCollection to &lt;GeometryCollection Tagged /// Text&gt; format, then Appends it to the writer. /// </summary> /// <param name="geometryCollection">The GeometryCollection to process</param> /// <param name="writer">The output stream writer to Append to.</param> // ********************************************************************** // private static void AppendGeometryCollectionTaggedText(GeometryCollection geometryCollection, StringWriter writer) { writer.Write("GEOMETRYCOLLECTION "); AppendGeometryCollectionText(geometryCollection, writer); } // // ********************************************************************** /// <summary> /// Converts a Coordinate to Point Text format then Appends it to the writer. /// </summary> /// <param name="coordinate">The Coordinate to process.</param> /// <param name="writer">The output stream writer to Append to.</param> // ********************************************************************** // private static void AppendPointText(Point coordinate, StringWriter writer) { if (coordinate == null || coordinate.IsEmpty()) { writer.Write("EMPTY"); } else { writer.Write("("); AppendCoordinate(coordinate, writer); writer.Write(")"); } } // // ********************************************************************** /// <summary> /// Converts a Coordinate to &lt;Point&gt; format, then Appends /// it to the writer. /// </summary> /// <param name="coordinate">The Coordinate to process.</param> /// <param name="writer">The output writer to Append to.</param> // ********************************************************************** // private static void AppendCoordinate(Point coordinate, StringWriter writer) { for (uint i = 0; i < coordinate.NumOrdinates; i++) writer.Write(WriteNumber(coordinate[i]) + (i < coordinate.NumOrdinates - 1 ? " " : "")); } // // ********************************************************************** /// <summary> /// Converts a double to a string, not in scientific notation. /// </summary> /// <param name="d">The double to convert.</param> /// <returns> /// The double as a string, not in scientific notation. /// </returns> // ********************************************************************** // private static string WriteNumber(double d) { return d.ToString(Hydra.Framework.Mapping.Map.numberFormat_EnUS); } // // ********************************************************************** /// <summary> /// Converts a LineString to &lt;LineString Text&gt; format, then /// Appends it to the writer. /// </summary> /// <param name="lineString">The LineString to process.</param> /// <param name="writer">The output stream to Append to.</param> // ********************************************************************** // private static void AppendLineStringText(LineString lineString, StringWriter writer) { if (lineString == null || lineString.IsEmpty()) { writer.Write("EMPTY"); } else { writer.Write("("); for (int i = 0; i < lineString.NumPoints; i++) { if (i > 0) writer.Write(", "); AppendCoordinate(lineString.Vertices[i], writer); } writer.Write(")"); } } // // ********************************************************************** /// <summary> /// Converts a Polygon to &lt;Polygon Text&gt; format, then /// Appends it to the writer. /// </summary> /// <param name="polygon">The Polygon to process.</param> /// <param name="writer">The writer.</param> // ********************************************************************** // private static void AppendPolygonText(Polygon polygon, StringWriter writer) { if (polygon == null || polygon.IsEmpty()) { writer.Write("EMPTY"); } else { writer.Write("("); AppendLineStringText(polygon.ExteriorRing, writer); for (int i = 0; i < polygon.InteriorRings.Count; i++) { writer.Write(", "); AppendLineStringText(polygon.InteriorRings[i], writer); } writer.Write(")"); } } // // ********************************************************************** /// <summary> /// Converts a MultiPoint to &lt;MultiPoint Text&gt; format, then /// Appends it to the writer. /// </summary> /// <param name="multiPoint">The MultiPoint to process.</param> /// <param name="writer">The output stream writer to Append to.</param> // ********************************************************************** // private static void AppendMultiPointText(MultiPoint multiPoint, StringWriter writer) { if (multiPoint == null || multiPoint.IsEmpty()) { writer.Write("EMPTY"); } else { writer.Write("("); for (int i = 0; i < multiPoint.Points.Count; i++) { if (i > 0) writer.Write(", "); AppendCoordinate(multiPoint[i], writer); } writer.Write(")"); } } // // ********************************************************************** /// <summary> /// Converts a MultiLineString to &lt;MultiLineString Text&gt; /// format, then Appends it to the writer. /// </summary> /// <param name="multiLineString">The MultiLineString to process.</param> /// <param name="writer">The output stream writer to Append to.</param> // ********************************************************************** // private static void AppendMultiLineStringText(MultiLineString multiLineString, StringWriter writer) { if (multiLineString == null || multiLineString.IsEmpty()) { writer.Write("EMPTY"); } else { writer.Write("("); for (int i = 0; i < multiLineString.LineStrings.Count; i++) { if (i > 0) writer.Write(", "); AppendLineStringText(multiLineString[i], writer); } writer.Write(")"); } } // // ********************************************************************** /// <summary> /// Converts a MultiPolygon to &lt;MultiPolygon Text&gt; format, then Appends to it to the writer. /// </summary> /// <param name="multiPolygon">The MultiPolygon to process.</param> /// <param name="writer">The output stream to Append to.</param> // ********************************************************************** // private static void AppendMultiPolygonText(MultiPolygon multiPolygon, StringWriter writer) { if (multiPolygon == null || multiPolygon.IsEmpty()) { writer.Write("EMPTY"); } else { writer.Write("("); for (int i = 0; i < multiPolygon.Polygons.Count; i++) { if (i > 0) writer.Write(", "); AppendPolygonText(multiPolygon[i], writer); } writer.Write(")"); } } // // ********************************************************************** /// <summary> /// Converts a GeometryCollection to &lt;GeometryCollection Text &gt; format, then Appends it to the writer. /// </summary> /// <param name="geometryCollection">The GeometryCollection to process.</param> /// <param name="writer">The output stream writer to Append to.</param> // ********************************************************************** // private static void AppendGeometryCollectionText(GeometryCollection geometryCollection, StringWriter writer) { if (geometryCollection == null || geometryCollection.IsEmpty()) { writer.Write("EMPTY"); } else { writer.Write("("); for (int i = 0; i < geometryCollection.Collection.Count; i++) { if (i > 0) writer.Write(", "); AppendGeometryTaggedText(geometryCollection[i], writer); } writer.Write(")"); } } #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.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// An editor for making changes to symbol source declarations. /// </summary> public sealed class SymbolEditor { private readonly Solution _originalSolution; private Solution _currentSolution; private SymbolEditor(Solution solution) { _originalSolution = solution; _currentSolution = solution; } /// <summary> /// Creates a new <see cref="SymbolEditor"/> instance. /// </summary> public static SymbolEditor Create(Solution solution) { if (solution == null) { throw new ArgumentNullException(nameof(solution)); } return new SymbolEditor(solution); } /// <summary> /// Creates a new <see cref="SymbolEditor"/> instance. /// </summary> public static SymbolEditor Create(Document document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return new SymbolEditor(document.Project.Solution); } /// <summary> /// The original solution. /// </summary> public Solution OriginalSolution { get { return _originalSolution; } } /// <summary> /// The solution with the edits applied. /// </summary> public Solution ChangedSolution { get { return _currentSolution; } } /// <summary> /// The documents changed since the <see cref="SymbolEditor"/> was constructed. /// </summary> public IEnumerable<Document> GetChangedDocuments() { var solutionChanges = _currentSolution.GetChanges(_originalSolution); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { foreach (var id in projectChanges.GetAddedDocuments()) { yield return _currentSolution.GetDocument(id); } foreach (var id in projectChanges.GetChangedDocuments()) { yield return _currentSolution.GetDocument(id); } } foreach (var project in solutionChanges.GetAddedProjects()) { foreach (var id in project.DocumentIds) { yield return project.GetDocument(id); } } } /// <summary> /// Gets the current symbol for a source symbol. /// </summary> public async Task<ISymbol> GetCurrentSymbolAsync(ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken)) { var symbolId = DocumentationCommentId.CreateDeclarationId(symbol); // check to see if symbol is from current solution var project = _currentSolution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null) { return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false); } // check to see if it is from original solution project = _originalSolution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null) { return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false); } // try to find symbol from any project (from current solution) with matching assembly name foreach (var projectId in this.GetProjectsForAssembly(symbol.ContainingAssembly)) { var currentSymbol = await GetSymbolAsync(_currentSolution, projectId, symbolId, cancellationToken).ConfigureAwait(false); if (currentSymbol != null) { return currentSymbol; } } return null; } private ImmutableDictionary<string, ImmutableArray<ProjectId>> _assemblyNameToProjectIdMap; private ImmutableArray<ProjectId> GetProjectsForAssembly(IAssemblySymbol assembly) { if (_assemblyNameToProjectIdMap == null) { _assemblyNameToProjectIdMap = _originalSolution.Projects .ToLookup(p => p.AssemblyName, p => p.Id) .ToImmutableDictionary(g => g.Key, g => ImmutableArray.CreateRange(g)); } if (!_assemblyNameToProjectIdMap.TryGetValue(assembly.Name, out var projectIds)) { projectIds = ImmutableArray<ProjectId>.Empty; } return projectIds; } private async Task<ISymbol> GetSymbolAsync(Solution solution, ProjectId projectId, string symbolId, CancellationToken cancellationToken) { var comp = await solution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, comp).ToList(); if (symbols.Count == 1) { return symbols[0]; } else if (symbols.Count > 1) { #if false // if we have multiple matches, use the same index that it appeared as in the original solution. var originalComp = await this.originalSolution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false); var originalSymbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, originalComp).ToList(); var index = originalSymbols.IndexOf(originalSymbol); if (index >= 0 && index <= symbols.Count) { return symbols[index]; } #else return symbols[0]; #endif } return null; } /// <summary> /// Gets the current declarations for the specified symbol. /// </summary> public async Task<IReadOnlyList<SyntaxNode>> GetCurrentDeclarationsAsync(ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); return this.GetDeclarations(currentSymbol).ToImmutableReadOnlyListOrEmpty(); } /// <summary> /// Gets the declaration syntax nodes for a given symbol. /// </summary> private IEnumerable<SyntaxNode> GetDeclarations(ISymbol symbol) { return symbol.DeclaringSyntaxReferences .Select(sr => sr.GetSyntax()) .Select(n => SyntaxGenerator.GetGenerator(_originalSolution.Workspace, n.Language).GetDeclaration(n)) .Where(d => d != null); } /// <summary> /// Gets the best declaration node for adding members. /// </summary> private bool TryGetBestDeclarationForSingleEdit(ISymbol symbol, out SyntaxNode declaration) { declaration = GetDeclarations(symbol).FirstOrDefault(); return declaration != null; } /// <summary> /// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param> /// <param name="declaration">The declaration to edit.</param> /// <returns></returns> public delegate void DeclarationEditAction(DocumentEditor editor, SyntaxNode declaration); /// <summary> /// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param> /// <param name="declaration">The declaration to edit.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns></returns> public delegate Task AsyncDeclarationEditAction(DocumentEditor editor, SyntaxNode declaration, CancellationToken cancellationToken); /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); if (TryGetBestDeclarationForSingleEdit(currentSymbol, out var declaration)) { return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false); } return null; } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, DeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { return this.EditOneDeclarationAsync( symbol, (e, d, c) => { editAction(e, d); return SpecializedTasks.EmptyTask; }, cancellationToken); } private void CheckSymbolArgument(ISymbol currentSymbol, ISymbol argSymbol) { if (currentSymbol == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_symbol_0_cannot_be_located_within_the_current_solution, argSymbol.Name)); } } private async Task<ISymbol> EditDeclarationAsync( ISymbol currentSymbol, SyntaxNode declaration, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken) { var doc = _currentSolution.GetDocument(declaration.SyntaxTree); var editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false); editor.TrackNode(declaration); await editAction(editor, declaration, cancellationToken).ConfigureAwait(false); var newDoc = editor.GetChangedDocument(); _currentSolution = newDoc.Project.Solution; // try to find new symbol by looking up via original declaration var model = await newDoc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(declaration); if (newDeclaration != null) { var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken); if (newSymbol != null) { return newSymbol; } } // otherwise fallback to rebinding with original symbol return await this.GetCurrentSymbolAsync(currentSymbol, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="location">A location within one of the symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, Location location, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var sourceTree = location.SourceTree; var doc = _currentSolution.GetDocument(sourceTree); if (doc != null) { return await this.EditOneDeclarationAsync(symbol, doc.Id, location.SourceSpan.Start, editAction, cancellationToken).ConfigureAwait(false); } doc = _originalSolution.GetDocument(sourceTree); if (doc != null) { return await this.EditOneDeclarationAsync(symbol, doc.Id, location.SourceSpan.Start, editAction, cancellationToken).ConfigureAwait(false); } throw new ArgumentException("The location specified is not part of the solution.", nameof(location)); } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="location">A location within one of the symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, Location location, DeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { return this.EditOneDeclarationAsync( symbol, location, (e, d, c) => { editAction(e, d); return SpecializedTasks.EmptyTask; }, cancellationToken); } private async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, DocumentId documentId, int position, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var decl = this.GetDeclarations(currentSymbol).FirstOrDefault(d => { var doc = _currentSolution.GetDocument(d.SyntaxTree); return doc != null && doc.Id == documentId && d.FullSpan.IntersectsWith(position); }); if (decl == null) { throw new ArgumentNullException(WorkspacesResources.The_position_is_not_within_the_symbol_s_declaration, nameof(position)); } return await this.EditDeclarationAsync(currentSymbol, decl, editAction, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the symbol's declaration where the member is also declared. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, ISymbol member, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var currentMember = await this.GetCurrentSymbolAsync(member, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentMember, member); // get first symbol declaration that encompasses at least one of the member declarations var memberDecls = this.GetDeclarations(currentMember).ToList(); var declaration = this.GetDeclarations(currentSymbol).FirstOrDefault(d => memberDecls.Any(md => md.SyntaxTree == d.SyntaxTree && d.FullSpan.IntersectsWith(md.FullSpan))); if (declaration == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_member_0_is_not_declared_within_the_declaration_of_the_symbol, member.Name)); } return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the symbol's declaration where the member is also declared. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, ISymbol member, DeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { return this.EditOneDeclarationAsync( symbol, member, (e, d, c) => { editAction(e, d); return SpecializedTasks.EmptyTask; }, cancellationToken); } /// <summary> /// Enables editing all the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to be edited.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditAllDeclarationsAsync( ISymbol symbol, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var declsByDocId = this.GetDeclarations(currentSymbol).ToLookup(d => _currentSolution.GetDocument(d.SyntaxTree).Id); var solutionEditor = new SolutionEditor(_currentSolution); foreach (var declGroup in declsByDocId) { var docId = declGroup.Key; var editor = await solutionEditor.GetDocumentEditorAsync(docId, cancellationToken).ConfigureAwait(false); foreach (var decl in declGroup) { editor.TrackNode(decl); // ensure the declaration gets tracked await editAction(editor, decl, cancellationToken).ConfigureAwait(false); } } _currentSolution = solutionEditor.GetChangedSolution(); // try to find new symbol by looking up via original declarations foreach (var declGroup in declsByDocId) { var doc = _currentSolution.GetDocument(declGroup.Key); var model = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var decl in declGroup) { var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(decl); if (newDeclaration != null) { var newSymbol = model.GetDeclaredSymbol(newDeclaration); if (newSymbol != null) { return newSymbol; } } } } // otherwise fallback to rebinding with original symbol return await GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing all the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to be edited.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditAllDeclarationsAsync( ISymbol symbol, DeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { return this.EditAllDeclarationsAsync( symbol, (e, d, c) => { editAction(e, d); return SpecializedTasks.EmptyTask; }, cancellationToken); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// WorkflowTriggerHistoriesOperations operations. /// </summary> internal partial class WorkflowTriggerHistoriesOperations : IServiceOperations<LogicManagementClient>, IWorkflowTriggerHistoriesOperations { /// <summary> /// Initializes a new instance of the WorkflowTriggerHistoriesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal WorkflowTriggerHistoriesOperations(LogicManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the LogicManagementClient /// </summary> public LogicManagementClient Client { get; private set; } /// <summary> /// Gets a list of workflow trigger histories. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='triggerName'> /// The workflow trigger name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkflowTriggerHistory>>> ListWithHttpMessagesAsync(string resourceGroupName, string workflowName, string triggerName, ODataQuery<WorkflowTriggerHistoryFilter> odataQuery = default(ODataQuery<WorkflowTriggerHistoryFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (workflowName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workflowName"); } if (triggerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "triggerName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workflowName", workflowName); tracingParameters.Add("triggerName", triggerName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/triggers/{triggerName}/histories").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName)); _url = _url.Replace("{triggerName}", System.Uri.EscapeDataString(triggerName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkflowTriggerHistory>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkflowTriggerHistory>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a workflow trigger history. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='triggerName'> /// The workflow trigger name. /// </param> /// <param name='historyName'> /// The workflow trigger history name. Corresponds to the run name for triggers /// that resulted in a run. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<WorkflowTriggerHistory>> GetWithHttpMessagesAsync(string resourceGroupName, string workflowName, string triggerName, string historyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (workflowName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workflowName"); } if (triggerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "triggerName"); } if (historyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "historyName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workflowName", workflowName); tracingParameters.Add("triggerName", triggerName); tracingParameters.Add("historyName", historyName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/triggers/{triggerName}/histories/{historyName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName)); _url = _url.Replace("{triggerName}", System.Uri.EscapeDataString(triggerName)); _url = _url.Replace("{historyName}", System.Uri.EscapeDataString(historyName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WorkflowTriggerHistory>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkflowTriggerHistory>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Resubmits a workflow run based on the trigger history. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='triggerName'> /// The workflow trigger name. /// </param> /// <param name='historyName'> /// The workflow trigger history name. Corresponds to the run name for triggers /// that resulted in a run. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> ResubmitWithHttpMessagesAsync(string resourceGroupName, string workflowName, string triggerName, string historyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (workflowName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workflowName"); } if (triggerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "triggerName"); } if (historyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "historyName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workflowName", workflowName); tracingParameters.Add("triggerName", triggerName); tracingParameters.Add("historyName", historyName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Resubmit", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/triggers/{triggerName}/histories/{historyName}/resubmit").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName)); _url = _url.Replace("{triggerName}", System.Uri.EscapeDataString(triggerName)); _url = _url.Replace("{historyName}", System.Uri.EscapeDataString(historyName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of workflow trigger histories. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkflowTriggerHistory>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkflowTriggerHistory>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkflowTriggerHistory>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
#version 430 core layout(local_size_x = 16, local_size_y = 16) in; //local workgroup size layout(binding=0) uniform sampler2D depth_tex; layout(binding=1) uniform sampler2D normals_tex; layout(binding=2) uniform sampler2D albedo_tex; layout(binding=3) uniform usamplerBuffer light_cull_tex; layout(binding=4) uniform sampler2DArray spot_shadow_tex[4]; layout(binding=8) uniform sampler2D ssao_tex; layout(binding=0) writeonly uniform image2D result_tex; uniform vec2 nearfar; uniform vec4 far_plane0; uniform vec2 far_plane1; uniform mat4 proj_mat; float proj_a, proj_b; shared float local_far, local_near; shared int local_lights_num; shared vec4 local_ll, local_ur; shared int local_lights[1024]; shared int local_num_of_lights; #include "common.h" #include "lighting_common.h" struct spot_data { vec4 diffuse_color; vec4 specular_color; //w is light_size vec4 vs_position; float attenuation_end; float attenuation_cutoff; // ]0...1], 1 (need low values for nice attenuation) float radius; float spot_exponent; vec4 spot_direction; //w is spot_cutoff ([0...90], 180) mat4 shadow_mat; ivec4 index; }; //148 bytes, 9 vec4s + int layout(std140) uniform spot_light_data { spot_data d[200]; } sld; void main() { ivec2 global_id = ivec2( gl_GlobalInvocationID.xy ); vec2 global_size = textureSize( normals_tex, 0 ).xy; ivec2 local_id = ivec2( gl_LocalInvocationID.xy ); ivec2 local_size = ivec2( gl_WorkGroupSize.xy ); ivec2 group_id = ivec2( gl_WorkGroupID.xy ); ivec2 group_size = ivec2(global_size) / local_size; uint workgroup_index = gl_LocalInvocationIndex; vec2 texel = global_id / global_size; vec2 pos_xy; vec4 raw_albedo = texture( albedo_tex, texel ); vec4 raw_normal = vec4( 0 ); vec4 raw_depth = texture( depth_tex, texel ); float raw_ssao = texture( ssao_tex, texel ).x; vec4 out_color = vec4( 0 ); if( workgroup_index == 0 ) { local_ll = vec4( far_plane0.xyz, 1.0 ); local_ur = vec4( far_plane0.w, far_plane1.xy, 1.0 ); local_far = nearfar.y; //-1000 local_near = nearfar.x; //-2.5 local_num_of_lights = int(texelFetch(light_cull_tex, int((group_id.x * group_size.y + group_id.y) * 1024)).x); } barrier(); //local memory barrier float far = local_far; float near = local_near; //WARNING: need to linearize the depth in order to make it work... proj_a = -(far + near) / (far - near); proj_b = (-2 * far * near) / (far - near); float linear_depth = -proj_b / (raw_depth.x * 2 - 1 + proj_a); raw_depth.x = linear_depth / -far; vec3 ll, ur; ll = local_ll.xyz; ur = local_ur.xyz; //check for skybox bool early_rejection = ( raw_depth.x > 0.999 || raw_depth.x < 0.001 ); for( uint c = workgroup_index; c < local_num_of_lights; c += local_size.x * local_size.y ) { bool in_frustum = true; int index = int(c); local_lights[index] = int(texelFetch( light_cull_tex, int((group_id.x * group_size.y + group_id.y) * 1024 + c + 1) ).x); } barrier(); //local memory barrier if( !early_rejection ) { pos_xy = mix( local_ll.xy, local_ur.xy, texel.xy ); raw_depth.xyz = linear_depth_to_vs_pos( raw_depth.x, pos_xy, far ); raw_normal = texture( normals_tex, texel ); raw_normal.xyz = normalize(raw_normal.xyz * 2.0 - 1.0); //float gloss_factor = toksvig_aa( raw_normal.xyz, roughness_to_spec_power(raw_albedo.w) ); float gloss_factor = toksvig_aa( raw_normal.xyz, raw_albedo.w*255 ); //float gloss_factor = raw_albedo.w * 255; vec3 view_dir = normalize( -raw_depth.xyz ); for( int c = 0; c < local_num_of_lights; ++c ) { int index = local_lights[c]; int shadow_tex_index = sld.d[index].index.x; int shadow_layer_index = sld.d[index].index.y; vec3 light_pos = sld.d[index].vs_position.xyz; float light_radius = sld.d[index].radius; float rcp_light_radius = recip( light_radius ); vec3 light_dir; float attenuation = 0.0; light_dir = light_pos - raw_depth.xyz; float distance = length( light_dir ); light_dir = normalize( light_dir ); //out_color.xyz += vec3( distance > light_radius && distance < light_radius + 0.5 ? 1.0 : 0.0 ); // && dot( -light_dir, spot_direction_data[i].xyz ) > spot_cutoff_data[i] float coeff = 0.0; attenuation = ( light_radius - distance ) * recip( light_radius ); vec3 spot_direction = sld.d[index].spot_direction.xyz; float spot_cos_cutoff = sld.d[index].spot_direction.w; float spot_effect = dot( -light_dir, spot_direction ); if( spot_effect > spot_cos_cutoff ) { float spot_exponent = sld.d[index].spot_exponent; spot_effect = pow( spot_effect, spot_exponent ); //if( attenuation > 0.0 ) //{ attenuation = spot_effect * recip( 1.0 - attenuation ) * attenuation + 1.0; // attenuation = spot_effect * native_recip( attenuation ) + 1.0f; // attenuation = spot_effect * attenuation + 1.0f; //} } attenuation -= 1.0; if( attenuation > 0.0 ) { float shadow = 1; /**/ int count = 0; int size = 5; float scale = 1.0; float k = 80; float bias = 0.001; vec4 ls_pos = sld.d[index].shadow_mat * vec4(raw_depth.xyz, 1); if( ls_pos.w > 0.0 ) { vec4 shadow_coord = ls_pos / ls_pos.w; //transform to tex coords (0...1) if( bounds_check(shadow_coord.x) && bounds_check(shadow_coord.y) && bounds_check(shadow_coord.z) ) { vec2 texcoord = shadow_coord.xy; shadow = 0; scale /= textureSize( spot_shadow_tex[shadow_tex_index], 0 ).x; scale *= 10; vec2 poisson_samples_25[25] = { vec2(-0.09956584, -0.9506168), vec2(0.0945536, -0.537095), vec2(-0.4186222, -0.8271356), vec2(0.2749816, -0.8264546), vec2(-0.3254788, -0.499952), vec2(-0.809692, -0.4665135), vec2(-0.2234173, -0.1774993), vec2(-0.7175227, -0.1786787), vec2(-0.964484, 0.03171529), vec2(0.0664617, -0.09118196), vec2(0.4066602, -0.1230906), vec2(0.6525381, -0.4510389), vec2(-0.507311, 0.1346684), vec2(-0.2599327, 0.4192313), vec2(-0.6924328, 0.3792625), vec2(0.1341985, 0.2107346), vec2(-0.3915392, 0.8384292), vec2(0.2936738, 0.6246353), vec2(-0.03307898, 0.7678965), vec2(0.6329493, 0.08375981), vec2(0.9811257, -0.1799406), vec2(0.4678418, 0.358797), vec2(0.8280757, 0.404021), vec2(0.700793, 0.6918929), vec2(0.2785904, 0.9276251) }; /**/ for( int x = 0; x < 25; ++x ) { float distance_from_light = texture( spot_shadow_tex[shadow_tex_index], vec3(texcoord + scale * poisson_samples_25[x], shadow_layer_index) ).x; shadow += clamp( 2.0 - exp((abs(shadow_coord.z) - distance_from_light) * k), 0, 1 ); } shadow = shadow / 25.0; /**/ /** texcoord -= scale * vec2(1) * 0.5; for( int y = 0; y < size; ++y ) for( int x = 0; x < size; ++x ) { float distance_from_light = texture( spot_shadow_tex[shadow_tex_index], vec3(texcoord + scale * vec2(x, y), shadow_layer_index) ).x; shadow += clamp( 2.0 - exp((abs(shadow_coord.z) - distance_from_light) * k), 0, 1 ); ++count; } shadow = shadow / float(count); /**/ //float distance_from_light = texture( spot_shadow_tex[shadow_tex_index], vec3(texcoord, shadow_layer_index) ).x; //shadow = float( shadow_coord.z < distance_from_light ); //shadow = clamp( 2.0 - exp((shadow_coord.z - distance_from_light) * k), 0, 1 ); //out_color = vec4( shadow_tex_index * 0.25 ); //out_color = vec4( texcoord, 0, 1 ); //float distance_from_light = texture( spot_shadow_tex[shadow_tex_index], vec3(texcoord, shadow_layer_index) ).x; //shadow = clamp( 2.0 - exp((shadow_coord.z - distance_from_light) * k), 0, 1 ); //out_color += vec4( shadow ); //out_color = vec4( shadow_layer_index*0.5 ); } } /**/ /**/ if( shadow > 0.0 ) { out_color.xyz += brdf( index, raw_albedo.xyz, raw_normal.xyz, light_dir, view_dir, gloss_factor, attenuation, sld.d[index].diffuse_color.xyz, sld.d[index].specular_color.xyz ) * shadow * raw_ssao; //out_color = vec4(raw_ssao); } /**/ //out_color.xyz += attenuation * vec3(0, 0.75, 1) * 0.01; } } //out_color.xyz = max(raw_normal.xyz, 0); //view space normal //out_color.xyz = raw_albedo.xyz; //albedo //out_color.xyz = (float3)(raw_albedo.w); //specular intensity //out_color.xyz = vec3(raw_depth.x); //view space linear depth //out_color.xyz = raw_depth.xyz; //view space position //out_color.xyz += num_to_radar_colors( local_num_of_lights, 5 ); //out_color.xyz = vec3(abs(normalize(vs_position_data[13].xyz))); //out_color = vec4(float(out_color.x > 0)); } else { out_color.xyz = vec3(0, 0.75, 1); } //out_color = vec4(1); if( global_id.x <= global_size.x && global_id.y <= global_size.y ) { //imageStore( result_tex, global_id, vec4( clamp(linear_to_gamma(tonemap(out_color.xyz)), 0.0, 1.0), 1.0 ) ); //imageStore( result_tex, global_id, vec4( rgb_to_ycocg( clamp(tonemap(out_color.xyz), 0.0, 1.0), ivec2(global_id) ), 0, 1.0 ) ); imageStore( result_tex, global_id, vec4( clamp(tonemap(out_color.xyz), 0.0, 1.0), 1.0 ) ); //imageStore( result_tex, global_id, vec4( out_color.xyz, 1.0 ) ); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; using System.IO; using System.Text; using System.Xml; namespace System.Data.SqlClient { sealed internal class SqlStream : Stream { private SqlDataReader _reader; // reader we will stream off private int _columnOrdinal; private long _bytesCol; private int _bom; private byte[] _bufferedData; private bool _processAllRows; private bool _advanceReader; private bool _readFirstRow = false; private bool _endOfColumn = false; internal SqlStream(SqlDataReader reader, bool addByteOrderMark, bool processAllRows) : this(0, reader, addByteOrderMark, processAllRows, true) { } internal SqlStream(int columnOrdinal, SqlDataReader reader, bool addByteOrderMark, bool processAllRows, bool advanceReader) { _columnOrdinal = columnOrdinal; _reader = reader; _bom = addByteOrderMark ? 0xfeff : 0; _processAllRows = processAllRows; _advanceReader = advanceReader; } override public bool CanRead { get { return true; } } override public bool CanSeek { get { return false; } } override public bool CanWrite { get { return false; } } override public long Length { get { throw ADP.NotSupported(); } } override public long Position { get { throw ADP.NotSupported(); } set { throw ADP.NotSupported(); } } override protected void Dispose(bool disposing) { try { if (disposing && _advanceReader && _reader != null && !_reader.IsClosed) { _reader.Close(); } _reader = null; } finally { base.Dispose(disposing); } } override public void Flush() { throw ADP.NotSupported(); } override public int Read(byte[] buffer, int offset, int count) { int intCount = 0; int cBufferedData = 0; if ((null == _reader)) { throw ADP.StreamClosed(); } if (null == buffer) { throw ADP.ArgumentNull(nameof(buffer)); } if ((offset < 0) || (count < 0)) { throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? nameof(offset) : nameof(count))); } if (buffer.Length - offset < count) { throw ADP.ArgumentOutOfRange(nameof(count)); } // Need to find out if we should add byte order mark or not. // We need to add this if we are getting ntext xml, not if we are getting binary xml // Binary Xml always begins with the bytes 0xDF and 0xFF // If we aren't getting these, then we are getting unicode xml if (_bom > 0) { // Read and buffer the first two bytes _bufferedData = new byte[2]; cBufferedData = ReadBytes(_bufferedData, 0, 2); // Check to se if we should add the byte order mark if ((cBufferedData < 2) || ((_bufferedData[0] == 0xDF) && (_bufferedData[1] == 0xFF))) { _bom = 0; } while (count > 0) { if (_bom > 0) { buffer[offset] = (byte)_bom; _bom >>= 8; offset++; count--; intCount++; } else { break; } } } if (cBufferedData > 0) { while (count > 0) { buffer[offset++] = _bufferedData[0]; intCount++; count--; if ((cBufferedData > 1) && (count > 0)) { buffer[offset++] = _bufferedData[1]; intCount++; count--; break; } } _bufferedData = null; } intCount += ReadBytes(buffer, offset, count); return intCount; } private static bool AdvanceToNextRow(SqlDataReader reader) { Debug.Assert(reader != null && !reader.IsClosed); // this method skips empty result sets do { if (reader.Read()) { return true; } } while (reader.NextResult()); // no more rows return false; } private int ReadBytes(byte[] buffer, int offset, int count) { bool gotData = true; int intCount = 0; int cb = 0; if (_reader.IsClosed || _endOfColumn) { return 0; } try { while (count > 0) { // if no bytes were read, get the next row if (_advanceReader && (0 == _bytesCol)) { gotData = false; if (_readFirstRow && !_processAllRows) { // for XML column, stop processing after the first row // no op here - reader is closed after the end of this loop } else if (AdvanceToNextRow(_reader)) { _readFirstRow = true; if (_reader.IsDBNull(_columnOrdinal)) { // Handle row with DBNULL as empty data // for XML column, processing is stopped on the next loop since _readFirstRow is true continue; } // the value is not null, read it gotData = true; } // else AdvanceToNextRow has returned false - no more rows or result sets remained, stop processing } if (gotData) { cb = (int)_reader.GetBytesInternal(_columnOrdinal, _bytesCol, buffer, offset, count); if (cb < count) { _bytesCol = 0; gotData = false; if (!_advanceReader) { _endOfColumn = true; } } else { Debug.Assert(cb == count); _bytesCol += cb; } // we are guaranteed that cb is < Int32.Max since we always pass in count which is of type Int32 to // our getbytes interface count -= (int)cb; offset += (int)cb; intCount += (int)cb; } else { break; // no more data available, we are done } } if (!gotData && _advanceReader) { _reader.Close(); // Need to close the reader if we are done reading } } catch (Exception e) { if (_advanceReader && ADP.IsCatchableExceptionType(e)) { _reader.Close(); } throw; } return intCount; } internal XmlReader ToXmlReader(bool async = false) { return SqlTypes.SqlXml.CreateSqlXmlReader(this, closeInput: true, async: async); } override public long Seek(long offset, SeekOrigin origin) { throw ADP.NotSupported(); } override public void SetLength(long value) { throw ADP.NotSupported(); } override public void Write(byte[] buffer, int offset, int count) { throw ADP.NotSupported(); } } // XmlTextReader does not read all the bytes off the network buffers, so we have to cache it here in the random access // case. This causes double buffering and is a perf hit, but this is not the high perf way for accessing this type of data. // In the case of sequential access, we do not have to do any buffering since the XmlTextReader we return can become // invalid as soon as we move off the current column. sealed internal class SqlCachedStream : Stream { private int _currentPosition; // Position within the current array byte private int _currentArrayIndex; // Index into the _cachedBytes List private List<byte[]> _cachedBytes; private long _totalLength; // Reads off from the network buffer and caches bytes. Only reads one column value in the current row. internal SqlCachedStream(SqlCachedBuffer sqlBuf) { _cachedBytes = sqlBuf.CachedBytes; } override public bool CanRead { get { return true; } } override public bool CanSeek { get { return true; } } override public bool CanWrite { get { return false; } } override public long Length { get { return TotalLength; } } override public long Position { get { long pos = 0; if (_currentArrayIndex > 0) { for (int ii = 0; ii < _currentArrayIndex; ii++) { pos += _cachedBytes[ii].Length; } } pos += _currentPosition; return pos; } set { if (null == _cachedBytes) { throw ADP.StreamClosed(ADP.ParameterSetPosition); } SetInternalPosition(value, ADP.ParameterSetPosition); } } override protected void Dispose(bool disposing) { try { if (disposing && _cachedBytes != null) _cachedBytes.Clear(); _cachedBytes = null; _currentPosition = 0; _currentArrayIndex = 0; _totalLength = 0; } finally { base.Dispose(disposing); } } override public void Flush() { throw ADP.NotSupported(); } override public int Read(byte[] buffer, int offset, int count) { int cb; int intCount = 0; if (null == _cachedBytes) { throw ADP.StreamClosed(); } if (null == buffer) { throw ADP.ArgumentNull(nameof(buffer)); } if ((offset < 0) || (count < 0)) { throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? nameof(offset) : nameof(count))); } if (buffer.Length - offset < count) { throw ADP.ArgumentOutOfRange(nameof(count)); } if (_cachedBytes.Count <= _currentArrayIndex) { return 0; // Everything is read! } while (count > 0) { if (_cachedBytes[_currentArrayIndex].Length <= _currentPosition) { _currentArrayIndex++; // We are done reading this chunk, go to next if (_cachedBytes.Count > _currentArrayIndex) { _currentPosition = 0; } else { break; } } cb = _cachedBytes[_currentArrayIndex].Length - _currentPosition; if (cb > count) cb = count; Buffer.BlockCopy(_cachedBytes[_currentArrayIndex], _currentPosition, buffer, offset, cb); _currentPosition += cb; count -= (int)cb; offset += (int)cb; intCount += (int)cb; } return intCount; } override public long Seek(long offset, SeekOrigin origin) { long pos = 0; if (null == _cachedBytes) { throw ADP.StreamClosed(); } switch (origin) { case SeekOrigin.Begin: SetInternalPosition(offset, nameof(offset)); break; case SeekOrigin.Current: pos = offset + Position; SetInternalPosition(pos, nameof(offset)); break; case SeekOrigin.End: pos = TotalLength + offset; SetInternalPosition(pos, nameof(offset)); break; default: throw ADP.InvalidSeekOrigin(nameof(offset)); } return pos; } override public void SetLength(long value) { throw ADP.NotSupported(); } override public void Write(byte[] buffer, int offset, int count) { throw ADP.NotSupported(); } private void SetInternalPosition(long lPos, string argumentName) { long pos = lPos; if (pos < 0) { throw new ArgumentOutOfRangeException(argumentName); } for (int ii = 0; ii < _cachedBytes.Count; ii++) { if (pos > _cachedBytes[ii].Length) { pos -= _cachedBytes[ii].Length; } else { _currentArrayIndex = ii; _currentPosition = (int)pos; return; } } if (pos > 0) throw new ArgumentOutOfRangeException(argumentName); } private long TotalLength { get { if ((_totalLength == 0) && (_cachedBytes != null)) { long pos = 0; for (int ii = 0; ii < _cachedBytes.Count; ii++) { pos += _cachedBytes[ii].Length; } _totalLength = pos; } return _totalLength; } } } sealed internal class SqlStreamingXml { private int _columnOrdinal; private SqlDataReader _reader; private XmlReader _xmlReader; private XmlWriter _xmlWriter; private StringWriter _strWriter; private long _charsRemoved; public SqlStreamingXml(int i, SqlDataReader reader) { _columnOrdinal = i; _reader = reader; } public void Close() { ((IDisposable)_xmlWriter).Dispose(); ((IDisposable)_xmlReader).Dispose(); _reader = null; _xmlReader = null; _xmlWriter = null; _strWriter = null; } public int ColumnOrdinal { get { return _columnOrdinal; } } public long GetChars(long dataIndex, char[] buffer, int bufferIndex, int length) { if (_xmlReader == null) { SqlStream sqlStream = new SqlStream(_columnOrdinal, _reader, true /* addByteOrderMark */, false /* processAllRows*/, false /*advanceReader*/); _xmlReader = sqlStream.ToXmlReader(); _strWriter = new StringWriter((System.IFormatProvider)null); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = true; // close the memory stream when done writerSettings.ConformanceLevel = ConformanceLevel.Fragment; _xmlWriter = XmlWriter.Create(_strWriter, writerSettings); } int charsToSkip = 0; int cnt = 0; if (dataIndex < _charsRemoved) { throw ADP.NonSeqByteAccess(dataIndex, _charsRemoved, nameof(GetChars)); } else if (dataIndex > _charsRemoved) { charsToSkip = (int)(dataIndex - _charsRemoved); } // If buffer parameter is null, we have to return -1 since there is no way for us to know the // total size up front without reading and converting the XML. if (buffer == null) { return (long)(-1); } StringBuilder strBldr = _strWriter.GetStringBuilder(); while (!_xmlReader.EOF) { if (strBldr.Length >= (length + charsToSkip)) { break; } // Can't call _xmlWriter.WriteNode here, since it reads all of the data in before returning the first char. // Do own implementation of WriteNode instead that reads just enough data to return the required number of chars //_xmlWriter.WriteNode(_xmlReader, true); // _xmlWriter.Flush(); WriteXmlElement(); if (charsToSkip > 0) { // Aggressively remove the characters we want to skip to avoid growing StringBuilder size too much cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip; strBldr.Remove(0, cnt); charsToSkip -= cnt; _charsRemoved += (long)cnt; } } if (charsToSkip > 0) { cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip; strBldr.Remove(0, cnt); charsToSkip -= cnt; _charsRemoved += (long)cnt; } if (strBldr.Length == 0) { return 0; } // At this point charsToSkip must be 0 Debug.Assert(charsToSkip == 0); cnt = strBldr.Length < length ? strBldr.Length : length; for (int i = 0; i < cnt; i++) { buffer[bufferIndex + i] = strBldr[i]; } // Remove the characters we have already returned strBldr.Remove(0, cnt); _charsRemoved += (long)cnt; return (long)cnt; } // This method duplicates the work of XmlWriter.WriteNode except that it reads one element at a time // instead of reading the entire node like XmlWriter. private void WriteXmlElement() { if (_xmlReader.EOF) return; bool canReadChunk = _xmlReader.CanReadValueChunk; char[] writeNodeBuffer = null; // Constants const int WriteNodeBufferSize = 1024; _xmlReader.Read(); switch (_xmlReader.NodeType) { case XmlNodeType.Element: _xmlWriter.WriteStartElement(_xmlReader.Prefix, _xmlReader.LocalName, _xmlReader.NamespaceURI); _xmlWriter.WriteAttributes(_xmlReader, true); if (_xmlReader.IsEmptyElement) { _xmlWriter.WriteEndElement(); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (writeNodeBuffer == null) { writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = _xmlReader.ReadValueChunk(writeNodeBuffer, 0, WriteNodeBufferSize)) > 0) { _xmlWriter.WriteChars(writeNodeBuffer, 0, read); } } else { _xmlWriter.WriteString(_xmlReader.Value); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: _xmlWriter.WriteWhitespace(_xmlReader.Value); break; case XmlNodeType.CDATA: _xmlWriter.WriteCData(_xmlReader.Value); break; case XmlNodeType.EntityReference: _xmlWriter.WriteEntityRef(_xmlReader.Name); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: _xmlWriter.WriteProcessingInstruction(_xmlReader.Name, _xmlReader.Value); break; case XmlNodeType.DocumentType: _xmlWriter.WriteDocType(_xmlReader.Name, _xmlReader.GetAttribute("PUBLIC"), _xmlReader.GetAttribute("SYSTEM"), _xmlReader.Value); break; case XmlNodeType.Comment: _xmlWriter.WriteComment(_xmlReader.Value); break; case XmlNodeType.EndElement: _xmlWriter.WriteFullEndElement(); break; } _xmlWriter.Flush(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TokenApi.Areas.HelpPage.ModelDescriptions; using TokenApi.Areas.HelpPage.Models; namespace TokenApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* Copyright (c) 2006- DEVSENSE Copyright (c) 2004-2006 Tomas Matousek, Ladislav Prosek, Vaclav Novak and Martin Maly. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Diagnostics; using System.Reflection.Emit; using PHP.Core.AST; using PHP.Core.Emit; using PHP.Core.Parsers; namespace PHP.Core.Compiler.AST { partial class NodeCompilers { #region VariableUse /// <summary> /// Base class for variable uses. /// </summary> abstract class VariableUseCompiler<T> : VarLikeConstructUseCompiler<T>, IVariableUseCompiler where T : VariableUse { internal abstract PhpTypeCode EmitAssign(T/*!*/node, CodeGenerator codeGenerator); internal abstract PhpTypeCode EmitIsset(T/*!*/node, CodeGenerator codeGenerator, bool empty); internal abstract void EmitUnset(T/*!*/node, CodeGenerator codeGenerator); #region IVariableUseCompiler Members PhpTypeCode IVariableUseCompiler.EmitAssign(VariableUse node, CodeGenerator codeGenerator) { return EmitAssign((T)node, codeGenerator); } PhpTypeCode IVariableUseCompiler.EmitIsset(VariableUse node, CodeGenerator codeGenerator, bool empty) { return EmitIsset((T)node, codeGenerator, empty); } void IVariableUseCompiler.EmitUnset(VariableUse node, CodeGenerator codeGenerator) { EmitUnset((T)node, codeGenerator); } #endregion } #endregion // possible access values for all VariableUse subclasses: // Read, Write, ReadRef, ReadUnknown, WriteRef, None #region CompoundVarUse abstract class CompoundVarUseCompiler<T> : VariableUseCompiler<T> where T : CompoundVarUse { } #endregion #region SimpleVarUse abstract class SimpleVarUseCompiler<T> : CompoundVarUseCompiler<T>, ISimpleVarUseCompiler where T : SimpleVarUse { /// <summary> /// Points to a method that emits code to be placed after the new instance field value has /// been loaded onto the evaluation stack. /// </summary> internal AssignmentCallback assignmentCallback; /// <summary> /// A holder of a temporary local variable which is used to obtain address of a variable /// stored in runtime variables table when methods from <see cref="PHP.Core.Operators"/> /// expecting a ref argument are invoked. /// </summary> /// <remarks>After the operator is invoked, the result should be stored back to table and this /// holder may be released. This holder does not take place in optimalized user functions and methods of /// user classes as the address of a variable shoul be obtained directly (variables are defined as /// locals).</remarks> protected LocalBuilder TabledLocalAddressStorage; internal abstract void EmitName(T/*!*/node, CodeGenerator codeGenerator); internal abstract PhpTypeCode EmitLoad(T/*!*/node, CodeGenerator codeGenerator); internal abstract void EmitLoadAddress(T/*!*/node, CodeGenerator codeGenerator); internal abstract void EmitLoadAddress_StoreBack(T/*!*/node, CodeGenerator codeGenerator); internal abstract void EmitLoadAddress_StoreBack(T/*!*/node, CodeGenerator codeGenerator, bool duplicate_value); internal abstract void EmitLoadRef(T/*!*/node, CodeGenerator codeGenerator); internal abstract void EmitStorePrepare(T/*!*/node, CodeGenerator codeGenerator); internal abstract void EmitStoreAssign(T/*!*/node, CodeGenerator codeGenerator); internal abstract void EmitStoreRefPrepare(T/*!*/node, CodeGenerator codeGenerator); internal abstract void EmitStoreRefAssign(T/*!*/node, CodeGenerator codeGenerator); /// <summary> /// Loads the value represented by this object from the runtime variables table, /// stores it to a local variable and loads the address of this local. /// </summary> /// <param name="node">Instance.</param> /// <remarks>This method is used only in non-optimized user functions and global code. /// Specified local variable is obtained from current <see cref="ILEmitter"/> by /// <see cref="ILEmitter.GetTemporaryLocal"/> and stored to <see cref="TabledLocalAddressStorage"/> /// for later use. Once the local become useless, <see cref="ILEmitter.ReturnTemporaryLocal"/> /// should be called. /// </remarks> /// <param name="codeGenerator">Currently used <see cref="CodeGenerator"/>.</param> internal virtual void LoadTabledVariableAddress(T/*!*/node, CodeGenerator codeGenerator) { // This function should be call only once on every SimpleVarUse object // TODO: ASSERTION FAILS (e.g. PhpMyAdmin, common.lib.php) // Debug.Assert(this.TabledLocalAddressStorage == null); ILEmitter il = codeGenerator.IL; // Load the value represented by this node from the runtime variables table // LOAD Operators.GetVariableUnchecked(<script context>, <local variables table>, <variable name>); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); EmitName(node, codeGenerator); codeGenerator.IL.Emit(OpCodes.Call, Methods.Operators.GetVariableUnchecked); // Get local from ILEmitter this.TabledLocalAddressStorage = il.GetTemporaryLocal(Types.Object[0]); // Store the value il.Stloc(this.TabledLocalAddressStorage); // Load the address il.Ldloca(this.TabledLocalAddressStorage); } /// <summary> /// Stores the value represented by <see cref="TabledLocalAddressStorage"/> to the runtime variables table and /// returns the <see cref="TabledLocalAddressStorage"/> back to <c>temporaryLocals</c>. /// Duplicates the value if requested. /// </summary> /// <param name="node">Instance.</param> /// <param name="codeGenerator">Currently used <see cref="CodeGenerator"/>.</param> /// <param name="duplicate_value">If <c>true</c>, the value of specified local is left on the evaluation stack. /// </param> internal virtual void StoreTabledVariableBack(T/*!*/node, CodeGenerator codeGenerator, bool duplicate_value) { ILEmitter il = codeGenerator.IL; // CALL Operators.SetVariable(<local variables table>,<name>,<TabledLocalAddressStorage>); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); EmitName(node, codeGenerator); il.Ldloc(TabledLocalAddressStorage); il.Emit(OpCodes.Call, Methods.Operators.SetVariable); // If requested, load the changed value on the evaluation stack if (duplicate_value) il.Ldloc(this.TabledLocalAddressStorage); // Release temporary local il.ReturnTemporaryLocal(this.TabledLocalAddressStorage); } /// <summary> /// Emits IL instructions that read the value of an instance field. /// </summary> /// <param name="node">Instance.</param> /// <param name="codeGenerator">The current <see cref="CodeGenerator"/>.</param> /// <param name="wantRef">If <B>false</B> the field value should be left on the evaluation stack, /// if <B>true</B> the <see cref="PhpReference"/> should be left on the evaluation stack.</param> /// <returns> /// Nothing is expected on the evaluation stack. A <see cref="PhpReference"/> (if <paramref name="wantRef"/> /// is <B>true</B>) or the field value itself (if <paramref name="wantRef"/> is <B>false</B>) is left on the /// evaluation stack. /// </returns> internal virtual PhpTypeCode EmitReadField(T/*!*/node, CodeGenerator codeGenerator, bool wantRef) { ILEmitter il = codeGenerator.IL; DirectVarUse direct_instance = node.IsMemberOf as DirectVarUse; if (direct_instance != null && direct_instance.IsMemberOf == null && direct_instance.VarName.IsThisVariableName) { return EmitReadFieldOfThis(node, codeGenerator, wantRef); } if (!wantRef) { //codeGenerator.ChainBuilder.Lengthen(); //PhpTypeCode type_code = isMemberOf.Emit(codeGenerator); //Debug.Assert(type_code == PhpTypeCode.Object || type_code == PhpTypeCode.DObject); //// CALL Operators.GetProperty(STACK,<field name>,<type desc>,<quiet>); //EmitName(codeGenerator); //codeGenerator.EmitLoadClassContext(); //il.LoadBool(codeGenerator.ChainBuilder.QuietRead); //il.Emit(OpCodes.Call, Methods.Operators.GetProperty); //return PhpTypeCode.Object; string fieldName = (node is DirectVarUse) ? (node as DirectVarUse).VarName.Value : null; Expression fieldNameExpr = (node is IndirectVarUse) ? (node as IndirectVarUse).VarNameEx : null; bool quietRead = wantRef ? false : codeGenerator.ChainBuilder.QuietRead; return codeGenerator.CallSitesBuilder.EmitGetProperty( codeGenerator, wantRef, node.IsMemberOf, null, null, null, fieldName, fieldNameExpr, quietRead); } // call GetProperty/GetObjectPropertyRef codeGenerator.ChainBuilder.Lengthen(); // loads the variable which field is gotten: PhpTypeCode var_type_code = node.IsMemberOf.Emit(codeGenerator); if (codeGenerator.ChainBuilder.Exists) { Debug.Assert(var_type_code == PhpTypeCode.DObject); // CALL Operators.GetObjectPropertyRef(STACK,<field name>,<type desc>); EmitName(node, codeGenerator); codeGenerator.EmitLoadClassContext(); il.Emit(OpCodes.Call, Methods.Operators.GetObjectPropertyRef); } else { Debug.Assert(var_type_code == PhpTypeCode.ObjectAddress); // CALL Operators.GetPropertyRef(ref STACK,<field name>,<type desc>,<script context>); EmitName(node, codeGenerator); codeGenerator.EmitLoadClassContext(); codeGenerator.EmitLoadScriptContext(); il.Emit(OpCodes.Call, Methods.Operators.GetPropertyRef); // stores the value of variable back: SimpleVarUse simple_var = node.IsMemberOf as SimpleVarUse; if (simple_var != null) simple_var.EmitLoadAddress_StoreBack(codeGenerator); } return PhpTypeCode.PhpReference; } /// <summary> /// Emits IL instructions that read the value of a field of $this instance. /// </summary> /// <param name="node">Instance.</param> /// <param name="codeGenerator">The current <see cref="CodeGenerator"/>.</param> /// <param name="wantRef">If <B>false</B> the field value should be left on the evaluation stack, /// if <B>true</B> the <see cref="PhpReference"/> should be left on the evaluation stack.</param> /// <returns></returns> private PhpTypeCode EmitReadFieldOfThis(T/*!*/node, CodeGenerator/*!*/ codeGenerator, bool wantRef) { ILEmitter il = codeGenerator.IL; // $this->a switch (codeGenerator.LocationStack.LocationType) { case LocationTypes.GlobalCode: { // load $this from one of Main's arguments and check for null Label this_non_null = il.DefineLabel(); Label reading_over = il.DefineLabel(); codeGenerator.EmitLoadSelf(); il.Emit(OpCodes.Brtrue_S, this_non_null); EmitThisUsedOutOfObjectThrow(codeGenerator, wantRef); il.Emit(OpCodes.Br, reading_over); il.MarkLabel(this_non_null, true); // call GetObjectProperty/GetObjectPropertyRef EmitGetFieldOfPlace(node, codeGenerator.SelfPlace, codeGenerator, wantRef); il.MarkLabel(reading_over, true); break; } case LocationTypes.FunctionDecl: { EmitThisUsedOutOfObjectThrow(codeGenerator, wantRef); break; } case LocationTypes.MethodDecl: { CompilerLocationStack.MethodDeclContext context = codeGenerator.LocationStack.PeekMethodDecl(); if (context.Method.IsStatic) { EmitThisUsedOutOfObjectThrow(codeGenerator, wantRef); break; } // attempt direct field reading (DirectVarUse only) return EmitReadFieldOfThisInInstanceMethod(node, codeGenerator, wantRef); } } return wantRef ? PhpTypeCode.PhpReference : PhpTypeCode.Object; } /// <summary> /// Emits IL instructions that read the value of a field of $this instance when we know that we /// are in an instance method and hence there's a chance of actually resolving the field being read. /// </summary> /// <param name="node">Instance.</param> /// <param name="codeGenerator">The current <see cref="CodeGenerator"/>.</param> /// <param name="wantRef">If <B>false</B> the field value should be left on the evaluation stack, /// if <B>true</B> the <see cref="PhpReference"/> should be left on the evaluation stack.</param> internal virtual PhpTypeCode EmitReadFieldOfThisInInstanceMethod(T/*!*/node, CodeGenerator/*!*/ codeGenerator, bool wantRef) { // the override in DirectVarUse is a bit more sophisticated ;) return EmitGetFieldOfPlace(node, codeGenerator.SelfPlace, codeGenerator, wantRef); } /// <summary> /// Emits error reporting call when "this" variable is used out of object context. /// </summary> private static void EmitThisUsedOutOfObjectThrow(CodeGenerator/*!*/ codeGenerator, bool wantRef) { codeGenerator.EmitPhpException(Methods.PhpException.ThisUsedOutOfObjectContext); if (wantRef) codeGenerator.IL.Emit(OpCodes.Newobj, Constructors.PhpReference_Void); else codeGenerator.IL.Emit(OpCodes.Ldnull); } /// <summary> /// Emits <see cref="Operators.GetObjectProperty"/> or <see cref="Operators.GetObjectPropertyRef"/> /// on a specified argument variable. /// </summary> private PhpTypeCode EmitGetFieldOfPlace(T/*!*/node, IPlace/*!*/ arg, CodeGenerator/*!*/ codeGenerator, bool wantRef) { //ILEmitter il = codeGenerator.IL; //arg.EmitLoad(il); //EmitName(codeGenerator); //codeGenerator.EmitLoadClassContext(); //if (wantRef) //{ // il.Emit(OpCodes.Call, Methods.Operators.GetObjectPropertyRef); // return PhpTypeCode.PhpReference; //} //else //{ // il.LoadBool(codeGenerator.ChainBuilder.QuietRead); // il.Emit(OpCodes.Call, Methods.Operators.GetObjectProperty); // return PhpTypeCode.Object; //} string fieldName = (node is DirectVarUse) ? (node as DirectVarUse).VarName.Value : null; Expression fieldNameExpr = (node is IndirectVarUse) ? (node as IndirectVarUse).VarNameEx : null; bool quietRead = wantRef ? false : codeGenerator.ChainBuilder.QuietRead; return codeGenerator.CallSitesBuilder.EmitGetProperty( codeGenerator, wantRef, null, arg, null, null, fieldName, fieldNameExpr, quietRead); } private static void EmitCallSetObjectField(CodeGenerator/*!*/ codeGenerator, PhpTypeCode stackTypeCode) { // CALL Operators.SetObjectProperty(<STACK:instance>,<STACK:field name>,<STACK:field value>, <type desc>) codeGenerator.EmitLoadClassContext(); codeGenerator.IL.Emit(OpCodes.Call, Methods.Operators.SetObjectProperty); //always when function with void return argument is called it's necesarry to add nop instruction due to debugger if (codeGenerator.Context.Config.Compiler.Debug) { codeGenerator.IL.Emit(OpCodes.Nop); } } private static void EmitPopValue(CodeGenerator/*!*/ codeGenerator, PhpTypeCode stackTypeCode) { // just pop the value that was meant to be written codeGenerator.IL.Emit(OpCodes.Pop); } /// <summary> /// Emits IL instructions that write a value to an instance field. /// </summary> /// <param name="node">Instance.</param> /// <param name="codeGenerator">The current <see cref="CodeGenerator"/>.</param> /// <param name="writeRef">If <B>true</B> the value being written is a <see cref="PhpReference"/> /// instance, if <B>false</B> it is an <see cref="Object"/> instance.</param> /// <returns>Delegate to a method that emits code to be executed when the actual value has been /// loaded on the evaluation stack.</returns> /// <remarks> /// If the field could be resolved at compile time (because <see cref="VarLikeConstructUse.IsMemberOf"/> is <c>$this</c> or a /// variable is proved to be of a certain type by type analysis), direct field writing code is emitted. /// Otherwise, <see cref="Operators.SetProperty"/> or <see cref="Operators.SetObjectProperty"/> call is emitted. /// </remarks> internal virtual AssignmentCallback EmitWriteField(T/*!*/node, CodeGenerator/*!*/ codeGenerator, bool writeRef) { ILEmitter il = codeGenerator.IL; DirectVarUse direct_instance = node.IsMemberOf as DirectVarUse; if (direct_instance != null && direct_instance.IsMemberOf == null && direct_instance.VarName.IsThisVariableName) { return EmitWriteFieldOfThis(node, codeGenerator, writeRef); } if (node.IsMemberOf is ItemUse || node.IsMemberOf is StaticFieldUse || node.IsMemberOf.IsMemberOf != null) { // we are part of a chain // Lengthen for hop over -> codeGenerator.ChainBuilder.Lengthen(); FunctionCall funcCall = node.IsMemberOf as FunctionCall; if (funcCall == null) { node.IsMemberOf.Emit(codeGenerator); EmitName(node, codeGenerator); } else { codeGenerator.ChainBuilder.LoadAddressOfFunctionReturnValue = true; node.IsMemberOf.Emit(codeGenerator); codeGenerator.ChainBuilder.RecastValueReturnedByFunctionCall(); EmitName(node, codeGenerator); } return new AssignmentCallback(EmitCallSetObjectField); } else { return delegate(CodeGenerator codeGen, PhpTypeCode stackTypeCode) { codeGen.ChainBuilder.Lengthen(); // CALL Operators.SetProperty(STACK,ref <instance>,<field name>,<handle>,<script context>); node.IsMemberOf.Emit(codeGen); EmitName(node, codeGen); codeGen.EmitLoadClassContext(); codeGen.EmitLoadScriptContext(); // invoke the operator codeGen.IL.Emit(OpCodes.Call, Methods.Operators.SetProperty); }; } } /// <summary> /// Emits IL instructions that prepare a field of $this for writing. /// </summary> private AssignmentCallback EmitWriteFieldOfThis(T/*!*/node, CodeGenerator/*!*/ codeGenerator, bool writeRef) { ILEmitter il = codeGenerator.IL; // $this->a switch (codeGenerator.LocationStack.LocationType) { case LocationTypes.GlobalCode: { // load $this from one of Main's arguments and check for null Label this_non_null = il.DefineLabel(); codeGenerator.EmitLoadSelf(); il.Emit(OpCodes.Brtrue_S, this_non_null); codeGenerator.EmitPhpException(Methods.PhpException.ThisUsedOutOfObjectContext); il.Emit(OpCodes.Br, codeGenerator.ChainBuilder.ErrorLabel); il.MarkLabel(this_non_null, true); // prepare the stack for SetObjectProperty call codeGenerator.EmitLoadSelf(); EmitName(node, codeGenerator); return new AssignmentCallback(EmitCallSetObjectField); } case LocationTypes.FunctionDecl: { // always throws error codeGenerator.EmitPhpException(Methods.PhpException.ThisUsedOutOfObjectContext); return new AssignmentCallback(EmitPopValue); } case LocationTypes.MethodDecl: { CompilerLocationStack.MethodDeclContext context = codeGenerator.LocationStack.PeekMethodDecl(); if (context.Method.IsStatic) { // always throws error codeGenerator.EmitPhpException(Methods.PhpException.ThisUsedOutOfObjectContext); return new AssignmentCallback(EmitPopValue); } // attempt direct field writing (DirectVarUse only) return EmitWriteFieldOfThisInInstanceMethod(node, codeGenerator, writeRef); } } Debug.Fail("Invalid lcoation type."); return null; } /// <summary> /// Emits IL instructions that write the value of a field of $this instance when we know that we /// are in an instance method and hence there's a chance of actually resolving the field being written. /// </summary> /// <param name="node">Instance.</param> /// <param name="codeGenerator">The current <see cref="CodeGenerator"/>.</param> /// <param name="writeRef">If <B>true</B> the value being written is a <see cref="PhpReference"/>; if /// <B>false</B> the value being written is an <see cref="Object"/>.</param> /// <returns></returns> internal virtual AssignmentCallback EmitWriteFieldOfThisInInstanceMethod(T/*!*/node, CodeGenerator/*!*/ codeGenerator, bool writeRef) { // prepare for SetObjectProperty call codeGenerator.EmitLoadSelf(); EmitName(node, codeGenerator); return new AssignmentCallback(EmitCallSetObjectField); } #region ISimpleVarUseCompiler Members void ISimpleVarUseCompiler.EmitLoadAddress_StoreBack(SimpleVarUse node, CodeGenerator codeGenerator) { EmitLoadAddress_StoreBack((T)node, codeGenerator); } void ISimpleVarUseCompiler.EmitName(SimpleVarUse node, CodeGenerator codeGenerator) { EmitName((T)node, codeGenerator); } void ISimpleVarUseCompiler.EmitAssign(SimpleVarUse node, CodeGenerator codeGenerator) { EmitAssign((T)node, codeGenerator); } void ISimpleVarUseCompiler.EmitLoadAddress(SimpleVarUse node, CodeGenerator codeGenerator) { EmitLoadAddress((T)node, codeGenerator); } #endregion } #endregion } #region IVariableUseCompiler internal interface IVariableUseCompiler { PhpTypeCode EmitAssign(VariableUse/*!*/node, CodeGenerator codeGenerator); PhpTypeCode EmitIsset(VariableUse/*!*/node, CodeGenerator codeGenerator, bool empty); void EmitUnset(VariableUse/*!*/node, CodeGenerator codeGenerator); } internal static class VariableUseHelper { public static PhpTypeCode EmitAssign(this VariableUse/*!*/node, CodeGenerator codeGenerator) { return node.NodeCompiler<IVariableUseCompiler>().EmitAssign(node, codeGenerator); } public static PhpTypeCode EmitIsset(this VariableUse/*!*/node, CodeGenerator codeGenerator, bool empty) { return node.NodeCompiler<IVariableUseCompiler>().EmitIsset(node, codeGenerator, empty); } public static void EmitUnset(this VariableUse/*!*/node, CodeGenerator codeGenerator) { node.NodeCompiler<IVariableUseCompiler>().EmitUnset(node, codeGenerator); } } #endregion #region ISimpleVarUseCompiler interface ISimpleVarUseCompiler { void EmitLoadAddress_StoreBack(SimpleVarUse/*!*/node, CodeGenerator codeGenerator); void EmitName(SimpleVarUse/*!*/node, CodeGenerator codeGenerator); void EmitAssign(SimpleVarUse/*!*/node, CodeGenerator codeGenerator); void EmitLoadAddress(SimpleVarUse node, CodeGenerator codeGenerator); } static class SimpleVarUseHelper { public static void EmitLoadAddress_StoreBack(this SimpleVarUse/*!*/node, CodeGenerator codeGenerator) { node.NodeCompiler<ISimpleVarUseCompiler>().EmitLoadAddress_StoreBack(node, codeGenerator); } public static void EmitName(this SimpleVarUse/*!*/node, CodeGenerator codeGenerator) { node.NodeCompiler<ISimpleVarUseCompiler>().EmitName(node, codeGenerator); } public static void EmitAssign(this SimpleVarUse/*!*/node, CodeGenerator codeGenerator) { node.NodeCompiler<ISimpleVarUseCompiler>().EmitAssign(node, codeGenerator); } public static void EmitLoadAddress(this SimpleVarUse node, CodeGenerator codeGenerator) { node.NodeCompiler<ISimpleVarUseCompiler>().EmitLoadAddress(node, codeGenerator); } } #endregion }
// // Source.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2005-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Query; using Banshee.Base; using Banshee.Collection; using Banshee.Configuration; using Banshee.ServiceStack; namespace Banshee.Sources { public abstract class Source : ISource { private Source parent; private PropertyStore properties = new PropertyStore (); protected SourceMessage status_message; private List<SourceMessage> messages = new List<SourceMessage> (); private List<Source> child_sources = new List<Source> (); private ReadOnlyCollection<Source> read_only_children; private SourceSortType child_sort; private bool sort_children = true; private SchemaEntry<string> child_sort_schema; private SchemaEntry<bool> separate_by_type_schema; public event EventHandler Updated; public event EventHandler UserNotifyUpdated; public event EventHandler MessageNotify; public event SourceEventHandler ChildSourceAdded; public event SourceEventHandler ChildSourceRemoved; public delegate void OpenPropertiesDelegate (); protected Source (string generic_name, string name, int order) : this (generic_name, name, order, null) { } protected Source (string generic_name, string name, int order, string type_unique_id) : this () { GenericName = generic_name; Name = name; Order = order; TypeUniqueId = type_unique_id; SourceInitialize (); } protected Source () { child_sort = DefaultChildSort; } // This method is chained to subclasses intialize methods, // allowing at any state for delayed intialization by using the empty ctor. protected virtual void Initialize () { SourceInitialize (); } private void SourceInitialize () { // If this source is not defined in Banshee.Services, set its // ResourceAssembly to the assembly where it is defined. Assembly asm = Assembly.GetAssembly (this.GetType ());//Assembly.GetCallingAssembly (); if (asm != Assembly.GetExecutingAssembly ()) { Properties.Set<Assembly> ("ResourceAssembly", asm); } properties.PropertyChanged += OnPropertyChanged; read_only_children = new ReadOnlyCollection<Source> (child_sources); if (ApplicationContext.Debugging && ApplicationContext.CommandLine.Contains ("test-source-messages")) { TestMessages (); } LoadSortSchema (); } protected void OnSetupComplete () { /*ITrackModelSource tm_source = this as ITrackModelSource; if (tm_source != null) { tm_source.TrackModel.Parent = this; ServiceManager.DBusServiceManager.RegisterObject (tm_source.TrackModel); // TODO if/when browsable models can be added/removed on the fly, this would need to change to reflect that foreach (IListModel model in tm_source.FilterModels) { Banshee.Collection.ExportableModel exportable = model as Banshee.Collection.ExportableModel; if (exportable != null) { exportable.Parent = this; ServiceManager.DBusServiceManager.RegisterObject (exportable); } } }*/ } protected void Remove () { if (prefs_page != null) { prefs_page.Dispose (); } if (ServiceManager.SourceManager.ContainsSource (this)) { if (this.Parent != null) { this.Parent.RemoveChildSource (this); } else { ServiceManager.SourceManager.RemoveSource (this); } } } protected void PauseSorting () { sort_children = false; } protected void ResumeSorting () { sort_children = true; } #region Public Methods public virtual void Activate () { } public virtual void Deactivate () { } public virtual void Rename (string newName) { properties.SetString ("Name", newName); } public virtual bool AcceptsInputFromSource (Source source) { return false; } public virtual bool AcceptsUserInputFromSource (Source source) { return AcceptsInputFromSource (source); } public virtual void MergeSourceInput (Source source, SourceMergeType mergeType) { Log.ErrorFormat ("MergeSourceInput not implemented by {0}", this); } public virtual SourceMergeType SupportedMergeTypes { get { return SourceMergeType.None; } } public virtual void SetParentSource (Source parent) { this.parent = parent; } public virtual bool ContainsChildSource (Source child) { lock (Children) { return child_sources.Contains (child); } } public virtual void AddChildSource (Source child) { lock (Children) { if (!child_sources.Contains (child)) { child.SetParentSource (this); child_sources.Add (child); OnChildSourceAdded (child); } } } public virtual void RemoveChildSource (Source child) { lock (Children) { if (child.Children.Count > 0) { child.ClearChildSources (); } child_sources.Remove (child); OnChildSourceRemoved (child); } } public virtual void ClearChildSources () { lock (Children) { while (child_sources.Count > 0) { RemoveChildSource (child_sources[child_sources.Count - 1]); } } } private class SizeComparer : IComparer<Source> { public int Compare (Source a, Source b) { return a.Count.CompareTo (b.Count); } } public virtual void SortChildSources (SourceSortType sort_type) { child_sort = sort_type; child_sort_schema.Set (child_sort.Id); SortChildSources (); } public virtual void SortChildSources () { lock (this) { if (!sort_children) { return; } sort_children = false; } if (child_sort != null && child_sort.SortType != SortType.None) { lock (Children) { child_sort.Sort (child_sources, SeparateChildrenByType); int i = 0; foreach (Source child in child_sources) { // Leave children with negative orders alone, so they can be manually // placed at the top if (child.Order >= 0) { child.Order = i++; } } } } sort_children = true; } private void LoadSortSchema () { if (ChildSortTypes.Length == 0) { return; } if (unique_id == null && type_unique_id == null) { Hyena.Log.WarningFormat ("Trying to LoadSortSchema, but source's id not set! {0}", UniqueId); return; } child_sort_schema = CreateSchema<string> ("child_sort_id", DefaultChildSort.Id, "", ""); string child_sort_id = child_sort_schema.Get (); foreach (SourceSortType sort_type in ChildSortTypes) { if (sort_type.Id == child_sort_id) { child_sort = sort_type; break; } } separate_by_type_schema = CreateSchema<bool> ("separate_by_type", false, "", ""); SortChildSources (); } public T GetProperty<T> (string name, bool inherited) { return inherited ? GetInheritedProperty<T> (name) : Properties.Get<T> (name); } public T GetInheritedProperty<T> (string name) { return Properties.Contains (name) ? Properties.Get<T> (name) : Parent != null ? Parent.GetInheritedProperty<T> (name) : default (T); } #endregion #region Protected Methods public virtual void SetStatus (string message, bool error) { SetStatus (message, !error, !error, error ? "dialog-error" : null); } public virtual void SetStatus (string message, bool can_close, bool is_spinning, string icon_name) { lock (this) { if (status_message == null) { status_message = new SourceMessage (this); PushMessage (status_message); } string status_name = String.Format ("<i>{0}</i>", GLib.Markup.EscapeText (Name)); status_message.FreezeNotify (); status_message.Text = String.Format (GLib.Markup.EscapeText (message), status_name); status_message.CanClose = can_close; status_message.IsSpinning = is_spinning; status_message.SetIconName (icon_name); status_message.IsHidden = false; status_message.ClearActions (); } status_message.ThawNotify (); } public virtual void HideStatus () { lock (this) { if (status_message != null) { RemoveMessage (status_message); status_message = null; } } } public void PushMessage (SourceMessage message) { lock (this) { messages.Insert (0, message); message.Updated += HandleMessageUpdated; } OnMessageNotify (); } protected SourceMessage PopMessage () { try { lock (this) { if (messages.Count > 0) { SourceMessage message = messages[0]; message.Updated -= HandleMessageUpdated; messages.RemoveAt (0); return message; } return null; } } finally { OnMessageNotify (); } } protected void ClearMessages () { lock (this) { if (messages.Count > 0) { foreach (SourceMessage message in messages) { message.Updated -= HandleMessageUpdated; } messages.Clear (); OnMessageNotify (); } status_message = null; } } private void TestMessages () { int count = 0; SourceMessage message_3 = null; Application.RunTimeout (5000, delegate { if (count++ > 5) { if (count == 7) { RemoveMessage (message_3); } PopMessage (); return true; } else if (count > 10) { return false; } SourceMessage message = new SourceMessage (this); message.FreezeNotify (); message.Text = String.Format ("Testing message {0}", count); message.IsSpinning = count % 2 == 0; message.CanClose = count % 2 == 1; if (count % 3 == 0) { for (int i = 2; i < count; i++) { message.AddAction (new MessageAction (String.Format ("Button {0}", i))); } } message.ThawNotify (); PushMessage (message); if (count == 3) { message_3 = message; } return true; }); } public void RemoveMessage (SourceMessage message) { lock (this) { if (messages.Remove (message)) { message.Updated -= HandleMessageUpdated; OnMessageNotify (); } } } private void HandleMessageUpdated (object o, EventArgs args) { if (CurrentMessage == o && CurrentMessage.IsHidden) { PopMessage (); } OnMessageNotify (); } protected virtual void OnMessageNotify () { EventHandler handler = MessageNotify; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnChildSourceAdded (Source source) { SortChildSources (); source.Updated += OnChildSourceUpdated; ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = ChildSourceAdded; if (handler != null) { SourceEventArgs args = new SourceEventArgs (); args.Source = source; handler (args); } }); } protected virtual void OnChildSourceRemoved (Source source) { source.Updated -= OnChildSourceUpdated; ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = ChildSourceRemoved; if (handler != null) { SourceEventArgs args = new SourceEventArgs (); args.Source = source; handler (args); } }); } protected virtual void OnUpdated () { EventHandler handler = Updated; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnChildSourceUpdated (object o, EventArgs args) { SortChildSources (); } public void NotifyUser () { OnUserNotifyUpdated (); } protected void OnUserNotifyUpdated () { if (this != ServiceManager.SourceManager.ActiveSource) { EventHandler handler = UserNotifyUpdated; if (handler != null) { handler (this, EventArgs.Empty); } } } #endregion #region Private Methods private void OnPropertyChanged (object o, PropertyChangeEventArgs args) { OnUpdated (); } #endregion #region Public Properties public ReadOnlyCollection<Source> Children { get { return read_only_children; } } string [] ISource.Children { get { return null; } } public Source Parent { get { return parent; } } public virtual string TypeName { get { return GetType ().Name; } } private string unique_id; public string UniqueId { get { if (unique_id == null && type_unique_id == null) { Log.ErrorFormat ("Creating Source.UniqueId for {0} (type {1}), but TypeUniqueId is null; trace is {2}", this.Name, GetType ().Name, System.Environment.StackTrace); } return unique_id ?? (unique_id = String.Format ("{0}-{1}", this.GetType ().Name, TypeUniqueId)); } } private string type_unique_id; protected string TypeUniqueId { get { return type_unique_id; } set { type_unique_id = value; } } public virtual bool CanRename { get { return false; } } public virtual bool HasProperties { get { return false; } } public virtual bool HasViewableTrackProperties { get { return false; } } public virtual bool HasEditableTrackProperties { get { return false; } } public virtual string Name { get { return properties.Get<string> ("Name"); } set { properties.SetString ("Name", value); } } public virtual string GenericName { get { return properties.Get<string> ("GenericName"); } set { properties.SetString ("GenericName", value); } } public int Order { get { return properties.GetInteger ("Order"); } set { properties.SetInteger ("Order", value); } } public SourceMessage CurrentMessage { get { lock (this) { return messages.Count > 0 ? messages[0] : null; } } } public virtual bool ImplementsCustomSearch { get { return false; } } public virtual bool CanSearch { get { return false; } } public virtual string FilterQuery { get { return properties.Get<string> ("FilterQuery"); } set { properties.SetString ("FilterQuery", value); } } public TrackFilterType FilterType { get { return (TrackFilterType)properties.GetInteger ("FilterType"); } set { properties.SetInteger ("FilterType", (int)value); } } public virtual bool Expanded { get { return properties.GetBoolean ("Expanded"); } set { properties.SetBoolean ("Expanded", value); } } public virtual bool? AutoExpand { get { return true; } } public virtual PropertyStore Properties { get { return properties; } } public virtual bool CanActivate { get { return true; } } public virtual int Count { get { return 0; } } public virtual int EnabledCount { get { return Count; } } private string parent_conf_id; public string ParentConfigurationId { get { if (parent_conf_id == null) { parent_conf_id = (Parent ?? this).UniqueId.Replace ('.', '_'); } return parent_conf_id; } } private string conf_id; public string ConfigurationId { get { return conf_id ?? (conf_id = UniqueId.Replace ('.', '_')); } } public virtual int FilteredCount { get { return Count; } } public virtual string TrackModelPath { get { return null; } } public static readonly SourceSortType SortNameAscending = new SourceSortType ( "NameAsc", Catalog.GetString ("Name"), SortType.Ascending, null); // null comparer b/c we already fall back to sorting by name public static readonly SourceSortType SortSizeAscending = new SourceSortType ( "SizeAsc", Catalog.GetString ("Size Ascending"), SortType.Ascending, new SizeComparer ()); public static readonly SourceSortType SortSizeDescending = new SourceSortType ( "SizeDesc", Catalog.GetString ("Size Descending"), SortType.Descending, new SizeComparer ()); private static SourceSortType[] sort_types = new SourceSortType[] {}; public virtual SourceSortType[] ChildSortTypes { get { return sort_types; } } public SourceSortType ActiveChildSort { get { return child_sort; } } public virtual SourceSortType DefaultChildSort { get { return null; } } public bool SeparateChildrenByType { get { return separate_by_type_schema.Get (); } set { separate_by_type_schema.Set (value); SortChildSources (); } } #endregion #region Status Message Stuff private static DurationStatusFormatters duration_status_formatters = new DurationStatusFormatters (); public static DurationStatusFormatters DurationStatusFormatters { get { return duration_status_formatters; } } protected virtual int StatusFormatsCount { get { return duration_status_formatters.Count; } } public virtual int CurrentStatusFormat { get { return ConfigurationClient.Get<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", 0); } set { ConfigurationClient.Set<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", value); } } public SchemaEntry<T> CreateSchema<T> (string name) { return CreateSchema<T> (name, default(T), null, null); } public SchemaEntry<T> CreateSchema<T> (string name, T defaultValue, string shortDescription, string longDescription) { return new SchemaEntry<T> (String.Format ("sources.{0}", ParentConfigurationId), name, defaultValue, shortDescription, longDescription); } public SchemaEntry<T> CreateSchema<T> (string ns, string name, T defaultValue, string shortDescription, string longDescription) { return new SchemaEntry<T> (String.Format ("sources.{0}.{1}", ParentConfigurationId, ns), name, defaultValue, shortDescription, longDescription); } public virtual string PreferencesPageId { get { return null; } } private Banshee.Preferences.SourcePage prefs_page; public Banshee.Preferences.Page PreferencesPage { get { return prefs_page ?? (prefs_page = new Banshee.Preferences.SourcePage (this)); } } public void CycleStatusFormat () { int new_status_format = CurrentStatusFormat + 1; if (new_status_format >= StatusFormatsCount) { new_status_format = 0; } CurrentStatusFormat = new_status_format; } private const string STATUS_BAR_SEPARATOR = " \u2013 "; public virtual string GetStatusText () { StringBuilder builder = new StringBuilder (); int count = FilteredCount; if (count == 0) { return String.Empty; } var count_str = String.Format ("{0:N0}", count); builder.AppendFormat (GetPluralItemCountString (count), count_str); if (this is IDurationAggregator && StatusFormatsCount > 0) { var duration = ((IDurationAggregator)this).Duration; if (duration > TimeSpan.Zero) { builder.Append (STATUS_BAR_SEPARATOR); duration_status_formatters[CurrentStatusFormat] (builder, ((IDurationAggregator)this).Duration); } } if (this is IFileSizeAggregator) { long bytes = (this as IFileSizeAggregator).FileSize; if (bytes > 0) { builder.Append (STATUS_BAR_SEPARATOR); builder.AppendFormat (new FileSizeQueryValue (bytes).ToUserQuery ()); } } return builder.ToString (); } public virtual string GetPluralItemCountString (int count) { return Catalog.GetPluralString ("{0} item", "{0} items", count); } #endregion public override string ToString () { return Name; } /*string IService.ServiceName { get { return String.Format ("{0}{1}", DBusServiceManager.MakeDBusSafeString (Name), "Source"); } }*/ // FIXME: Replace ISource with IDBusExportable when it's enabled again ISource ISource.Parent { get { if (Parent != null) { return ((Source)this).Parent; } else { return null /*ServiceManager.SourceManager*/; } } } } }
using System; using System.Collections.Generic; using System.Linq; using Avalonia.Input; using Avalonia.Input.Raw; using static Avalonia.X11.XLib; namespace Avalonia.X11 { unsafe class XI2Manager { private static readonly XiEventType[] DefaultEventTypes = new XiEventType[] { XiEventType.XI_Motion, XiEventType.XI_ButtonPress, XiEventType.XI_ButtonRelease, XiEventType.XI_Leave, XiEventType.XI_Enter, }; private static readonly XiEventType[] MultiTouchEventTypes = new XiEventType[] { XiEventType.XI_TouchBegin, XiEventType.XI_TouchUpdate, XiEventType.XI_TouchEnd }; private X11Info _x11; private bool _multitouch; private Dictionary<IntPtr, IXI2Client> _clients = new Dictionary<IntPtr, IXI2Client>(); class DeviceInfo { public int Id { get; } public XIValuatorClassInfo[] Valuators { get; private set; } public XIScrollClassInfo[] Scrollers { get; private set; } public DeviceInfo(XIDeviceInfo info) { Id = info.Deviceid; Update(info.Classes, info.NumClasses); } public virtual void Update(XIAnyClassInfo** classes, int num) { var valuators = new List<XIValuatorClassInfo>(); var scrollers = new List<XIScrollClassInfo>(); for (var c = 0; c < num; c++) { if (classes[c]->Type == XiDeviceClass.XIValuatorClass) valuators.Add(*((XIValuatorClassInfo**)classes)[c]); if (classes[c]->Type == XiDeviceClass.XIScrollClass) scrollers.Add(*((XIScrollClassInfo**)classes)[c]); } Valuators = valuators.ToArray(); Scrollers = scrollers.ToArray(); } public void UpdateValuators(Dictionary<int, double> valuators) { foreach (var v in valuators) { if (Valuators.Length > v.Key) Valuators[v.Key].Value = v.Value; } } } class PointerDeviceInfo : DeviceInfo { public PointerDeviceInfo(XIDeviceInfo info) : base(info) { } public bool HasScroll(ParsedDeviceEvent ev) { foreach (var val in ev.Valuators) if (Scrollers.Any(s => s.Number == val.Key)) return true; return false; } public bool HasMotion(ParsedDeviceEvent ev) { foreach (var val in ev.Valuators) if (Scrollers.All(s => s.Number != val.Key)) return true; return false; } } private PointerDeviceInfo _pointerDevice; private AvaloniaX11Platform _platform; public bool Init(AvaloniaX11Platform platform) { _platform = platform; _x11 = platform.Info; _multitouch = platform.Options?.EnableMultiTouch ?? true; var devices =(XIDeviceInfo*) XIQueryDevice(_x11.Display, (int)XiPredefinedDeviceId.XIAllMasterDevices, out int num); for (var c = 0; c < num; c++) { if (devices[c].Use == XiDeviceType.XIMasterPointer) { _pointerDevice = new PointerDeviceInfo(devices[c]); break; } } if(_pointerDevice == null) return false; /* int mask = 0; XISetMask(ref mask, XiEventType.XI_DeviceChanged); var emask = new XIEventMask { Mask = &mask, Deviceid = _pointerDevice.Id, MaskLen = XiEventMaskLen }; if (XISelectEvents(_x11.Display, _x11.RootWindow, &emask, 1) != Status.Success) return false; return true; */ return XiSelectEvents(_x11.Display, _x11.RootWindow, new Dictionary<int, List<XiEventType>> { [_pointerDevice.Id] = new List<XiEventType> { XiEventType.XI_DeviceChanged } }) == Status.Success; } public XEventMask AddWindow(IntPtr xid, IXI2Client window) { _clients[xid] = window; var eventsLength = DefaultEventTypes.Length; if (_multitouch) eventsLength += MultiTouchEventTypes.Length; var events = new List<XiEventType>(eventsLength); events.AddRange(DefaultEventTypes); if (_multitouch) events.AddRange(MultiTouchEventTypes); XiSelectEvents(_x11.Display, xid, new Dictionary<int, List<XiEventType>> {[_pointerDevice.Id] = events}); // We are taking over mouse input handling from here return XEventMask.PointerMotionMask | XEventMask.ButtonMotionMask | XEventMask.Button1MotionMask | XEventMask.Button2MotionMask | XEventMask.Button3MotionMask | XEventMask.Button4MotionMask | XEventMask.Button5MotionMask | XEventMask.ButtonPressMask | XEventMask.ButtonReleaseMask | XEventMask.LeaveWindowMask | XEventMask.EnterWindowMask; } public void OnWindowDestroyed(IntPtr xid) => _clients.Remove(xid); public void OnEvent(XIEvent* xev) { if (xev->evtype == XiEventType.XI_DeviceChanged) { var changed = (XIDeviceChangedEvent*)xev; _pointerDevice.Update(changed->Classes, changed->NumClasses); } if ((xev->evtype >= XiEventType.XI_ButtonPress && xev->evtype <= XiEventType.XI_Motion) || (xev->evtype >= XiEventType.XI_TouchBegin && xev->evtype <= XiEventType.XI_TouchEnd)) { var dev = (XIDeviceEvent*)xev; if (_clients.TryGetValue(dev->EventWindow, out var client)) OnDeviceEvent(client, new ParsedDeviceEvent(dev)); } if (xev->evtype == XiEventType.XI_Leave || xev->evtype == XiEventType.XI_Enter) { var rev = (XIEnterLeaveEvent*)xev; if (_clients.TryGetValue(rev->EventWindow, out var client)) OnEnterLeaveEvent(client, ref *rev); } } void OnEnterLeaveEvent(IXI2Client client, ref XIEnterLeaveEvent ev) { if (ev.evtype == XiEventType.XI_Leave) { var buttons = ParsedDeviceEvent.ParseButtonState(ev.buttons.MaskLen, ev.buttons.Mask); var detail = ev.detail; if ((detail == XiEnterLeaveDetail.XINotifyNonlinearVirtual || detail == XiEnterLeaveDetail.XINotifyNonlinear || detail == XiEnterLeaveDetail.XINotifyVirtual) && buttons == default) { client.ScheduleXI2Input(new RawPointerEventArgs(client.MouseDevice, (ulong)ev.time.ToInt64(), client.InputRoot, RawPointerEventType.LeaveWindow, new Point(ev.event_x, ev.event_y), buttons)); } } } void OnDeviceEvent(IXI2Client client, ParsedDeviceEvent ev) { if (ev.Type == XiEventType.XI_TouchBegin || ev.Type == XiEventType.XI_TouchUpdate || ev.Type == XiEventType.XI_TouchEnd) { var type = ev.Type == XiEventType.XI_TouchBegin ? RawPointerEventType.TouchBegin : (ev.Type == XiEventType.XI_TouchUpdate ? RawPointerEventType.TouchUpdate : RawPointerEventType.TouchEnd); client.ScheduleXI2Input(new RawTouchEventArgs(client.TouchDevice, ev.Timestamp, client.InputRoot, type, ev.Position, ev.Modifiers, ev.Detail)); return; } if (_multitouch && ev.Emulated) return; if (ev.Type == XiEventType.XI_Motion) { Vector scrollDelta = default; foreach (var v in ev.Valuators) { foreach (var scroller in _pointerDevice.Scrollers) { if (scroller.Number == v.Key) { var old = _pointerDevice.Valuators[scroller.Number].Value; // Value was zero after reset, ignore the event and use it as a reference next time if (old == 0) continue; var diff = (old - v.Value) / scroller.Increment; if (scroller.ScrollType == XiScrollType.Horizontal) scrollDelta = scrollDelta.WithX(scrollDelta.X + diff); else scrollDelta = scrollDelta.WithY(scrollDelta.Y + diff); } } } if (scrollDelta != default) client.ScheduleXI2Input(new RawMouseWheelEventArgs(client.MouseDevice, ev.Timestamp, client.InputRoot, ev.Position, scrollDelta, ev.Modifiers)); if (_pointerDevice.HasMotion(ev)) client.ScheduleXI2Input(new RawPointerEventArgs(client.MouseDevice, ev.Timestamp, client.InputRoot, RawPointerEventType.Move, ev.Position, ev.Modifiers)); } if (ev.Type == XiEventType.XI_ButtonPress && ev.Button >= 4 && ev.Button <= 7 && !ev.Emulated) { var scrollDelta = ev.Button switch { 4 => new Vector(0, 1), 5 => new Vector(0, -1), 6 => new Vector(1, 0), 7 => new Vector(-1, 0), _ => (Vector?)null }; if (scrollDelta.HasValue) client.ScheduleXI2Input(new RawMouseWheelEventArgs(client.MouseDevice, ev.Timestamp, client.InputRoot, ev.Position, scrollDelta.Value, ev.Modifiers)); } if (ev.Type == XiEventType.XI_ButtonPress || ev.Type == XiEventType.XI_ButtonRelease) { var down = ev.Type == XiEventType.XI_ButtonPress; var type = ev.Button switch { 1 => down ? RawPointerEventType.LeftButtonDown : RawPointerEventType.LeftButtonUp, 2 => down ? RawPointerEventType.MiddleButtonDown : RawPointerEventType.MiddleButtonUp, 3 => down ? RawPointerEventType.RightButtonDown : RawPointerEventType.RightButtonUp, 8 => down ? RawPointerEventType.XButton1Down : RawPointerEventType.XButton1Up, 9 => down ? RawPointerEventType.XButton2Down : RawPointerEventType.XButton2Up, _ => (RawPointerEventType?)null }; if (type.HasValue) client.ScheduleXI2Input(new RawPointerEventArgs(client.MouseDevice, ev.Timestamp, client.InputRoot, type.Value, ev.Position, ev.Modifiers)); } _pointerDevice.UpdateValuators(ev.Valuators); } } unsafe class ParsedDeviceEvent { public XiEventType Type { get; } public RawInputModifiers Modifiers { get; } public ulong Timestamp { get; } public Point Position { get; } public int Button { get; set; } public int Detail { get; set; } public bool Emulated { get; set; } public Dictionary<int, double> Valuators { get; } public static RawInputModifiers ParseButtonState(int len, byte* buttons) { RawInputModifiers rv = default; if (len > 0) { if (XIMaskIsSet(buttons, 1)) rv |= RawInputModifiers.LeftMouseButton; if (XIMaskIsSet(buttons, 2)) rv |= RawInputModifiers.MiddleMouseButton; if (XIMaskIsSet(buttons, 3)) rv |= RawInputModifiers.RightMouseButton; if (len > 1) { if (XIMaskIsSet(buttons, 8)) rv |= RawInputModifiers.XButton1MouseButton; if (XIMaskIsSet(buttons, 9)) rv |= RawInputModifiers.XButton2MouseButton; } } return rv; } public ParsedDeviceEvent(XIDeviceEvent* ev) { Type = ev->evtype; Timestamp = (ulong)ev->time.ToInt64(); var state = (XModifierMask)ev->mods.Effective; if (state.HasFlag(XModifierMask.ShiftMask)) Modifiers |= RawInputModifiers.Shift; if (state.HasFlag(XModifierMask.ControlMask)) Modifiers |= RawInputModifiers.Control; if (state.HasFlag(XModifierMask.Mod1Mask)) Modifiers |= RawInputModifiers.Alt; if (state.HasFlag(XModifierMask.Mod4Mask)) Modifiers |= RawInputModifiers.Meta; Modifiers = ParseButtonState(ev->buttons.MaskLen, ev->buttons.Mask); Valuators = new Dictionary<int, double>(); Position = new Point(ev->event_x, ev->event_y); var values = ev->valuators.Values; if(ev->valuators.Mask != null) for (var c = 0; c < ev->valuators.MaskLen * 8; c++) if (XIMaskIsSet(ev->valuators.Mask, c)) Valuators[c] = *values++; if (Type == XiEventType.XI_ButtonPress || Type == XiEventType.XI_ButtonRelease) Button = ev->detail; Detail = ev->detail; Emulated = ev->flags.HasFlag(XiDeviceEventFlags.XIPointerEmulated); } } interface IXI2Client { IInputRoot InputRoot { get; } void ScheduleXI2Input(RawInputEventArgs args); IMouseDevice MouseDevice { get; } TouchDevice TouchDevice { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using BTDB.Collections; namespace BTDB.IL.Caching; class CachingILDynamicType : IILDynamicType { readonly CachingILBuilder _cachingIlBuilder; readonly string _name; readonly Type _baseType; readonly Type[] _interfaces; StructList<IReplay> _instructions; Type? TrueContent { get; set; } interface IReplay { void ReplayTo(IILDynamicType target); void FinishReplay(IILDynamicType target); void FreeTemps(); bool Equals(IReplay? other); object TrueContent(); } public CachingILDynamicType(CachingILBuilder cachingIlBuilder, string name, Type baseType, Type[] interfaces) { _cachingIlBuilder = cachingIlBuilder; _name = name; _baseType = baseType; _interfaces = interfaces; } public IILMethod DefineMethod(string name, Type returns, Type[] parameters, MethodAttributes methodAttributes = MethodAttributes.Public) { var res = new Method((int)_instructions.Count, name, returns, parameters, methodAttributes); _instructions.Add(res); return res; } class Method : IReplay, IILMethodPrivate { readonly int _id; readonly string _name; readonly Type _returns; readonly Type[] _parameters; readonly MethodAttributes _methodAttributes; readonly CachingILGen _ilGen = new CachingILGen(); int _expectedLength = -1; IILMethodPrivate? _trueContent; public Method(int id, string name, Type returns, Type[] parameters, MethodAttributes methodAttributes) { _id = id; _name = name; _returns = returns; _parameters = parameters; _methodAttributes = methodAttributes; InitLocals = true; } public void ReplayTo(IILDynamicType target) { _trueContent = (IILMethodPrivate)target.DefineMethod(_name, _returns, _parameters, _methodAttributes); _trueContent.InitLocals = InitLocals; if (_expectedLength >= 0) _trueContent.ExpectedLength(_expectedLength); } public void FinishReplay(IILDynamicType target) { _ilGen.ReplayTo(_trueContent!.Generator); } public void FreeTemps() { _trueContent = null; _ilGen.FreeTemps(); } public bool Equals(IReplay? other) { if (!(other is Method v)) return false; return _id == v._id && _name == v._name && _returns == v._returns && _methodAttributes == v._methodAttributes && _parameters.SequenceEqual(v._parameters) && InitLocals == v.InitLocals && _ilGen.Equals(v._ilGen); } public override bool Equals(object obj) { return Equals(obj as IReplay); } public override int GetHashCode() { unchecked { var hashCode = _id; hashCode = (hashCode * 397) ^ _name.GetHashCode(); hashCode = (hashCode * 397) ^ _returns.GetHashCode(); return hashCode; } } public object TrueContent() { return _trueContent!; } public void ExpectedLength(int length) { _expectedLength = length; } public bool InitLocals { get; set; } public IILGen Generator => _ilGen; public MethodInfo TrueMethodInfo => _trueContent!.TrueMethodInfo; public Type ReturnType => _returns; public Type[] Parameters => _parameters; } public IILField DefineField(string name, Type type, FieldAttributes fieldAttributes) { var res = new Field((int)_instructions.Count, name, type, fieldAttributes); _instructions.Add(res); return res; } class Field : IReplay, IILFieldPrivate { readonly int _id; readonly string _name; readonly Type _type; readonly FieldAttributes _fieldAttributes; IILFieldPrivate? _trueContent; public Field(int id, string name, Type type, FieldAttributes fieldAttributes) { _id = id; _name = name; _type = type; _fieldAttributes = fieldAttributes; } public void ReplayTo(IILDynamicType target) { _trueContent = (IILFieldPrivate)target.DefineField(_name, _type, _fieldAttributes); } public void FreeTemps() { _trueContent = null; } public bool Equals(IReplay? other) { if (!(other is Field v)) return false; return _id == v._id && _name == v._name && _type == v._type && _fieldAttributes == v._fieldAttributes; } public override bool Equals(object obj) { return Equals(obj as IReplay); } public override int GetHashCode() { unchecked { var hashCode = _id; hashCode = (hashCode * 397) ^ _name.GetHashCode(); hashCode = (hashCode * 397) ^ _type.GetHashCode(); return hashCode; } } public object TrueContent() { return _trueContent!; } public Type FieldType => _type; public string Name => _name; public void FinishReplay(IILDynamicType target) { } public FieldBuilder TrueField => _trueContent!.TrueField; } public IILEvent DefineEvent(string name, EventAttributes eventAttributes, Type type) { var res = new Event((int)_instructions.Count, name, eventAttributes, type); _instructions.Add(res); return res; } class Event : IReplay, IILEvent { readonly int _id; readonly string _name; readonly EventAttributes _eventAttributes; readonly Type _type; IILEvent? _trueContent; IReplay? _addOnMethod; IReplay? _removeOnMethod; public Event(int id, string name, EventAttributes eventAttributes, Type type) { _id = id; _name = name; _eventAttributes = eventAttributes; _type = type; } public void ReplayTo(IILDynamicType target) { _trueContent = target.DefineEvent(_name, _eventAttributes, _type); } public void FreeTemps() { _trueContent = null; } public bool Equals(IReplay? other) { if (!(other is Event v)) return false; return _id == v._id && _name == v._name && _eventAttributes == v._eventAttributes && _type == v._type; } public override bool Equals(object obj) { return Equals(obj as IReplay); } public override int GetHashCode() { unchecked { var hashCode = _id; hashCode = (hashCode * 397) ^ _name.GetHashCode(); hashCode = (hashCode * 397) ^ _type.GetHashCode(); return hashCode; } } public object TrueContent() { return _trueContent!; } public void SetAddOnMethod(IILMethod method) { _addOnMethod = (IReplay)method; } public void SetRemoveOnMethod(IILMethod method) { _removeOnMethod = (IReplay)method; } public void FinishReplay(IILDynamicType target) { _trueContent!.SetAddOnMethod((IILMethod)_addOnMethod!.TrueContent()); _trueContent.SetRemoveOnMethod((IILMethod)_removeOnMethod!.TrueContent()); } } public IILMethod DefineConstructor(Type[] parameters) { return DefineConstructor(parameters, Array.Empty<string>()); } public IILMethod DefineConstructor(Type[] parameters, string[] parametersNames) { var res = new Constructor((int)_instructions.Count, parameters, parametersNames); _instructions.Add(res); return res; } class Constructor : IReplay, IILMethod { readonly int _id; readonly Type[] _parameters; readonly string[] _parametersNames; readonly CachingILGen _ilGen = new CachingILGen(); int _expectedLength = -1; IILMethod? _trueContent; public Constructor(int id, Type[] parameters, string[] parametersNames) { _id = id; _parameters = parameters; _parametersNames = parametersNames; InitLocals = true; } public void ReplayTo(IILDynamicType target) { _trueContent = target.DefineConstructor(_parameters, _parametersNames); _trueContent.InitLocals = InitLocals; if (_expectedLength >= 0) _trueContent.ExpectedLength(_expectedLength); } public void FinishReplay(IILDynamicType target) { _ilGen.ReplayTo(_trueContent!.Generator); } public void FreeTemps() { _trueContent = null; _ilGen.FreeTemps(); } public bool Equals(IReplay? other) { if (!(other is Constructor v)) return false; return _id == v._id && _parameters.SequenceEqual(v._parameters) && _ilGen.Equals(v._ilGen) && _parametersNames.SequenceEqual(v._parametersNames) && InitLocals == v.InitLocals; } public override bool Equals(object obj) { return Equals(obj as IReplay); } public override int GetHashCode() { return _id; } public object TrueContent() { return _trueContent!; } public void ExpectedLength(int length) { _expectedLength = length; } public bool InitLocals { get; set; } public IILGen Generator => _ilGen; } public void DefineMethodOverride(IILMethod methodBuilder, MethodInfo baseMethod) { _instructions.Add(new MethodOverride((int)_instructions.Count, methodBuilder, baseMethod)); } class MethodOverride : IReplay { readonly int _id; readonly IReplay _methodBuilder; readonly MethodInfo _baseMethod; public MethodOverride(int id, IILMethod methodBuilder, MethodInfo baseMethod) { _id = id; _methodBuilder = (IReplay)methodBuilder; _baseMethod = baseMethod; } public void ReplayTo(IILDynamicType target) { } public void FinishReplay(IILDynamicType target) { target.DefineMethodOverride((IILMethod)_methodBuilder.TrueContent(), _baseMethod); } public void FreeTemps() { } public bool Equals(IReplay? other) { if (!(other is MethodOverride v)) return false; return _id == v._id && _methodBuilder.Equals(v._methodBuilder) && _baseMethod == v._baseMethod; } public override bool Equals(object obj) { return Equals(obj as IReplay); } public override int GetHashCode() { return _id; } public object TrueContent() { throw new InvalidOperationException(); } } public Type CreateType() { lock (_cachingIlBuilder.Lock) { var item = (CachingILDynamicType)_cachingIlBuilder.FindInCache(this); if (item.TrueContent == null) { var typeGen = _cachingIlBuilder.Wrapping.NewType(_name, _baseType, _interfaces); foreach (var replay in _instructions) { replay.ReplayTo(typeGen); } foreach (var replay in _instructions) { replay.FinishReplay(typeGen); } foreach (var replay in _instructions) { replay.FreeTemps(); } item.TrueContent = typeGen.CreateType(); } return item.TrueContent; } } public override int GetHashCode() { // ReSharper disable once NonReadonlyMemberInGetHashCode return _name.GetHashCode() * 33 + (int)_instructions.Count; } public override bool Equals(object obj) { if (!(obj is CachingILDynamicType v)) return false; return _name == v._name && _baseType == v._baseType && _interfaces.SequenceEqual(v._interfaces) && _instructions.SequenceEqual(v._instructions, ReplayComparer.Instance); } class ReplayComparer : IEqualityComparer<IReplay> { internal static readonly ReplayComparer Instance = new ReplayComparer(); public bool Equals(IReplay? x, IReplay? y) { if (ReferenceEquals(x, y)) return true; return x != null && x.Equals(y); } public int GetHashCode(IReplay obj) { return 0; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Orleans.Runtime; using Orleans.Serialization; using Orleans.TestingHost.Utils; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using Orleans.Configuration; using Microsoft.Extensions.Options; namespace Orleans.TestingHost { /// <summary> /// A host class for local testing with Orleans using in-process silos. /// Runs a Primary and optionally secondary silos in separate app domains, and client in the main app domain. /// Additional silos can also be started in-process on demand if required for particular test cases. /// </summary> /// <remarks> /// Make sure that your test project references your test grains and test grain interfaces /// projects, and has CopyLocal=True set on those references [which should be the default]. /// </remarks> public class TestCluster : IDisposable { private readonly List<SiloHandle> additionalSilos = new List<SiloHandle>(); private readonly TestClusterOptions options; private readonly StringBuilder log = new StringBuilder(); private int startedInstances; /// <summary> /// Primary silo handle, if applicable. /// </summary> /// <remarks>This handle is valid only when using Grain-based membership.</remarks> public SiloHandle Primary { get; private set; } /// <summary> /// List of handles to the secondary silos. /// </summary> public IReadOnlyList<SiloHandle> SecondarySilos { get { lock (this.additionalSilos) { return new List<SiloHandle>(this.additionalSilos); } } } /// <summary> /// Collection of all known silos. /// </summary> public ReadOnlyCollection<SiloHandle> Silos { get { var result = new List<SiloHandle>(); if (this.Primary != null) { result.Add(this.Primary); } lock (this.additionalSilos) { result.AddRange(this.additionalSilos); } return result.AsReadOnly(); } } /// <summary> /// Options used to configure the test cluster. /// </summary> /// <remarks>This is the options you configured your test cluster with, or the default one. /// If the cluster is being configured via ClusterConfiguration, then this object may not reflect the true settings. /// </remarks> public TestClusterOptions Options => this.options; /// <summary> /// The internal client interface. /// </summary> internal IInternalClusterClient InternalClient { get; private set; } /// <summary> /// The client. /// </summary> public IClusterClient Client => this.InternalClient; /// <summary> /// GrainFactory to use in the tests /// </summary> public IGrainFactory GrainFactory => this.Client; /// <summary> /// GrainFactory to use in the tests /// </summary> internal IInternalGrainFactory InternalGrainFactory => this.InternalClient; /// <summary> /// Client-side <see cref="IServiceProvider"/> to use in the tests. /// </summary> public IServiceProvider ServiceProvider => this.Client.ServiceProvider; /// <summary> /// SerializationManager to use in the tests /// </summary> public SerializationManager SerializationManager { get; private set; } /// <summary> /// Delegate used to create and start an individual silo. /// </summary> public Func<string, IList<IConfigurationSource>, Task<SiloHandle>> CreateSiloAsync { private get; set; } = InProcessSiloHandle.CreateAsync; /// <summary> /// Configures the test cluster plus client in-process. /// </summary> public TestCluster(TestClusterOptions options, IReadOnlyList<IConfigurationSource> configurationSources) { this.options = options; this.ConfigurationSources = configurationSources.ToArray(); } /// <summary> /// Deploys the cluster using the specified configuration and starts the client in-process. /// It will start the number of silos defined in <see cref="TestClusterOptions.InitialSilosCount"/>. /// </summary> public void Deploy() { this.DeployAsync().GetAwaiter().GetResult(); } /// <summary> /// Deploys the cluster using the specified configuration and starts the client in-process. /// </summary> public async Task DeployAsync() { if (this.Primary != null || this.additionalSilos.Count > 0) throw new InvalidOperationException("Cluster host already deployed."); AppDomain.CurrentDomain.UnhandledException += ReportUnobservedException; try { string startMsg = "----------------------------- STARTING NEW UNIT TEST SILO HOST: " + GetType().FullName + " -------------------------------------"; WriteLog(startMsg); await InitializeAsync(); if (this.options.InitializeClientOnDeploy) { await WaitForInitialStabilization(); } } catch (TimeoutException te) { FlushLogToConsole(); throw new TimeoutException("Timeout during test initialization", te); } catch (Exception ex) { await StopAllSilosAsync(); Exception baseExc = ex.GetBaseException(); FlushLogToConsole(); if (baseExc is TimeoutException) { throw new TimeoutException("Timeout during test initialization", ex); } // IMPORTANT: // Do NOT re-throw the original exception here, also not as an internal exception inside AggregateException // Due to the way MS tests works, if the original exception is an Orleans exception, // it's assembly might not be loaded yet in this phase of the test. // As a result, we will get "MSTest: Unit Test Adapter threw exception: Type is not resolved for member XXX" // and will loose the original exception. This makes debugging tests super hard! // The root cause has to do with us initializing our tests from Test constructor and not from TestInitialize method. // More details: http://dobrzanski.net/2010/09/20/mstest-unit-test-adapter-threw-exception-type-is-not-resolved-for-member/ //throw new Exception( // string.Format("Exception during test initialization: {0}", // LogFormatter.PrintException(baseExc))); throw; } } private async Task WaitForInitialStabilization() { // Poll each silo to check that it knows the expected number of active silos. // If any silo does not have the expected number of active silos in its cluster membership oracle, try again. // If the cluster membership has not stabilized after a certain period of time, give up and continue anyway. var totalWait = Stopwatch.StartNew(); while (true) { var silos = this.Silos; var expectedCount = silos.Count; var remainingSilos = expectedCount; foreach (var silo in silos) { var hooks = this.InternalClient.GetTestHooks(silo); var statuses = await hooks.GetApproximateSiloStatuses(); var activeCount = statuses.Count(s => s.Value == SiloStatus.Active); if (activeCount != expectedCount) break; remainingSilos--; } if (remainingSilos == 0) { totalWait.Stop(); break; } WriteLog($"{remainingSilos} silos do not have a consistent cluster view, waiting until stabilization."); await Task.Delay(TimeSpan.FromMilliseconds(100)); if (totalWait.Elapsed < TimeSpan.FromSeconds(60)) { WriteLog($"Warning! {remainingSilos} silos do not have a consistent cluster view after {totalWait.ElapsedMilliseconds}ms, continuing without stabilization."); break; } } } /// <summary> /// Get the list of current active silos. /// </summary> /// <returns>List of current silos.</returns> public IEnumerable<SiloHandle> GetActiveSilos() { var additional = new List<SiloHandle>(); lock (additionalSilos) { additional.AddRange(additionalSilos); } WriteLog("GetActiveSilos: Primary={0} + {1} Additional={2}", Primary, additional.Count, Runtime.Utils.EnumerableToString(additional)); if (Primary?.IsActive == true) yield return Primary; if (additional.Count > 0) foreach (var s in additional) if (s?.IsActive == true) yield return s; } /// <summary> /// Find the silo handle for the specified silo address. /// </summary> /// <param name="siloAddress">Silo address to be found.</param> /// <returns>SiloHandle of the appropriate silo, or <c>null</c> if not found.</returns> public SiloHandle GetSiloForAddress(SiloAddress siloAddress) { var activeSilos = GetActiveSilos().ToList(); var ret = activeSilos.FirstOrDefault(s => s.SiloAddress.Equals(siloAddress)); return ret; } /// <summary> /// Wait for the silo liveness sub-system to detect and act on any recent cluster membership changes. /// </summary> /// <param name="didKill">Whether recent membership changes we done by graceful Stop.</param> public async Task WaitForLivenessToStabilizeAsync(bool didKill = false) { var clusterMembershipOptions = this.ServiceProvider.GetRequiredService<IOptions<ClusterMembershipOptions>>().Value; TimeSpan stabilizationTime = GetLivenessStabilizationTime(clusterMembershipOptions, didKill); WriteLog(Environment.NewLine + Environment.NewLine + "WaitForLivenessToStabilize is about to sleep for {0}", stabilizationTime); await Task.Delay(stabilizationTime); WriteLog("WaitForLivenessToStabilize is done sleeping"); } /// <summary> /// Get the timeout value to use to wait for the silo liveness sub-system to detect and act on any recent cluster membership changes. /// <seealso cref="WaitForLivenessToStabilizeAsync"/> /// </summary> public static TimeSpan GetLivenessStabilizationTime(ClusterMembershipOptions clusterMembershipOptions, bool didKill = false) { TimeSpan stabilizationTime = TimeSpan.Zero; if (didKill) { // in case of hard kill (kill and not Stop), we should give silos time to detect failures first. stabilizationTime = TestingUtils.Multiply(clusterMembershipOptions.ProbeTimeout, clusterMembershipOptions.NumMissedProbesLimit); } if (clusterMembershipOptions.UseLivenessGossip) { stabilizationTime += TimeSpan.FromSeconds(5); } else { stabilizationTime += TestingUtils.Multiply(clusterMembershipOptions.TableRefreshTimeout, 2); } return stabilizationTime; } /// <summary> /// Start an additional silo, so that it joins the existing cluster. /// </summary> /// <returns>SiloHandle for the newly started silo.</returns> public SiloHandle StartAdditionalSilo(bool startAdditionalSiloOnNewPort = false) { return StartAdditionalSiloAsync(startAdditionalSiloOnNewPort).GetAwaiter().GetResult(); } /// <summary> /// Start an additional silo, so that it joins the existing cluster. /// </summary> /// <returns>SiloHandle for the newly started silo.</returns> public async Task<SiloHandle> StartAdditionalSiloAsync(bool startAdditionalSiloOnNewPort = false) { return (await this.StartAdditionalSilosAsync(1, startAdditionalSiloOnNewPort)).Single(); } /// <summary> /// Start a number of additional silo, so that they join the existing cluster. /// </summary> /// <param name="silosToStart">Number of silos to start.</param> /// <param name="startAdditionalSiloOnNewPort"></param> /// <returns>List of SiloHandles for the newly started silos.</returns> public async Task<List<SiloHandle>> StartAdditionalSilosAsync(int silosToStart, bool startAdditionalSiloOnNewPort = false) { var instances = new List<SiloHandle>(); if (silosToStart > 0) { var siloStartTasks = Enumerable.Range(this.startedInstances, silosToStart) .Select(instanceNumber => Task.Run(() => StartSiloAsync((short)instanceNumber, this.options, startSiloOnNewPort: startAdditionalSiloOnNewPort))).ToArray(); try { await Task.WhenAll(siloStartTasks); } catch (Exception) { lock (additionalSilos) { this.additionalSilos.AddRange(siloStartTasks.Where(t => t.Exception == null).Select(t => t.Result)); } throw; } instances.AddRange(siloStartTasks.Select(t => t.Result)); lock (additionalSilos) { this.additionalSilos.AddRange(instances); } } return instances; } /// <summary> /// Stop any additional silos, not including the default Primary silo. /// </summary> public async Task StopSecondarySilosAsync() { foreach (var instance in this.additionalSilos.ToList()) { await StopSiloAsync(instance); } } /// <summary> /// Stops the default Primary silo. /// </summary> public async Task StopPrimarySiloAsync() { if (Primary == null) throw new InvalidOperationException("There is no primary silo"); await StopClusterClientAsync(); await StopSiloAsync(Primary); } private async Task StopClusterClientAsync() { try { if (InternalClient != null) { await this.InternalClient.Close(); } } catch (Exception exc) { WriteLog("Exception Uninitializing grain client: {0}", exc); } finally { this.InternalClient?.Dispose(); this.InternalClient = null; } } /// <summary> /// Stop all current silos. /// </summary> public void StopAllSilos() { StopAllSilosAsync().GetAwaiter().GetResult(); } /// <summary> /// Stop all current silos. /// </summary> public async Task StopAllSilosAsync() { await StopClusterClientAsync(); await StopSecondarySilosAsync(); if (Primary != null) { await StopPrimarySiloAsync(); } AppDomain.CurrentDomain.UnhandledException -= ReportUnobservedException; } /// <summary> /// Do a semi-graceful Stop of the specified silo. /// </summary> /// <param name="instance">Silo to be stopped.</param> public async Task StopSiloAsync(SiloHandle instance) { if (instance != null) { await StopSiloAsync(instance, true); if (Primary == instance) { Primary = null; } else { lock (additionalSilos) { additionalSilos.Remove(instance); } } } } /// <summary> /// Do an immediate Kill of the specified silo. /// </summary> /// <param name="instance">Silo to be killed.</param> public async Task KillSiloAsync(SiloHandle instance) { if (instance != null) { // do NOT stop, just kill directly, to simulate crash. await StopSiloAsync(instance, false); } } /// <summary> /// Performs a hard kill on client. Client will not cleanup resources. /// </summary> public async Task KillClientAsync() { if (InternalClient != null) { await this.InternalClient.AbortAsync(); this.InternalClient = null; } } /// <summary> /// Do a Stop or Kill of the specified silo, followed by a restart. /// </summary> /// <param name="instance">Silo to be restarted.</param> public async Task<SiloHandle> RestartSiloAsync(SiloHandle instance) { if (instance != null) { var instanceNumber = instance.InstanceNumber; var siloName = instance.Name; await StopSiloAsync(instance); var newInstance = await StartSiloAsync(instanceNumber, this.options); if (siloName == Silo.PrimarySiloName) { Primary = newInstance; } else { lock (additionalSilos) { additionalSilos.Add(newInstance); } } return newInstance; } return null; } /// <summary> /// Restart a previously stopped. /// </summary> /// <param name="siloName">Silo to be restarted.</param> public async Task<SiloHandle> RestartStoppedSecondarySiloAsync(string siloName) { if (siloName == null) throw new ArgumentNullException(nameof(siloName)); var siloHandle = this.Silos.Single(s => s.Name.Equals(siloName, StringComparison.Ordinal)); var newInstance = await this.StartSiloAsync(this.Silos.IndexOf(siloHandle), this.options); lock (additionalSilos) { additionalSilos.Add(newInstance); } return newInstance; } /// <summary> /// Initialize the grain client. This should be already done by <see cref="Deploy()"/> or <see cref="DeployAsync"/> /// </summary> public void InitializeClient() { WriteLog("Initializing Cluster Client"); this.InternalClient = (IInternalClusterClient)TestClusterHostFactory.CreateClusterClient("MainClient", this.ConfigurationSources); this.InternalClient.Connect().GetAwaiter().GetResult(); this.SerializationManager = this.ServiceProvider.GetRequiredService<SerializationManager>(); } public IReadOnlyList<IConfigurationSource> ConfigurationSources { get; } private async Task InitializeAsync() { short silosToStart = this.options.InitialSilosCount; if (this.options.UseTestClusterMembership) { this.Primary = await StartSiloAsync(this.startedInstances, this.options); silosToStart--; } if (silosToStart > 0) { await this.StartAdditionalSilosAsync(silosToStart); } WriteLog("Done initializing cluster"); if (this.options.InitializeClientOnDeploy) { InitializeClient(); } } /// <summary> /// Start a new silo in the target cluster /// </summary> /// <param name="cluster">The TestCluster in which the silo should be deployed</param> /// <param name="instanceNumber">The instance number to deploy</param> /// <param name="clusterOptions">The options to use.</param> /// <param name="configurationOverrides">Configuration overrides.</param> /// <param name="startSiloOnNewPort">Whether we start this silo on a new port, instead of the default one</param> /// <returns>A handle to the silo deployed</returns> public static async Task<SiloHandle> StartSiloAsync(TestCluster cluster, int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false) { if (cluster == null) throw new ArgumentNullException(nameof(cluster)); return await cluster.StartSiloAsync(instanceNumber, clusterOptions, configurationOverrides, startSiloOnNewPort); } /// <summary> /// Starts a new silo. /// </summary> /// <param name="instanceNumber">The instance number to deploy</param> /// <param name="clusterOptions">The options to use.</param> /// <param name="configurationOverrides">Configuration overrides.</param> /// <param name="startSiloOnNewPort">Whether we start this silo on a new port, instead of the default one</param> /// <returns>A handle to the deployed silo.</returns> public async Task<SiloHandle> StartSiloAsync(int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false) { var configurationSources = this.ConfigurationSources.ToList(); // Add overrides. if (configurationOverrides != null) configurationSources.AddRange(configurationOverrides); var siloSpecificOptions = TestSiloSpecificOptions.Create(clusterOptions, instanceNumber, startSiloOnNewPort); configurationSources.Add(new MemoryConfigurationSource { InitialData = siloSpecificOptions.ToDictionary() }); var handle = await this.CreateSiloAsync(siloSpecificOptions.SiloName, configurationSources); handle.InstanceNumber = (short)instanceNumber; Interlocked.Increment(ref this.startedInstances); return handle; } private async Task StopSiloAsync(SiloHandle instance, bool stopGracefully) { try { await instance.StopSiloAsync(stopGracefully); instance.Dispose(); } finally { Interlocked.Decrement(ref this.startedInstances); } } public string GetLog() { return this.log.ToString(); } private void ReportUnobservedException(object sender, UnhandledExceptionEventArgs eventArgs) { Exception exception = (Exception)eventArgs.ExceptionObject; this.WriteLog("Unobserved exception: {0}", exception); } private void WriteLog(string format, params object[] args) { log.AppendFormat(format + Environment.NewLine, args); } private void FlushLogToConsole() { Console.WriteLine(GetLog()); } public void Dispose() { foreach (var handle in this.SecondarySilos) { handle.Dispose(); } this.Primary?.Dispose(); this.Client?.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Text.Tests { public static partial class NegativeEncodingTests { public static IEnumerable<object[]> Encodings_TestData() { yield return new object[] { new UnicodeEncoding(false, false) }; yield return new object[] { new UnicodeEncoding(true, false) }; yield return new object[] { new UnicodeEncoding(true, true) }; yield return new object[] { new UnicodeEncoding(true, true) }; yield return new object[] { Encoding.BigEndianUnicode }; yield return new object[] { Encoding.Unicode }; yield return new object[] { new UTF7Encoding(true) }; yield return new object[] { new UTF7Encoding(false) }; yield return new object[] { Encoding.UTF7 }; yield return new object[] { new UTF8Encoding(true, true) }; yield return new object[] { new UTF8Encoding(false, true) }; yield return new object[] { new UTF8Encoding(true, false) }; yield return new object[] { new UTF8Encoding(false, false) }; yield return new object[] { Encoding.UTF8 }; yield return new object[] { new ASCIIEncoding() }; yield return new object[] { Encoding.ASCII }; yield return new object[] { new UTF32Encoding(true, true, true) }; yield return new object[] { new UTF32Encoding(true, true, false) }; yield return new object[] { new UTF32Encoding(true, false, false) }; yield return new object[] { new UTF32Encoding(true, false, true) }; yield return new object[] { new UTF32Encoding(false, true, true) }; yield return new object[] { new UTF32Encoding(false, true, false) }; yield return new object[] { new UTF32Encoding(false, false, false) }; yield return new object[] { new UTF32Encoding(false, false, true) }; yield return new object[] { Encoding.UTF32 }; yield return new object[] { Encoding.GetEncoding("latin1") }; } [Theory] [MemberData(nameof(Encodings_TestData))] public static unsafe void GetByteCount_Invalid(Encoding encoding) { // Chars is null if (PlatformDetection.IsNetCore) { AssertExtensions.Throws<ArgumentNullException>((encoding is ASCIIEncoding || encoding is UTF8Encoding) ? "chars" : "s", () => encoding.GetByteCount((string)null)); } else { AssertExtensions.Throws<ArgumentNullException>((encoding is ASCIIEncoding) ? "chars" : "s", () => encoding.GetByteCount((string)null)); } AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount((char[])null)); AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount((char[])null, 0, 0)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetByteCount(new char[3], -1, 0)); // Count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetByteCount(new char[3], 0, -1)); // Index + count > chars.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 0, 4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 1, 3)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 2, 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 3, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 4, 0)); char[] chars = new char[3]; fixed (char* pChars = chars) { char* pCharsLocal = pChars; AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetByteCount(pCharsLocal, -1)); } } [Theory] [MemberData(nameof(Encodings_TestData))] public static unsafe void GetBytes_Invalid(Encoding encoding) { string expectedStringParamName = encoding is ASCIIEncoding ? "chars" : "s"; // Source is null AssertExtensions.Throws<ArgumentNullException>("s", () => encoding.GetBytes((string)null)); AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null)); AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null, 0, 0)); AssertExtensions.Throws<ArgumentNullException>(expectedStringParamName, () => encoding.GetBytes((string)null, 0, 0, new byte[1], 0)); AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null, 0, 0, new byte[1], 0)); // Bytes is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes("abc", 0, 3, null, 0)); AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes(new char[3], 0, 3, null, 0)); // Char index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetBytes(new char[1], -1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetBytes("a", -1, 0, new byte[1], 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetBytes(new char[1], -1, 0, new byte[1], 0)); // Char count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetBytes(new char[1], 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes("a", 0, -1, new byte[1], 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes(new char[1], 0, -1, new byte[1], 0)); // Char index + count > source.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 2, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 2, 0, new byte[1], 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 2, 0, new byte[1], 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 1, 1, new byte[1], 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 1, 1, new byte[1], 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 0, 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 0, 2, new byte[1], 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 0, 2, new byte[1], 0)); // Byte index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes("a", 0, 1, new byte[1], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes(new char[1], 0, 1, new byte[1], -1)); // Byte index > bytes.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes("a", 0, 1, new byte[1], 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes(new char[1], 0, 1, new byte[1], 2)); // Bytes does not have enough capacity to accomodate result AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("a", 0, 1, new byte[0], 0)); AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("abc", 0, 3, new byte[1], 0)); AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("\uD800\uDC00", 0, 2, new byte[1], 0)); AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(new char[1], 0, 1, new byte[0], 0)); AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(new char[3], 0, 3, new byte[1], 0)); AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("\uD800\uDC00".ToCharArray(), 0, 2, new byte[1], 0)); char[] chars = new char[3]; byte[] bytes = new byte[3]; byte[] smallBytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = bytes) fixed (byte* pSmallBytes = smallBytes) { char* pCharsLocal = pChars; byte* pBytesLocal = pBytes; byte* pSmallBytesLocal = pSmallBytes; // Bytes or chars is null AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char*)null, 0, pBytesLocal, bytes.Length)); AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes(pCharsLocal, chars.Length, (byte*)null, bytes.Length)); // CharCount or byteCount is negative AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes(pCharsLocal, -1, pBytesLocal, bytes.Length)); AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetBytes(pCharsLocal, chars.Length, pBytesLocal, -1)); // Bytes does not have enough capacity to accomodate result AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(pCharsLocal, chars.Length, pSmallBytesLocal, smallBytes.Length)); } } [Theory] [MemberData(nameof(Encodings_TestData))] public static unsafe void GetCharCount_Invalid(Encoding encoding) { // Bytes is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null)); AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null, 0, 0)); // Index or count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetCharCount(new byte[4], -1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetCharCount(new byte[4], 0, -1)); // Index + count > bytes.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 5, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 4, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 3, 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 2, 3)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 1, 4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 0, 5)); byte[] bytes = new byte[4]; fixed (byte* pBytes = bytes) { byte* pBytesLocal = pBytes; AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetCharCount(pBytesLocal, -1)); } } [Theory] [MemberData(nameof(Encodings_TestData))] public static unsafe void GetChars_Invalid(Encoding encoding) { // Bytes is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null)); AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null, 0, 0)); AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null, 0, 0, new char[0], 0)); // Chars is null AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetChars(new byte[4], 0, 4, null, 0)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetChars(new byte[4], -1, 4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetChars(new byte[4], -1, 4, new char[1], 0)); // Count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetChars(new byte[4], 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetChars(new byte[4], 0, -1, new char[1], 0)); // Count > bytes.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 0, 5)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 0, 5, new char[1], 0)); // Index + count > bytes.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 5, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 5, 0, new char[1], 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 4, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 4, 1, new char[1], 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 3, 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 3, 2, new char[1], 0)); // CharIndex < 0 or >= chars.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetChars(new byte[4], 0, 4, new char[1], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetChars(new byte[4], 0, 4, new char[1], 2)); // Chars does not have enough capacity to accomodate result AssertExtensions.Throws<ArgumentException>("chars", () => encoding.GetChars(new byte[4], 0, 4, new char[1], 1)); byte[] bytes = new byte[encoding.GetMaxByteCount(2)]; char[] chars = new char[4]; char[] smallChars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = chars) fixed (char* pSmallChars = smallChars) { byte* pBytesLocal = pBytes; char* pCharsLocal = pChars; char* pSmallCharsLocal = pSmallChars; // Bytes or chars is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars((byte*)null, 0, pCharsLocal, chars.Length)); AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetChars(pBytesLocal, bytes.Length, (char*)null, chars.Length)); // ByteCount or charCount is negative AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetChars(pBytesLocal, -1, pCharsLocal, chars.Length)); AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetChars(pBytesLocal, bytes.Length, pCharsLocal, -1)); // Chars does not have enough capacity to accomodate result AssertExtensions.Throws<ArgumentException>("chars", () => encoding.GetChars(pBytesLocal, bytes.Length, pSmallCharsLocal, smallChars.Length)); } } [Theory] [MemberData(nameof(Encodings_TestData))] public static void GetMaxByteCount_Invalid(Encoding encoding) { AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(-1)); if (!encoding.IsSingleByte) { AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(int.MaxValue / 2)); } AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(int.MaxValue)); // Make sure that GetMaxByteCount respects the MaxCharCount property of EncoderFallback // However, Utf7Encoding ignores this if (!(encoding is UTF7Encoding)) { Encoding customizedMaxCharCountEncoding = Encoding.GetEncoding(encoding.CodePage, new HighMaxCharCountEncoderFallback(), DecoderFallback.ReplacementFallback); AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => customizedMaxCharCountEncoding.GetMaxByteCount(2)); } } [Theory] [MemberData(nameof(Encodings_TestData))] public static void GetMaxCharCount_Invalid(Encoding encoding) { AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetMaxCharCount(-1)); // TODO: find a more generic way to find what byteCount is invalid if (encoding is UTF8Encoding) { AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetMaxCharCount(int.MaxValue)); } // Make sure that GetMaxCharCount respects the MaxCharCount property of DecoderFallback // However, Utf7Encoding ignores this if (!(encoding is UTF7Encoding) && !(encoding is UTF32Encoding)) { Encoding customizedMaxCharCountEncoding = Encoding.GetEncoding(encoding.CodePage, EncoderFallback.ReplacementFallback, new HighMaxCharCountDecoderFallback()); AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => customizedMaxCharCountEncoding.GetMaxCharCount(2)); } } [Theory] [MemberData(nameof(Encodings_TestData))] public static void GetString_Invalid(Encoding encoding) { // Bytes is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetString(null)); AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetString(null, 0, 0)); // Index or count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(encoding is ASCIIEncoding ? "byteIndex" : "index", () => encoding.GetString(new byte[1], -1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>(encoding is ASCIIEncoding ? "byteCount" : "count", () => encoding.GetString(new byte[1], 0, -1)); // Index + count > bytes.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 2, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 0, 2)); } internal static unsafe void Encode_Invalid(Encoding encoding, string chars, int index, int count) { Assert.Equal(EncoderFallback.ExceptionFallback, encoding.EncoderFallback); char[] charsArray = chars.ToCharArray(); byte[] bytes = new byte[encoding.GetMaxByteCount(count)]; if (index == 0 && count == chars.Length) { Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(chars)); Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(charsArray)); Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(chars)); Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray)); } Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(charsArray, index, count)); Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray, index, count)); Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(chars, index, count, bytes, 0)); Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray, index, count, bytes, 0)); fixed (char* pChars = chars) fixed (byte* pBytes = bytes) { char* pCharsLocal = pChars; byte* pBytesLocal = pBytes; Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(pCharsLocal + index, count)); Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(pCharsLocal + index, count, pBytesLocal, bytes.Length)); } } internal static unsafe void Decode_Invalid(Encoding encoding, byte[] bytes, int index, int count) { Assert.Equal(DecoderFallback.ExceptionFallback, encoding.DecoderFallback); char[] chars = new char[encoding.GetMaxCharCount(count)]; if (index == 0 && count == bytes.Length) { Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(bytes)); Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes)); Assert.Throws<DecoderFallbackException>(() => encoding.GetString(bytes)); } Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(bytes, index, count)); Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes, index, count)); Assert.Throws<DecoderFallbackException>(() => encoding.GetString(bytes, index, count)); Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes, index, count, chars, 0)); fixed (byte* pBytes = bytes) fixed (char* pChars = chars) { byte* pBytesLocal = pBytes; char* pCharsLocal = pChars; Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(pBytesLocal + index, count)); Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(pBytesLocal + index, count, pCharsLocal, chars.Length)); Assert.Throws<DecoderFallbackException>(() => encoding.GetString(pBytesLocal + index, count)); } } public static IEnumerable<object[]> Encoders_TestData() { foreach (object[] encodingTestData in Encodings_TestData()) { Encoding encoding = (Encoding)encodingTestData[0]; yield return new object[] { encoding.GetEncoder(), true }; yield return new object[] { encoding.GetEncoder(), false }; } } [Theory] [MemberData(nameof(Encoders_TestData))] public static void Encoder_GetByteCount_Invalid(Encoder encoder, bool flush) { // Chars is null AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.GetByteCount(null, 0, 0, flush)); // Index is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoder.GetByteCount(new char[4], -1, 0, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 5, 0, flush)); // Count is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoder.GetByteCount(new char[4], 0, -1, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 0, 5, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 1, 4, flush)); } [Theory] [MemberData(nameof(Encoders_TestData))] public static void Encoder_GetBytes_Invalid(Encoder encoder, bool flush) { // Chars is null AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.GetBytes(null, 0, 0, new byte[4], 0, flush)); // CharIndex is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoder.GetBytes(new char[4], -1, 0, new byte[4], 0, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 5, 0, new byte[4], 0, flush)); // CharCount is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoder.GetBytes(new char[4], 0, -1, new byte[4], 0, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 0, 5, new byte[4], 0, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 1, 4, new byte[4], 0, flush)); // Bytes is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoder.GetBytes(new char[1], 0, 1, null, 0, flush)); // ByteIndex is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.GetBytes(new char[1], 0, 1, new byte[4], -1, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.GetBytes(new char[1], 0, 1, new byte[4], 5, flush)); // Bytes does not have enough space int byteCount = encoder.GetByteCount(new char[] { 'a' }, 0, 1, flush); AssertExtensions.Throws<ArgumentException>("bytes", () => encoder.GetBytes(new char[] { 'a' }, 0, 1, new byte[byteCount - 1], 0, flush)); } [Theory] [MemberData(nameof(Encoders_TestData))] public static void Encoder_Convert_Invalid(Encoder encoder, bool flush) { int charsUsed = 0; int bytesUsed = 0; bool completed = false; Action verifyOutParams = () => { Assert.Equal(0, charsUsed); Assert.Equal(0, bytesUsed); Assert.False(completed); }; // Chars is null AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.Convert(null, 0, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // CharIndex is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoder.Convert(new char[4], -1, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 5, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // CharCount is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoder.Convert(new char[4], 0, -1, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 0, 5, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 1, 4, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // Bytes is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoder.Convert(new char[1], 0, 1, null, 0, 0, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // ByteIndex is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.Convert(new char[1], 0, 0, new byte[4], -1, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 5, 0, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // ByteCount is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, -1, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, 5, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 1, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // Bytes does not have enough space int byteCount = encoder.GetByteCount(new char[] { 'a' }, 0, 1, flush); AssertExtensions.Throws<ArgumentException>("bytes", () => encoder.Convert(new char[] { 'a' }, 0, 1, new byte[byteCount - 1], 0, byteCount - 1, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); } public static IEnumerable<object[]> Decoders_TestData() { foreach (object[] encodingTestData in Encodings_TestData()) { Encoding encoding = (Encoding)encodingTestData[0]; yield return new object[] { encoding, encoding.GetDecoder(), true }; yield return new object[] { encoding, encoding.GetDecoder(), false }; } } [Theory] [MemberData(nameof(Decoders_TestData))] public static void Decoder_GetCharCount_Invalid(Encoding _, Decoder decoder, bool flush) { // Bytes is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetCharCount(null, 0, 0, flush)); // Index is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => decoder.GetCharCount(new byte[4], -1, 0, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 5, 0, flush)); // Count is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => decoder.GetCharCount(new byte[4], 0, -1, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 0, 5, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 1, 4, flush)); } [Theory] [MemberData(nameof(Decoders_TestData))] public static void Decoder_GetChars_Invalid(Encoding _, Decoder decoder, bool flush) { // Bytes is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetChars(null, 0, 0, new char[4], 0, flush)); // ByteIndex is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => decoder.GetChars(new byte[4], -1, 0, new char[4], 0, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte[4], 5, 0, new char[4], 0, flush)); // ByteCount is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.GetChars(new byte[4], 0, -1, new char[4], 0, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte[4], 0, 5, new char[4], 0, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte [4], 1, 4, new char[4], 0, flush)); // Chars is null AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.GetChars(new byte[1], 0, 1, null, 0, flush)); // CharIndex is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.GetChars(new byte[1], 0, 1, new char[4], -1, flush)); AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.GetChars(new byte[1], 0, 1, new char[4], 5, flush)); // Chars does not have enough space int charCount = decoder.GetCharCount(new byte[4], 0, 4, flush); AssertExtensions.Throws<ArgumentException>("chars", () => decoder.GetChars(new byte[4], 0, 4, new char[charCount - 1], 0, flush)); } [Theory] [MemberData(nameof(Decoders_TestData))] public static void Decoder_Convert_Invalid(Encoding encoding, Decoder decoder, bool flush) { int bytesUsed = 0; int charsUsed = 0; bool completed = false; Action verifyOutParams = () => { Assert.Equal(0, bytesUsed); Assert.Equal(0, charsUsed); Assert.False(completed); }; // Bytes is null AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.Convert(null, 0, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // ByteIndex is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => decoder.Convert(new byte[4], -1, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 5, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // ByteCount is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.Convert(new byte[4], 0, -1, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 0, 5, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 1, 4, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // Chars is null AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.Convert(new byte[1], 0, 1, null, 0, 0, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // CharIndex is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.Convert(new byte[1], 0, 0, new char[4], -1, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 5, 0, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // CharCount is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => decoder.Convert(new byte[1], 0, 0, new char[4], 0, -1, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 0, 5, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 1, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // Chars does not have enough space AssertExtensions.Throws<ArgumentException>("chars", () => decoder.Convert(new byte[4], 0, 4, new char[0], 0, 0, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); } } public class HighMaxCharCountEncoderFallback : EncoderFallback { public override int MaxCharCount => int.MaxValue; public override EncoderFallbackBuffer CreateFallbackBuffer() => ReplacementFallback.CreateFallbackBuffer(); } public class HighMaxCharCountDecoderFallback : DecoderFallback { public override int MaxCharCount => int.MaxValue; public override DecoderFallbackBuffer CreateFallbackBuffer() => ReplacementFallback.CreateFallbackBuffer(); } }
using System; using System.Collections; using System.Collections.Generic; using Server; using Server.Items; using Server.Gumps; using Server.Network; using Server.ContextMenus; namespace Server.Mobiles { [CorpseName( "Un corps de serviteur de la horde" )] public class HordeMinionFamiliar : BaseFamiliar { public override bool DisplayWeight{ get { return true; } } public HordeMinionFamiliar() { Name = "Un serviteur de la horde"; Body = 776; BaseSoundID = 0x39D; SetStr( 100 ); SetDex( 110 ); SetInt( 100 ); SetHits( 70 ); SetStam( 110 ); SetMana( 0 ); SetDamage( 5, 10 ); SetDamageType( ResistanceType.Physical, 100 ); SetResistance( ResistanceType.Physical, 50, 60 ); SetResistance( ResistanceType.Fire, 50, 55 ); SetResistance( ResistanceType.Poison, 25, 30 ); SetResistance( ResistanceType.Energy, 25, 30 ); SetSkill( SkillName.Wrestling, 70.1, 75.0 ); SetSkill( SkillName.Tactics, 50.0 ); ControlSlots = 1; Container pack = Backpack; if ( pack != null ) pack.Delete(); pack = new Backpack(); pack.Movable = false; pack.Weight = 13.0; AddItem( pack ); } private DateTime m_NextPickup; public override void OnThink() { base.OnThink(); if ( DateTime.Now < m_NextPickup ) return; m_NextPickup = DateTime.Now + TimeSpan.FromSeconds( Utility.RandomMinMax( 5, 10 ) ); Container pack = this.Backpack; if ( pack == null ) return; ArrayList list = new ArrayList(); foreach ( Item item in this.GetItemsInRange( 2 ) ) { if ( item.Movable && item.Stackable ) list.Add( item ); } int pickedUp = 0; for ( int i = 0; i < list.Count; ++i ) { Item item = (Item)list[i]; if ( !pack.CheckHold( this, item, false, true ) ) return; bool rejected; LRReason reject; NextActionTime = DateTime.Now; Lift( item, item.Amount, out rejected, out reject ); if ( rejected ) continue; Drop( this, Point3D.Zero ); if ( ++pickedUp == 3 ) break; } } private void ConfirmRelease_Callback( Mobile from, bool okay, object state ) { if ( okay ) EndRelease( from ); } public override void BeginRelease( Mobile from ) { Container pack = this.Backpack; if ( pack != null && pack.Items.Count > 0 ) from.SendGump( new WarningGump( 1060635, 30720, 1061672, 32512, 420, 280, new WarningGumpCallback( ConfirmRelease_Callback ), null ) ); else EndRelease( from ); } #region Pack Animal Methods public override bool OnBeforeDeath() { if ( !base.OnBeforeDeath() ) return false; PackAnimal.CombineBackpacks( this ); return true; } public override DeathMoveResult GetInventoryMoveResultFor( Item item ) { return DeathMoveResult.MoveToCorpse; } public override bool IsSnoop( Mobile from ) { if ( PackAnimal.CheckAccess( this, from ) ) return false; return base.IsSnoop( from ); } public override bool OnDragDrop( Mobile from, Item item ) { if ( CheckFeed( from, item ) ) return true; if ( PackAnimal.CheckAccess( this, from ) ) { AddToBackpack( item ); return true; } return base.OnDragDrop( from, item ); } public override bool CheckNonlocalDrop( Mobile from, Item item, Item target ) { return PackAnimal.CheckAccess( this, from ); } public override bool CheckNonlocalLift( Mobile from, Item item ) { return PackAnimal.CheckAccess( this, from ); } public override void OnDoubleClick( Mobile from ) { PackAnimal.TryPackOpen( this, from ); } public override void GetContextMenuEntries( Mobile from, List<ContextMenuEntry> list ) { base.GetContextMenuEntries( from, list ); PackAnimal.GetContextMenuEntries( this, from, list ); } #endregion public HordeMinionFamiliar( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
using System.Collections.Generic; using Assets.PostProcessing.Runtime.Models; using Assets.PostProcessing.Runtime.Utils; using UnityEngine; using UnityEngine.Rendering; namespace Assets.PostProcessing.Runtime.Components { using Mode = BuiltinDebugViewsModel.Mode; public sealed class BuiltinDebugViewsComponent : PostProcessingComponentCommandBuffer<BuiltinDebugViewsModel> { static class Uniforms { internal static readonly int _DepthScale = Shader.PropertyToID("_DepthScale"); internal static readonly int _TempRT = Shader.PropertyToID("_TempRT"); internal static readonly int _Opacity = Shader.PropertyToID("_Opacity"); internal static readonly int _MainTex = Shader.PropertyToID("_MainTex"); internal static readonly int _TempRT2 = Shader.PropertyToID("_TempRT2"); internal static readonly int _Amplitude = Shader.PropertyToID("_Amplitude"); internal static readonly int _Scale = Shader.PropertyToID("_Scale"); } const string k_ShaderString = "Hidden/Post FX/Builtin Debug Views"; enum Pass { Depth, Normals, MovecOpacity, MovecImaging, MovecArrows } ArrowArray m_Arrows; class ArrowArray { public Mesh mesh { get; private set; } public int columnCount { get; private set; } public int rowCount { get; private set; } public void BuildMesh(int columns, int rows) { // Base shape var arrow = new Vector3[6] { new Vector3(0f, 0f, 0f), new Vector3(0f, 1f, 0f), new Vector3(0f, 1f, 0f), new Vector3(-1f, 1f, 0f), new Vector3(0f, 1f, 0f), new Vector3(1f, 1f, 0f) }; // make the vertex array int vcount = 6 * columns * rows; var vertices = new List<Vector3>(vcount); var uvs = new List<Vector2>(vcount); for (int iy = 0; iy < rows; iy++) { for (int ix = 0; ix < columns; ix++) { var uv = new Vector2( (0.5f + ix) / columns, (0.5f + iy) / rows ); for (int i = 0; i < 6; i++) { vertices.Add(arrow[i]); uvs.Add(uv); } } } // make the index array var indices = new int[vcount]; for (int i = 0; i < vcount; i++) indices[i] = i; // initialize the mesh object mesh = new Mesh { hideFlags = HideFlags.DontSave }; mesh.SetVertices(vertices); mesh.SetUVs(0, uvs); mesh.SetIndices(indices, MeshTopology.Lines, 0); mesh.UploadMeshData(true); // update the properties columnCount = columns; rowCount = rows; } public void Release() { GraphicsUtils.Destroy(mesh); mesh = null; } } public override bool active { get { return model.IsModeActive(Mode.Depth) || model.IsModeActive(Mode.Normals) || model.IsModeActive(Mode.MotionVectors); } } public override DepthTextureMode GetCameraFlags() { var mode = model.settings.mode; var flags = DepthTextureMode.None; switch (mode) { case Mode.Normals: flags |= DepthTextureMode.DepthNormals; break; case Mode.MotionVectors: flags |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth; break; case Mode.Depth: flags |= DepthTextureMode.Depth; break; } return flags; } public override CameraEvent GetCameraEvent() { return model.settings.mode == Mode.MotionVectors ? CameraEvent.BeforeImageEffects : CameraEvent.BeforeImageEffectsOpaque; } public override string GetName() { return "Builtin Debug Views"; } public override void PopulateCommandBuffer(CommandBuffer cb) { var settings = model.settings; var material = context.materialFactory.Get(k_ShaderString); material.shaderKeywords = null; if (context.isGBufferAvailable) material.EnableKeyword("SOURCE_GBUFFER"); switch (settings.mode) { case Mode.Depth: DepthPass(cb); break; case Mode.Normals: DepthNormalsPass(cb); break; case Mode.MotionVectors: MotionVectorsPass(cb); break; } context.Interrupt(); } void DepthPass(CommandBuffer cb) { var material = context.materialFactory.Get(k_ShaderString); var settings = model.settings.depth; cb.SetGlobalFloat(Uniforms._DepthScale, 1f / settings.scale); cb.Blit((Texture)null, BuiltinRenderTextureType.CameraTarget, material, (int)Pass.Depth); } void DepthNormalsPass(CommandBuffer cb) { var material = context.materialFactory.Get(k_ShaderString); cb.Blit((Texture)null, BuiltinRenderTextureType.CameraTarget, material, (int)Pass.Normals); } void MotionVectorsPass(CommandBuffer cb) { #if UNITY_EDITOR // Don't render motion vectors preview when the editor is not playing as it can in some // cases results in ugly artifacts (i.e. when resizing the game view). if (!Application.isPlaying) return; #endif var material = context.materialFactory.Get(k_ShaderString); var settings = model.settings.motionVectors; // Blit the original source image int tempRT = Uniforms._TempRT; cb.GetTemporaryRT(tempRT, context.width, context.height, 0, FilterMode.Bilinear); cb.SetGlobalFloat(Uniforms._Opacity, settings.sourceOpacity); cb.SetGlobalTexture(Uniforms._MainTex, BuiltinRenderTextureType.CameraTarget); cb.Blit(BuiltinRenderTextureType.CameraTarget, tempRT, material, (int)Pass.MovecOpacity); // Motion vectors (imaging) if (settings.motionImageOpacity > 0f && settings.motionImageAmplitude > 0f) { int tempRT2 = Uniforms._TempRT2; cb.GetTemporaryRT(tempRT2, context.width, context.height, 0, FilterMode.Bilinear); cb.SetGlobalFloat(Uniforms._Opacity, settings.motionImageOpacity); cb.SetGlobalFloat(Uniforms._Amplitude, settings.motionImageAmplitude); cb.SetGlobalTexture(Uniforms._MainTex, tempRT); cb.Blit(tempRT, tempRT2, material, (int)Pass.MovecImaging); cb.ReleaseTemporaryRT(tempRT); tempRT = tempRT2; } // Motion vectors (arrows) if (settings.motionVectorsOpacity > 0f && settings.motionVectorsAmplitude > 0f) { PrepareArrows(); float sy = 1f / settings.motionVectorsResolution; float sx = sy * context.height / context.width; cb.SetGlobalVector(Uniforms._Scale, new Vector2(sx, sy)); cb.SetGlobalFloat(Uniforms._Opacity, settings.motionVectorsOpacity); cb.SetGlobalFloat(Uniforms._Amplitude, settings.motionVectorsAmplitude); cb.DrawMesh(m_Arrows.mesh, Matrix4x4.identity, material, 0, (int)Pass.MovecArrows); } cb.SetGlobalTexture(Uniforms._MainTex, tempRT); cb.Blit(tempRT, BuiltinRenderTextureType.CameraTarget); cb.ReleaseTemporaryRT(tempRT); } void PrepareArrows() { int row = model.settings.motionVectors.motionVectorsResolution; int col = row * Screen.width / Screen.height; if (m_Arrows == null) m_Arrows = new ArrowArray(); if (m_Arrows.columnCount != col || m_Arrows.rowCount != row) { m_Arrows.Release(); m_Arrows.BuildMesh(col, row); } } public override void OnDisable() { if (m_Arrows != null) m_Arrows.Release(); m_Arrows = null; } } }
// Copyright 2016 Mark Raasveldt // // 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.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Tibialyzer { class OutfiterForm : NotificationForm { private PictureBox outfiterImageBox; private PrettyButton rotateRightButton; private PrettyButton rotateLeftButton; private PrettyButton secondaryColorButton; private PrettyButton detailColorButton; private PrettyButton primaryColorButton; private PrettyButton headColorButton; private PrettyButton rotateLabel; private PrettyButton outfitLabel; private PrettyButton outfitRightButton; private PrettyButton outfitLeftButton; private PrettyButton mountLabel; private PrettyButton mountRightButton; private PrettyButton mountLeftButton; private PrettyButton copyTextButton; private PrettyButton addon1Toggle; private PrettyButton addon2Toggle; private PrettyButton genderToggle; public OutfiterOutfit outfit; public OutfiterForm(OutfiterOutfit outfit) { this.outfit = outfit; this.InitializeComponent(); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OutfiterForm)); this.outfiterImageBox = new System.Windows.Forms.PictureBox(); this.rotateRightButton = new Tibialyzer.PrettyButton(); this.rotateLeftButton = new Tibialyzer.PrettyButton(); this.secondaryColorButton = new Tibialyzer.PrettyButton(); this.detailColorButton = new Tibialyzer.PrettyButton(); this.primaryColorButton = new Tibialyzer.PrettyButton(); this.headColorButton = new Tibialyzer.PrettyButton(); this.rotateLabel = new Tibialyzer.PrettyButton(); this.outfitLabel = new Tibialyzer.PrettyButton(); this.outfitRightButton = new Tibialyzer.PrettyButton(); this.outfitLeftButton = new Tibialyzer.PrettyButton(); this.mountLabel = new Tibialyzer.PrettyButton(); this.mountRightButton = new Tibialyzer.PrettyButton(); this.mountLeftButton = new Tibialyzer.PrettyButton(); this.copyTextButton = new Tibialyzer.PrettyButton(); this.addon1Toggle = new Tibialyzer.PrettyButton(); this.addon2Toggle = new Tibialyzer.PrettyButton(); this.genderToggle = new Tibialyzer.PrettyButton(); ((System.ComponentModel.ISupportInitialize)(this.outfiterImageBox)).BeginInit(); this.SuspendLayout(); // // outfiterImageBox // this.outfiterImageBox.BackColor = System.Drawing.Color.Transparent; this.outfiterImageBox.Location = new System.Drawing.Point(125, 142); this.outfiterImageBox.Name = "outfiterImageBox"; this.outfiterImageBox.Size = new System.Drawing.Size(128, 128); this.outfiterImageBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.outfiterImageBox.TabIndex = 4; this.outfiterImageBox.TabStop = false; // // rotateRightButton // this.rotateRightButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.rotateRightButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rotateRightButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.rotateRightButton.Image = global::Tibialyzer.Properties.Resources.rightarrow; this.rotateRightButton.Location = new System.Drawing.Point(362, 142); this.rotateRightButton.Name = "rotateRightButton"; this.rotateRightButton.Padding = new System.Windows.Forms.Padding(3); this.rotateRightButton.Size = new System.Drawing.Size(24, 24); this.rotateRightButton.TabIndex = 91; this.rotateRightButton.Click += new System.EventHandler(this.rotateRightButton_Click); // // rotateLeftButton // this.rotateLeftButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.rotateLeftButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rotateLeftButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.rotateLeftButton.Image = global::Tibialyzer.Properties.Resources.leftarrow; this.rotateLeftButton.Location = new System.Drawing.Point(258, 142); this.rotateLeftButton.Name = "rotateLeftButton"; this.rotateLeftButton.Padding = new System.Windows.Forms.Padding(3); this.rotateLeftButton.Size = new System.Drawing.Size(24, 24); this.rotateLeftButton.TabIndex = 90; this.rotateLeftButton.Click += new System.EventHandler(this.rotateLeftButton_Click); // // secondaryColorButton // this.secondaryColorButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.secondaryColorButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.secondaryColorButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.secondaryColorButton.Location = new System.Drawing.Point(12, 192); this.secondaryColorButton.Name = "secondaryColorButton"; this.secondaryColorButton.Padding = new System.Windows.Forms.Padding(3); this.secondaryColorButton.Size = new System.Drawing.Size(107, 25); this.secondaryColorButton.TabIndex = 89; this.secondaryColorButton.Text = "Secondary"; this.secondaryColorButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.secondaryColorButton.Click += new System.EventHandler(this.secondaryColorButton_Click); // // detailColorButton // this.detailColorButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.detailColorButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.detailColorButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.detailColorButton.Location = new System.Drawing.Point(12, 217); this.detailColorButton.Name = "detailColorButton"; this.detailColorButton.Padding = new System.Windows.Forms.Padding(3); this.detailColorButton.Size = new System.Drawing.Size(107, 25); this.detailColorButton.TabIndex = 88; this.detailColorButton.Text = "Detail"; this.detailColorButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.detailColorButton.Click += new System.EventHandler(this.detailColorButton_Click); // // primaryColorButton // this.primaryColorButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.primaryColorButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.primaryColorButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.primaryColorButton.Location = new System.Drawing.Point(12, 167); this.primaryColorButton.Name = "primaryColorButton"; this.primaryColorButton.Padding = new System.Windows.Forms.Padding(3); this.primaryColorButton.Size = new System.Drawing.Size(107, 25); this.primaryColorButton.TabIndex = 87; this.primaryColorButton.Text = "Primary"; this.primaryColorButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.primaryColorButton.Click += new System.EventHandler(this.primaryColorButton_Click); // // headColorButton // this.headColorButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.headColorButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.headColorButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.headColorButton.Location = new System.Drawing.Point(12, 142); this.headColorButton.Name = "headColorButton"; this.headColorButton.Padding = new System.Windows.Forms.Padding(3); this.headColorButton.Size = new System.Drawing.Size(107, 25); this.headColorButton.TabIndex = 86; this.headColorButton.Text = "Head"; this.headColorButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.headColorButton.Click += new System.EventHandler(this.headColorButton_Click); // // rotateLabel // this.rotateLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.rotateLabel.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rotateLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.rotateLabel.Location = new System.Drawing.Point(279, 142); this.rotateLabel.Name = "rotateLabel"; this.rotateLabel.Padding = new System.Windows.Forms.Padding(3); this.rotateLabel.Size = new System.Drawing.Size(83, 24); this.rotateLabel.TabIndex = 92; this.rotateLabel.Text = "Rotate"; this.rotateLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // outfitLabel // this.outfitLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.outfitLabel.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.outfitLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.outfitLabel.Location = new System.Drawing.Point(279, 167); this.outfitLabel.Name = "outfitLabel"; this.outfitLabel.Padding = new System.Windows.Forms.Padding(3); this.outfitLabel.Size = new System.Drawing.Size(83, 24); this.outfitLabel.TabIndex = 95; this.outfitLabel.Text = "Outfit"; this.outfitLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // outfitRightButton // this.outfitRightButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.outfitRightButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.outfitRightButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.outfitRightButton.Image = global::Tibialyzer.Properties.Resources.rightarrow; this.outfitRightButton.Location = new System.Drawing.Point(362, 167); this.outfitRightButton.Name = "outfitRightButton"; this.outfitRightButton.Padding = new System.Windows.Forms.Padding(3); this.outfitRightButton.Size = new System.Drawing.Size(24, 24); this.outfitRightButton.TabIndex = 94; this.outfitRightButton.Click += new System.EventHandler(this.outfitRightButton_Click); // // outfitLeftButton // this.outfitLeftButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.outfitLeftButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.outfitLeftButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.outfitLeftButton.Image = global::Tibialyzer.Properties.Resources.leftarrow; this.outfitLeftButton.Location = new System.Drawing.Point(258, 167); this.outfitLeftButton.Name = "outfitLeftButton"; this.outfitLeftButton.Padding = new System.Windows.Forms.Padding(3); this.outfitLeftButton.Size = new System.Drawing.Size(24, 24); this.outfitLeftButton.TabIndex = 93; this.outfitLeftButton.Click += new System.EventHandler(this.outfitLeftButton_Click); // // mountLabel // this.mountLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.mountLabel.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.mountLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.mountLabel.Location = new System.Drawing.Point(279, 192); this.mountLabel.Name = "mountLabel"; this.mountLabel.Padding = new System.Windows.Forms.Padding(3); this.mountLabel.Size = new System.Drawing.Size(83, 24); this.mountLabel.TabIndex = 98; this.mountLabel.Text = "Mount"; this.mountLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // mountRightButton // this.mountRightButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.mountRightButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.mountRightButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.mountRightButton.Image = global::Tibialyzer.Properties.Resources.rightarrow; this.mountRightButton.Location = new System.Drawing.Point(362, 192); this.mountRightButton.Name = "mountRightButton"; this.mountRightButton.Padding = new System.Windows.Forms.Padding(3); this.mountRightButton.Size = new System.Drawing.Size(24, 24); this.mountRightButton.TabIndex = 97; this.mountRightButton.Click += new System.EventHandler(this.mountRightButton_Click); // // mountLeftButton // this.mountLeftButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.mountLeftButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.mountLeftButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.mountLeftButton.Image = global::Tibialyzer.Properties.Resources.leftarrow; this.mountLeftButton.Location = new System.Drawing.Point(258, 192); this.mountLeftButton.Name = "mountLeftButton"; this.mountLeftButton.Padding = new System.Windows.Forms.Padding(3); this.mountLeftButton.Size = new System.Drawing.Size(24, 24); this.mountLeftButton.TabIndex = 96; this.mountLeftButton.Click += new System.EventHandler(this.mountLeftButton_Click); // // copyTextButton // this.copyTextButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.copyTextButton.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.copyTextButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.copyTextButton.Location = new System.Drawing.Point(258, 245); this.copyTextButton.Name = "copyTextButton"; this.copyTextButton.Padding = new System.Windows.Forms.Padding(3); this.copyTextButton.Size = new System.Drawing.Size(128, 25); this.copyTextButton.TabIndex = 99; this.copyTextButton.Text = "Copy Text"; this.copyTextButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.copyTextButton.Click += new System.EventHandler(this.copyTextButton_Click); // // addon1Toggle // this.addon1Toggle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.addon1Toggle.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.addon1Toggle.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.addon1Toggle.Location = new System.Drawing.Point(258, 217); this.addon1Toggle.Name = "addon1Toggle"; this.addon1Toggle.Padding = new System.Windows.Forms.Padding(3); this.addon1Toggle.Size = new System.Drawing.Size(40, 25); this.addon1Toggle.TabIndex = 100; this.addon1Toggle.Text = "A1"; this.addon1Toggle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.addon1Toggle.Click += new System.EventHandler(this.addon1Toggle_Click); // // addon2Toggle // this.addon2Toggle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.addon2Toggle.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.addon2Toggle.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.addon2Toggle.Location = new System.Drawing.Point(304, 217); this.addon2Toggle.Name = "addon2Toggle"; this.addon2Toggle.Padding = new System.Windows.Forms.Padding(3); this.addon2Toggle.Size = new System.Drawing.Size(40, 25); this.addon2Toggle.TabIndex = 101; this.addon2Toggle.Text = "A2"; this.addon2Toggle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.addon2Toggle.Click += new System.EventHandler(this.addon2Toggle_Click); // // genderToggle // this.genderToggle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(55)))), ((int)(((byte)(59))))); this.genderToggle.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.genderToggle.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(124)))), ((int)(((byte)(133)))), ((int)(((byte)(142))))); this.genderToggle.Location = new System.Drawing.Point(346, 217); this.genderToggle.Name = "genderToggle"; this.genderToggle.Padding = new System.Windows.Forms.Padding(3); this.genderToggle.Size = new System.Drawing.Size(40, 25); this.genderToggle.TabIndex = 102; this.genderToggle.Text = "F"; this.genderToggle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.genderToggle.Click += new System.EventHandler(this.genderToggle_Click); // // OutfiterForm // this.ClientSize = new System.Drawing.Size(392, 279); this.Controls.Add(this.genderToggle); this.Controls.Add(this.addon2Toggle); this.Controls.Add(this.addon1Toggle); this.Controls.Add(this.copyTextButton); this.Controls.Add(this.mountLabel); this.Controls.Add(this.mountRightButton); this.Controls.Add(this.mountLeftButton); this.Controls.Add(this.outfitLabel); this.Controls.Add(this.outfitRightButton); this.Controls.Add(this.outfitLeftButton); this.Controls.Add(this.rotateLabel); this.Controls.Add(this.rotateRightButton); this.Controls.Add(this.rotateLeftButton); this.Controls.Add(this.secondaryColorButton); this.Controls.Add(this.detailColorButton); this.Controls.Add(this.primaryColorButton); this.Controls.Add(this.headColorButton); this.Controls.Add(this.outfiterImageBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "OutfiterForm"; ((System.ComponentModel.ISupportInitialize)(this.outfiterImageBox)).EndInit(); this.ResumeLayout(false); } PictureBox colorPicker; int colorIndex; public override void LoadForm() { if (outfit == null) return; this.SuspendLayout(); NotificationInitialize(); colorPicker = new PictureBox(); colorPicker.Location = new Point(50, 25); colorPicker.Size = new Size(OutfiterManager.OutfitColorBoxSize * OutfiterManager.OutfitColorsPerRow, OutfiterManager.OutfitColorBoxSize * 7); colorPicker.Image = null; colorPicker.MouseDown += ChangeOutfitColor; this.Controls.Add(colorPicker); RefreshColorPicker(0); this.RefreshImage(); ToggleActivation(addon1Toggle, outfit.addon1); ToggleActivation(addon2Toggle, outfit.addon2); ToggleActivation(genderToggle, outfit.gender == Gender.Female); base.NotificationFinalize(); this.ResumeLayout(false); } private void RefreshColorPicker(int colorIndex) { this.colorIndex = colorIndex; headColorButton.Enabled = true; primaryColorButton.Enabled = true; secondaryColorButton.Enabled = true; detailColorButton.Enabled = true; switch (colorIndex) { case 0: headColorButton.Enabled = false; break; case 1: primaryColorButton.Enabled = false; break; case 2: secondaryColorButton.Enabled = false; break; case 3: detailColorButton.Enabled = false; break; } Image oldImage = colorPicker.Image; colorPicker.Image = OutfiterManager.GenerateColorImage(outfit.colors[colorIndex]); if (oldImage != null) { oldImage.Dispose(); } } private void ChangeOutfitColor(object sender, MouseEventArgs e) { int index = OutfiterManager.ColorIndex(e.X, e.Y); if (index < 0) return; outfit.colors[colorIndex] = index; RefreshColorPicker(colorIndex); RefreshImage(); } public void RefreshImage() { Image oldImage = outfiterImageBox.Image; outfiterImageBox.Image = outfit.GetImage(); if (oldImage != null) { oldImage.Dispose(); } } public override string FormName() { return "OutfiterForm"; } private void headColorButton_Click(object sender, EventArgs e) { RefreshColorPicker(0); } private void primaryColorButton_Click(object sender, EventArgs e) { RefreshColorPicker(1); } private void secondaryColorButton_Click(object sender, EventArgs e) { RefreshColorPicker(2); } private void detailColorButton_Click(object sender, EventArgs e) { RefreshColorPicker(3); } private void rotateLeftButton_Click(object sender, EventArgs e) { outfit.Rotate(-1); RefreshImage(); } private void rotateRightButton_Click(object sender, EventArgs e) { outfit.Rotate(1); RefreshImage(); } private void outfitLeftButton_Click(object sender, EventArgs e) { outfit.SwitchOutfit(-1); RefreshImage(); } private void outfitRightButton_Click(object sender, EventArgs e) { outfit.SwitchOutfit(1); RefreshImage(); } private void mountLeftButton_Click(object sender, EventArgs e) { outfit.SwitchMount(-1); RefreshImage(); } private void mountRightButton_Click(object sender, EventArgs e) { outfit.SwitchMount(1); RefreshImage(); } private void copyTextButton_Click(object sender, EventArgs e) { MainForm.mainForm.Invoke((MethodInvoker)delegate { Clipboard.SetText(outfit.ToString()); }); } public void ToggleActivation(Control control, bool activated) { if (!activated) { control.ForeColor = StyleManager.HealthDanger; } else { control.ForeColor = StyleManager.HealthHealthy; } } private void addon1Toggle_Click(object sender, EventArgs e) { outfit.addon1 = !outfit.addon1; ToggleActivation(sender as Control, outfit.addon1); RefreshImage(); } private void addon2Toggle_Click(object sender, EventArgs e) { outfit.addon2 = !outfit.addon2; ToggleActivation(sender as Control, outfit.addon2); RefreshImage(); } private void genderToggle_Click(object sender, EventArgs e) { outfit.gender = outfit.gender == Gender.Male ? Gender.Female : Gender.Male; ToggleActivation(sender as Control, outfit.gender == Gender.Female); RefreshImage(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Xunit; namespace System.Tests { public static partial class AttributeTests { [Fact] public static void DefaultEquality() { var a1 = new ParentAttribute { Prop = 1 }; var a2 = new ParentAttribute { Prop = 42 }; var a3 = new ParentAttribute { Prop = 1 }; var d1 = new ChildAttribute { Prop = 1 }; var d2 = new ChildAttribute { Prop = 42 }; var d3 = new ChildAttribute { Prop = 1 }; var s1 = new GrandchildAttribute { Prop = 1 }; var s2 = new GrandchildAttribute { Prop = 42 }; var s3 = new GrandchildAttribute { Prop = 1 }; var f1 = new ChildAttributeWithField { Prop = 1 }; var f2 = new ChildAttributeWithField { Prop = 42 }; var f3 = new ChildAttributeWithField { Prop = 1 }; Assert.NotEqual(a1, a2); Assert.NotEqual(a2, a3); Assert.Equal(a1, a3); // The implementation of Attribute.Equals uses reflection to // enumerate fields. On .NET core, we add `BindingFlags.DeclaredOnly` // to fix a bug where an instance of a subclass of an attribute can // be equal to an instance of the parent class. // See https://github.com/dotnet/coreclr/pull/6240 Assert.Equal(PlatformDetection.IsFullFramework, d1.Equals(d2)); Assert.Equal(PlatformDetection.IsFullFramework, d2.Equals(d3)); Assert.Equal(d1, d3); Assert.Equal(PlatformDetection.IsFullFramework, s1.Equals(s2)); Assert.Equal(PlatformDetection.IsFullFramework, s2.Equals(s3)); Assert.Equal(s1, s3); Assert.Equal(PlatformDetection.IsFullFramework, f1.Equals(f2)); Assert.Equal(PlatformDetection.IsFullFramework, f2.Equals(f3)); Assert.Equal(f1, f3); Assert.NotEqual(d1, a1); Assert.NotEqual(d2, a2); Assert.NotEqual(d3, a3); Assert.NotEqual(d1, a3); Assert.NotEqual(d3, a1); Assert.NotEqual(d1, s1); Assert.NotEqual(d2, s2); Assert.NotEqual(d3, s3); Assert.NotEqual(d1, s3); Assert.NotEqual(d3, s1); Assert.NotEqual(f1, a1); Assert.NotEqual(f2, a2); Assert.NotEqual(f3, a3); Assert.NotEqual(f1, a3); Assert.NotEqual(f3, a1); } [Fact] public static void DefaultHashCode() { var a1 = new ParentAttribute { Prop = 1 }; var a2 = new ParentAttribute { Prop = 42 }; var a3 = new ParentAttribute { Prop = 1 }; var d1 = new ChildAttribute { Prop = 1 }; var d2 = new ChildAttribute { Prop = 42 }; var d3 = new ChildAttribute { Prop = 1 }; var s1 = new GrandchildAttribute { Prop = 1 }; var s2 = new GrandchildAttribute { Prop = 42 }; var s3 = new GrandchildAttribute { Prop = 1 }; var f1 = new ChildAttributeWithField { Prop = 1 }; var f2 = new ChildAttributeWithField { Prop = 42 }; var f3 = new ChildAttributeWithField { Prop = 1 }; Assert.NotEqual(a1.GetHashCode(), 0); Assert.NotEqual(a2.GetHashCode(), 0); Assert.NotEqual(a3.GetHashCode(), 0); Assert.NotEqual(d1.GetHashCode(), 0); Assert.NotEqual(d2.GetHashCode(), 0); Assert.NotEqual(d3.GetHashCode(), 0); Assert.NotEqual(s1.GetHashCode(), 0); Assert.NotEqual(s2.GetHashCode(), 0); Assert.NotEqual(s3.GetHashCode(), 0); Assert.Equal(f1.GetHashCode(), 0); Assert.Equal(f2.GetHashCode(), 0); Assert.Equal(f3.GetHashCode(), 0); Assert.NotEqual(a1.GetHashCode(), a2.GetHashCode()); Assert.NotEqual(a2.GetHashCode(), a3.GetHashCode()); Assert.Equal(a1.GetHashCode(), a3.GetHashCode()); // The implementation of Attribute.GetHashCode uses reflection to // enumerate fields. On .NET core, we add `BindingFlags.DeclaredOnly` // to fix a bug where the hash code of a a subclass of an attribute can // be equal to an instance of the parent class. // See https://github.com/dotnet/coreclr/pull/6240 Assert.Equal(PlatformDetection.IsFullFramework, s1.GetHashCode().Equals(s2.GetHashCode())); Assert.Equal(PlatformDetection.IsFullFramework, s2.GetHashCode().Equals(s3.GetHashCode())); Assert.Equal(s1.GetHashCode(), s3.GetHashCode()); Assert.Equal(PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(d2.GetHashCode())); Assert.Equal(PlatformDetection.IsFullFramework, d2.GetHashCode().Equals(d3.GetHashCode())); Assert.Equal(d1.GetHashCode(), d3.GetHashCode()); Assert.Equal(f1.GetHashCode(), f2.GetHashCode()); Assert.Equal(f2.GetHashCode(), f3.GetHashCode()); Assert.Equal(f1.GetHashCode(), f3.GetHashCode()); Assert.Equal(!PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(a1.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d2.GetHashCode().Equals(a2.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d3.GetHashCode().Equals(a3.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(a3.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d3.GetHashCode().Equals(a1.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(s1.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d2.GetHashCode().Equals(s2.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d3.GetHashCode().Equals(s3.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(s3.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d3.GetHashCode().Equals(s1.GetHashCode())); Assert.NotEqual(f1.GetHashCode(), a1.GetHashCode()); Assert.NotEqual(f2.GetHashCode(), a2.GetHashCode()); Assert.NotEqual(f3.GetHashCode(), a3.GetHashCode()); Assert.NotEqual(f1.GetHashCode(), a3.GetHashCode()); Assert.NotEqual(f3.GetHashCode(), a1.GetHashCode()); } class ParentAttribute : Attribute { public int Prop {get;set;} } class ChildAttribute : ParentAttribute { } class GrandchildAttribute : ChildAttribute { } class ChildAttributeWithField : ParentAttribute { public int Field = 0; } [Fact] [StringValue("\uDFFF")] [ActiveIssue("TFS 437293 - Invalid Utf8 string in custom attribute argument falls back to wrong value.", TargetFrameworkMonikers.UapAot)] public static void StringArgument_InvalidCodeUnits_FallbackUsed() { MethodInfo thisMethod = typeof(AttributeTests).GetTypeInfo().GetDeclaredMethod("StringArgument_InvalidCodeUnits_FallbackUsed"); Assert.NotNull(thisMethod); CustomAttributeData cad = thisMethod.CustomAttributes.Where(ca => ca.AttributeType == typeof(StringValueAttribute)).FirstOrDefault(); Assert.NotNull(cad); string stringArg = cad.ConstructorArguments[0].Value as string; Assert.NotNull(stringArg); Assert.Equal("\uFFFD\uFFFD", stringArg); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new StringValueAttribute("hello"), new StringValueAttribute("hello"), true, true }; yield return new object[] { new StringValueAttribute("hello"), new StringValueAttribute("foo"), false, false }; yield return new object[] { new StringValueIntValueAttribute("hello", 1), new StringValueIntValueAttribute("hello", 1), true, true }; yield return new object[] { new StringValueIntValueAttribute("hello", 1), new StringValueIntValueAttribute("hello", 2), false, true }; // GetHashCode() ignores the int value yield return new object[] { new EmptyAttribute(), new EmptyAttribute(), true, true }; yield return new object[] { new StringValueAttribute("hello"), new StringValueIntValueAttribute("hello", 1), false, true }; // GetHashCode() ignores the int value yield return new object[] { new StringValueAttribute("hello"), "hello", false, false }; yield return new object[] { new StringValueAttribute("hello"), null, false, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public static void Equals(Attribute attr1, object obj, bool expected, bool hashEqualityExpected) { Assert.Equal(expected, attr1.Equals(obj)); Attribute attr2 = obj as Attribute; if (attr2 != null) { Assert.Equal(hashEqualityExpected, attr1.GetHashCode() == attr2.GetHashCode()); } } [AttributeUsage(AttributeTargets.Method)] private sealed class StringValueAttribute : Attribute { public string StringValue; public StringValueAttribute(string stringValue) { StringValue = stringValue; } } private sealed class StringValueIntValueAttribute : Attribute { public string StringValue; private int IntValue; public StringValueIntValueAttribute(string stringValue, int intValue) { StringValue = stringValue; IntValue = intValue; } } [AttributeUsage(AttributeTargets.Method)] private sealed class EmptyAttribute : Attribute { } [Fact] public static void ValidateDefaults() { StringValueAttribute sav = new StringValueAttribute("test"); Assert.Equal(false, sav.IsDefaultAttribute()); Assert.Equal(sav.GetType(), sav.TypeId); Assert.Equal(true, sav.Match(sav)); } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; using Amazon.Runtime.Internal.Util; using Amazon.Util; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace Amazon.DynamoDBv2 { #region Basic converters internal class ByteConverterV1 : Converter<byte> { protected override bool TryTo(byte value, out Primitive p) { p = new Primitive(value.ToString("d", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out byte result) { return byte.TryParse(p.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } } internal class SByteConverterV1 : Converter<SByte> { protected override bool TryTo(sbyte value, out Primitive p) { p = new Primitive(value.ToString("d", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out sbyte result) { return SByte.TryParse(p.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } } internal class UInt16ConverterV1 : Converter<UInt16> { protected override bool TryTo(ushort value, out Primitive p) { p = new Primitive(value.ToString("d", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out ushort result) { return UInt16.TryParse(p.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } } internal class Int16ConverterV1 : Converter<Int16> { protected override bool TryTo(short value, out Primitive p) { p = new Primitive(value.ToString("d", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out short result) { return Int16.TryParse(p.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } } internal class UInt32ConverterV1 : Converter<UInt32> { protected override bool TryTo(uint value, out Primitive p) { p = new Primitive(value.ToString("d", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out uint result) { return UInt32.TryParse(p.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } } internal class Int32ConverterV1 : Converter<Int32> { protected override bool TryTo(int value, out Primitive p) { p = new Primitive(value.ToString("d", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out int result) { return Int32.TryParse(p.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } } internal class UInt64ConverterV1 : Converter<UInt64> { protected override bool TryTo(ulong value, out Primitive p) { p = new Primitive(value.ToString("d", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out ulong result) { return UInt64.TryParse(p.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } } internal class Int64ConverterV1 : Converter<Int64> { protected override bool TryTo(long value, out Primitive p) { p = new Primitive(value.ToString("d", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out long result) { return Int64.TryParse(p.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } } internal class SingleConverterV1 : Converter<Single> { protected override bool TryTo(float value, out Primitive p) { p = new Primitive(value.ToString("r", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out float result) { return Single.TryParse(p.StringValue, NumberStyles.Float, CultureInfo.InvariantCulture, out result); } } internal class DoubleConverterV1 : Converter<Double> { protected override bool TryTo(double value, out Primitive p) { p = new Primitive(value.ToString("r", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out double result) { return Double.TryParse(p.StringValue, NumberStyles.Float, CultureInfo.InvariantCulture, out result); } } internal class DecimalConverterV1 : Converter<Decimal> { protected override bool TryTo(decimal value, out Primitive p) { p = new Primitive(value.ToString("g", CultureInfo.InvariantCulture), DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(Primitive p, Type targetType, out decimal result) { return Decimal.TryParse(p.StringValue, NumberStyles.Float, CultureInfo.InvariantCulture, out result); } } internal class CharConverterV1 : Converter<Char> { protected override bool TryTo(char value, out Primitive p) { p = new Primitive(value.ToString(CultureInfo.InvariantCulture), DynamoDBEntryType.String); return true; } protected override bool TryFrom(Primitive p, Type targetType, out char result) { return Char.TryParse(p.StringValue, out result); } } internal class StringConverterV1 : Converter<String> { protected override bool TryTo(string value, out Primitive p) { p = new Primitive(value, DynamoDBEntryType.String); return true; } protected override bool TryFrom(Primitive p, Type targetType, out string result) { result = p.StringValue; return (result != null); } } internal class DateTimeConverterV1 : Converter<DateTime> { protected override bool TryTo(DateTime value, out Primitive p) { DateTime utc = value.ToUniversalTime(); p = new Primitive(utc.ToString(AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture), DynamoDBEntryType.String); return true; } protected override bool TryFrom(Primitive p, Type targetType, out DateTime result) { return DateTime.TryParseExact( p.StringValue, AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out result); } } internal class GuidConverterV1 : Converter<Guid> { protected override bool TryTo(Guid value, out Primitive p) { p = new Primitive(value.ToString("D", CultureInfo.InvariantCulture), DynamoDBEntryType.String); return true; } protected override bool TryFrom(Primitive p, Type targetType, out Guid result) { result = new Guid(p.StringValue); return true; } } internal class BytesConverterV1 : Converter<byte[]> { protected override bool TryTo(byte[] value, out Primitive p) { p = new Primitive(value); return true; } protected override bool TryFrom(Primitive p, Type targetType, out byte[] result) { result = p.Value as byte[]; return (result != null); } } internal class MemoryStreamConverterV1 : Converter<MemoryStream> { protected override bool TryTo(MemoryStream value, out Primitive p) { p = new Primitive(value); return true; } protected override bool TryFrom(Primitive p, Type targetType, out MemoryStream result) { var bytes = p.Value as byte[]; if (bytes == null) { result = null; return false; } result = new MemoryStream(bytes); return true; } } #endregion #region Converters supporting reading V2 DDB items, but writing V1 items /// <summary> /// A boolean converter which reads booleans as N or BOOL types, /// but writes out N type (1 if true, 0 if false). /// </summary> internal class BoolConverterV1 : Converter<bool> { protected override bool TryTo(bool value, out Primitive p) { p = new Primitive(value ? "1" : "0", DynamoDBEntryType.Numeric); return true; } protected override bool TryFrom(DynamoDBBool b, Type targetType, out bool result) { result = b.Value; return true; } protected override bool TryFrom(Primitive p, Type targetType, out bool result) { result = !p.StringValue.Equals("0", StringComparison.OrdinalIgnoreCase); return true; } } internal abstract class CollectionConverter : Converter { private IEnumerable<Type> targetTypes; private static IEnumerable<Type> GetTargetTypes(IEnumerable<Type> memberTypes) { var listType = typeof(List<>); var setType = typeof(HashSet<>); foreach (var pt in memberTypes) { // typeof(T[]), if (pt != typeof(byte)) { yield return pt.MakeArrayType(); } // typeof(List<T>), yield return listType.MakeGenericType(pt); // typeof(HashSet<T>), yield return setType.MakeGenericType(pt); } } public CollectionConverter(IEnumerable<Type> memberTypes) { targetTypes = GetTargetTypes(memberTypes); } public override IEnumerable<Type> GetTargetTypes() { return targetTypes; } protected bool EntriesToCollection(Type targetType, Type elementType, IEnumerable<DynamoDBEntry> entries, out object result) { var items = Conversion.ConvertFromEntries(elementType, entries); return Utils.ItemsToCollection(targetType, items, out result); } } /// <summary> /// A collection converter which reads both sets of collections (sets and lists) /// and writes out sets (NS, SS, BS) /// </summary> internal class PrimitiveCollectionConverterV1 : CollectionConverter { public PrimitiveCollectionConverterV1() : base(Utils.PrimitiveTypes) { } public override bool TryTo(object value, out PrimitiveList pl) { var items = value as IEnumerable; if (items != null) { pl = Conversion.ItemsToPrimitiveList(items); return true; } pl = null; return false; } public override bool TryFrom(PrimitiveList pl, Type targetType, out object result) { var elementType = Utils.GetPrimitiveElementType(targetType); return EntriesToCollection(targetType, elementType, pl.Entries.Cast<DynamoDBEntry>(), out result); } public override bool TryFrom(DynamoDBList l, Type targetType, out object result) { var elementType = Utils.GetPrimitiveElementType(targetType); var entries = l.Entries; return EntriesToCollection(targetType, elementType, entries, out result); } } /// <summary> /// Dictionary converter. /// Converts from Dictionary{string,object} to DynamoDBEntry. /// Does NOT convert from DynamoDBEntry to Dictionary{string,object}. /// </summary> internal class DictionaryConverterV1 : Converter { public override IEnumerable<Type> GetTargetTypes() { yield return typeof(Dictionary<string, object>); } public override bool TryTo(object value, out Document d) { var items = value as IDictionary<string, object>; if (items != null) { d = new Document(); foreach(var kvp in items) { string name = kvp.Key; object item = kvp.Value; DynamoDBEntry entry = null; if (item != null) { Type itemType = item.GetType(); entry = Conversion.ConvertToEntry(itemType, item); } d[name] = entry; } return true; } d = null; return false; } } #endregion }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ #define SPINE_OPTIONAL_RENDEROVERRIDE using UnityEngine; using System.Collections.Generic; using Spine.Unity; namespace Spine.Unity.Modules { [ExecuteInEditMode] [HelpURL("https://github.com/pharan/spine-unity-docs/blob/master/SkeletonRenderSeparator.md")] public class SkeletonRenderSeparator : MonoBehaviour { public const int DefaultSortingOrderIncrement = 5; #region Inspector [SerializeField] protected SkeletonRenderer skeletonRenderer; public SkeletonRenderer SkeletonRenderer { get { return skeletonRenderer; } set { #if SPINE_OPTIONAL_RENDEROVERRIDE if (skeletonRenderer != null) skeletonRenderer.GenerateMeshOverride -= HandleRender; #endif skeletonRenderer = value; this.enabled = false; // Disable if nulled. } } MeshRenderer mainMeshRenderer; public bool copyPropertyBlock = true; [Tooltip("Copies MeshRenderer flags into each parts renderer")] public bool copyMeshRendererFlags = true; public List<Spine.Unity.Modules.SkeletonPartsRenderer> partsRenderers = new List<SkeletonPartsRenderer>(); #if UNITY_EDITOR void Reset () { if (skeletonRenderer == null) skeletonRenderer = GetComponent<SkeletonRenderer>(); } #endif #endregion #region Runtime Instantiation public static SkeletonRenderSeparator AddToSkeletonRenderer (SkeletonRenderer skeletonRenderer, int sortingLayerID = 0, int extraPartsRenderers = 0, int sortingOrderIncrement = DefaultSortingOrderIncrement, int baseSortingOrder = 0, bool addMinimumPartsRenderers = true) { if (skeletonRenderer == null) { Debug.Log("Tried to add SkeletonRenderSeparator to a null SkeletonRenderer reference."); return null; } var srs = skeletonRenderer.gameObject.AddComponent<SkeletonRenderSeparator>(); srs.skeletonRenderer = skeletonRenderer; skeletonRenderer.Initialize(false); int count = extraPartsRenderers; if (addMinimumPartsRenderers) count = extraPartsRenderers + skeletonRenderer.separatorSlots.Count + 1; var skeletonRendererTransform = skeletonRenderer.transform; var componentRenderers = srs.partsRenderers; for (int i = 0; i < count; i++) { var smr = SkeletonPartsRenderer.NewPartsRendererGameObject(skeletonRendererTransform, i.ToString()); var mr = smr.MeshRenderer; mr.sortingLayerID = sortingLayerID; mr.sortingOrder = baseSortingOrder + (i * sortingOrderIncrement); componentRenderers.Add(smr); } return srs; } #endregion void OnEnable () { if (skeletonRenderer == null) return; if (copiedBlock == null) copiedBlock = new MaterialPropertyBlock(); mainMeshRenderer = skeletonRenderer.GetComponent<MeshRenderer>(); #if SPINE_OPTIONAL_RENDEROVERRIDE skeletonRenderer.GenerateMeshOverride -= HandleRender; skeletonRenderer.GenerateMeshOverride += HandleRender; #endif #if UNITY_5_4_OR_NEWER if (copyMeshRendererFlags) { var lightProbeUsage = mainMeshRenderer.lightProbeUsage; bool receiveShadows = mainMeshRenderer.receiveShadows; #if UNITY_5_5_OR_NEWER var reflectionProbeUsage = mainMeshRenderer.reflectionProbeUsage; var shadowCastingMode = mainMeshRenderer.shadowCastingMode; var motionVectorGenerationMode = mainMeshRenderer.motionVectorGenerationMode; var probeAnchor = mainMeshRenderer.probeAnchor; #endif for (int i = 0; i < partsRenderers.Count; i++) { var currentRenderer = partsRenderers[i]; if (currentRenderer == null) continue; // skip null items. var mr = currentRenderer.MeshRenderer; mr.lightProbeUsage = lightProbeUsage; mr.receiveShadows = receiveShadows; #if UNITY_5_5_OR_NEWER mr.reflectionProbeUsage = reflectionProbeUsage; mr.shadowCastingMode = shadowCastingMode; mr.motionVectorGenerationMode = motionVectorGenerationMode; mr.probeAnchor = probeAnchor; #endif } } #else if (copyMeshRendererFlags) { var useLightProbes = mainMeshRenderer.useLightProbes; bool receiveShadows = mainMeshRenderer.receiveShadows; for (int i = 0; i < partsRenderers.Count; i++) { var currentRenderer = partsRenderers[i]; if (currentRenderer == null) continue; // skip null items. var mr = currentRenderer.MeshRenderer; mr.useLightProbes = useLightProbes; mr.receiveShadows = receiveShadows; } } #endif } void OnDisable () { if (skeletonRenderer == null) return; #if SPINE_OPTIONAL_RENDEROVERRIDE skeletonRenderer.GenerateMeshOverride -= HandleRender; #endif #if UNITY_EDITOR skeletonRenderer.LateUpdate(); #endif foreach (var s in partsRenderers) s.ClearMesh(); } MaterialPropertyBlock copiedBlock; void HandleRender (SkeletonRendererInstruction instruction) { int rendererCount = partsRenderers.Count; if (rendererCount <= 0) return; if (copyPropertyBlock) mainMeshRenderer.GetPropertyBlock(copiedBlock); var settings = new MeshGenerator.Settings { addNormals = skeletonRenderer.addNormals, calculateTangents = skeletonRenderer.calculateTangents, immutableTriangles = false, // parts cannot do immutable triangles. pmaVertexColors = skeletonRenderer.pmaVertexColors, //renderMeshes = skeletonRenderer.renderMeshes, tintBlack = skeletonRenderer.tintBlack, useClipping = true, zSpacing = skeletonRenderer.zSpacing }; var submeshInstructions = instruction.submeshInstructions; var submeshInstructionsItems = submeshInstructions.Items; int lastSubmeshInstruction = submeshInstructions.Count - 1; int rendererIndex = 0; var currentRenderer = partsRenderers[rendererIndex]; for (int si = 0, start = 0; si <= lastSubmeshInstruction; si++) { if (submeshInstructionsItems[si].forceSeparate || si == lastSubmeshInstruction) { // Apply properties var meshGenerator = currentRenderer.MeshGenerator; meshGenerator.settings = settings; if (copyPropertyBlock) currentRenderer.SetPropertyBlock(copiedBlock); // Render currentRenderer.RenderParts(instruction.submeshInstructions, start, si + 1); start = si + 1; rendererIndex++; if (rendererIndex < rendererCount) { currentRenderer = partsRenderers[rendererIndex]; } else { // Not enough renderers. Skip the rest of the instructions. break; } } } // Clear extra renderers if they exist. for (; rendererIndex < rendererCount; rendererIndex++) { partsRenderers[rendererIndex].ClearMesh(); } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // DistinctQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// This operator yields all of the distinct elements in a single data set. It works quite /// like the above set operations, with the obvious difference being that it only accepts /// a single data source as input. /// </summary> /// <typeparam name="TInputOutput"></typeparam> internal sealed class DistinctQueryOperator<TInputOutput> : UnaryQueryOperator<TInputOutput, TInputOutput> { private readonly IEqualityComparer<TInputOutput>? _comparer; // An (optional) equality comparer. //--------------------------------------------------------------------------------------- // Constructs a new distinction operator. // internal DistinctQueryOperator(IEnumerable<TInputOutput> source, IEqualityComparer<TInputOutput>? comparer) : base(source) { Debug.Assert(source != null, "child data source cannot be null"); _comparer = comparer; SetOrdinalIndexState(OrdinalIndexState.Shuffled); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TInputOutput> Open(QuerySettings settings, bool preferStriping) { // We just open our child operator. Do not propagate the preferStriping value, but // instead explicitly set it to false. Regardless of whether the parent prefers striping or range // partitioning, the output will be hash-partitioned. QueryResults<TInputOutput> childResults = Child.Open(settings, false); return new UnaryQueryOperatorResults(childResults, this, settings, false); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TInputOutput, TKey> inputStream, IPartitionedStreamRecipient<TInputOutput> recipient, bool preferStriping, QuerySettings settings) { // Hash-repartition the source stream if (OutputOrdered) { WrapPartitionedStreamHelper<TKey>( ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TKey>( inputStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken), recipient, settings.CancellationState.MergedCancellationToken); } else { WrapPartitionedStreamHelper<int>( ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TKey>( inputStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken), recipient, settings.CancellationState.MergedCancellationToken); } } //--------------------------------------------------------------------------------------- // This is a helper method. WrapPartitionedStream decides what type TKey is going // to be, and then call this method with that key as a generic parameter. // private void WrapPartitionedStreamHelper<TKey>( PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> hashStream, IPartitionedStreamRecipient<TInputOutput> recipient, CancellationToken cancellationToken) { int partitionCount = hashStream.PartitionCount; PartitionedStream<TInputOutput, TKey> outputStream = new PartitionedStream<TInputOutput, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { if (OutputOrdered) { outputStream[i] = new OrderedDistinctQueryOperatorEnumerator<TKey>(hashStream[i], _comparer, hashStream.KeyComparer, cancellationToken); } else { outputStream[i] = (QueryOperatorEnumerator<TInputOutput, TKey>)(object) new DistinctQueryOperatorEnumerator<TKey>(hashStream[i], _comparer, cancellationToken); } } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // This enumerator performs the distinct operation incrementally. It does this by // maintaining a history -- in the form of a set -- of all data already seen. It simply // then doesn't return elements it has already seen before. // private class DistinctQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TInputOutput, int> { private readonly QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> _source; // The data source. private readonly Set<TInputOutput> _hashLookup; // The hash lookup, used to produce the distinct set. private readonly CancellationToken _cancellationToken; private Shared<int>? _outputLoopCount; // Allocated in MoveNext to avoid false sharing. //--------------------------------------------------------------------------------------- // Instantiates a new distinction operator. // internal DistinctQueryOperatorEnumerator( QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> source, IEqualityComparer<TInputOutput>? comparer, CancellationToken cancellationToken) { Debug.Assert(source != null); _source = source; _hashLookup = new Set<TInputOutput>(comparer); _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the single data source, skipping elements it has already seen. // internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TInputOutput currentElement, ref int currentKey) { Debug.Assert(_source != null); Debug.Assert(_hashLookup != null); // Iterate over this set's elements until we find a unique element. TKey keyUnused = default!; Pair<TInputOutput, NoKeyMemoizationRequired> current = default(Pair<TInputOutput, NoKeyMemoizationRequired>); if (_outputLoopCount == null) _outputLoopCount = new Shared<int>(0); while (_source.MoveNext(ref current, ref keyUnused)) { if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // We ensure we never return duplicates by tracking them in our set. if (_hashLookup.Add(current.First)) { #if DEBUG currentKey = unchecked((int)0xdeadbeef); #endif currentElement = current.First; return true; } } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_source != null); _source.Dispose(); } } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { IEnumerable<TInputOutput> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.Distinct(_comparer); } private class OrderedDistinctQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TInputOutput, TKey> { private readonly QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> _source; // The data source. private readonly Dictionary<Wrapper<TInputOutput>, TKey> _hashLookup; // The hash lookup, used to produce the distinct set. private readonly IComparer<TKey> _keyComparer; // Comparer to decide the key order. private IEnumerator<KeyValuePair<Wrapper<TInputOutput>, TKey>>? _hashLookupEnumerator; // Enumerates over _hashLookup. private readonly CancellationToken _cancellationToken; //--------------------------------------------------------------------------------------- // Instantiates a new distinction operator. // internal OrderedDistinctQueryOperatorEnumerator( QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> source, IEqualityComparer<TInputOutput>? comparer, IComparer<TKey> keyComparer, CancellationToken cancellationToken) { Debug.Assert(source != null); _source = source; _keyComparer = keyComparer; _hashLookup = new Dictionary<Wrapper<TInputOutput>, TKey>( new WrapperEqualityComparer<TInputOutput>(comparer)); _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the single data source, skipping elements it has already seen. // internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TInputOutput currentElement, ref TKey currentKey) { Debug.Assert(_source != null); Debug.Assert(_hashLookup != null); if (_hashLookupEnumerator == null) { Pair<TInputOutput, NoKeyMemoizationRequired> elem = default(Pair<TInputOutput, NoKeyMemoizationRequired>); TKey orderKey = default!; int i = 0; while (_source.MoveNext(ref elem, ref orderKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // For each element, we track the smallest order key for that element that we saw so far TKey oldEntry; Wrapper<TInputOutput> wrappedElem = new Wrapper<TInputOutput>(elem.First); // If this is the first occurrence of this element, or the order key is lower than all keys we saw previously, // update the order key for this element. if (!_hashLookup.TryGetValue(wrappedElem, out oldEntry!) || _keyComparer.Compare(orderKey, oldEntry) < 0) { // For each "elem" value, we store the smallest key, and the element value that had that key. // Note that even though two element values are "equal" according to the EqualityComparer, // we still cannot choose arbitrarily which of the two to yield. _hashLookup[wrappedElem] = orderKey; } } _hashLookupEnumerator = _hashLookup.GetEnumerator(); } if (_hashLookupEnumerator.MoveNext()) { KeyValuePair<Wrapper<TInputOutput>, TKey> currentPair = _hashLookupEnumerator.Current; currentElement = currentPair.Key.Value; currentKey = currentPair.Value; return true; } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_source != null); _source.Dispose(); if (_hashLookupEnumerator != null) { _hashLookupEnumerator.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System { // DateTimeOffset is a value type that consists of a DateTime and a time zone offset, // ie. how far away the time is from GMT. The DateTime is stored whole, and the offset // is stored as an Int16 internally to save space, but presented as a TimeSpan. // // The range is constrained so that both the represented clock time and the represented // UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime // for actual UTC times, and a slightly constrained range on one end when an offset is // present. // // This class should be substitutable for date time in most cases; so most operations // effectively work on the clock time. However, the underlying UTC time is what counts // for the purposes of identity, sorting and subtracting two instances. // // // There are theoretically two date times stored, the UTC and the relative local representation // or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable // for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this // out and for internal readability. [StructLayout(LayoutKind.Auto)] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct DateTimeOffset : IComparable, IFormattable, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>, ISerializable, IDeserializationCallback, ISpanFormattable { // Constants internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14; internal const Int64 MinOffset = -MaxOffset; private const long UnixEpochSeconds = DateTime.UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 private const long UnixEpochMilliseconds = DateTime.UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 internal const long UnixMinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; internal const long UnixMaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; // Static Fields public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero); public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero); public static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(DateTime.UnixEpochTicks, TimeSpan.Zero); // Instance Fields private DateTime _dateTime; private Int16 _offsetMinutes; // Constructors // Constructs a DateTimeOffset from a tick count and offset public DateTimeOffset(long ticks, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); // Let the DateTime constructor do the range checks DateTime dateTime = new DateTime(ticks); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds, // extracts the local offset. For UTC, creates a UTC instance with a zero offset. public DateTimeOffset(DateTime dateTime) { TimeSpan offset; if (dateTime.Kind != DateTimeKind.Utc) { // Local and Unspecified are both treated as Local offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else { offset = new TimeSpan(0); } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time // consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that // the offset corresponds to the local. public DateTimeOffset(DateTime dateTime, TimeSpan offset) { if (dateTime.Kind == DateTimeKind.Local) { if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) { throw new ArgumentException(SR.Argument_OffsetLocalMismatch, nameof(offset)); } } else if (dateTime.Kind == DateTimeKind.Utc) { if (offset != TimeSpan.Zero) { throw new ArgumentException(SR.Argument_OffsetUtcMismatch, nameof(offset)); } } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond and offset public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond, Calendar and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset); } // Returns a DateTimeOffset representing the current date and time. The // resolution of the returned value depends on the system timer. public static DateTimeOffset Now { get { return new DateTimeOffset(DateTime.Now); } } public static DateTimeOffset UtcNow { get { return new DateTimeOffset(DateTime.UtcNow); } } public DateTime DateTime { get { return ClockDateTime; } } public DateTime UtcDateTime { get { return DateTime.SpecifyKind(_dateTime, DateTimeKind.Utc); } } public DateTime LocalDateTime { get { return UtcDateTime.ToLocalTime(); } } // Adjust to a given offset with the same UTC time. Can throw ArgumentException // public DateTimeOffset ToOffset(TimeSpan offset) { return new DateTimeOffset((_dateTime + offset).Ticks, offset); } // Instance Properties // The clock or visible time represented. This is just a wrapper around the internal date because this is // the chosen storage mechanism. Going through this helper is good for readability and maintainability. // This should be used for display but not identity. private DateTime ClockDateTime { get { return new DateTime((_dateTime + Offset).Ticks, DateTimeKind.Unspecified); } } // Returns the date part of this DateTimeOffset. The resulting value // corresponds to this DateTimeOffset with the time-of-day part set to // zero (midnight). // public DateTime Date { get { return ClockDateTime.Date; } } // Returns the day-of-month part of this DateTimeOffset. The returned // value is an integer between 1 and 31. // public int Day { get { return ClockDateTime.Day; } } // Returns the day-of-week part of this DateTimeOffset. 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 DayOfWeek DayOfWeek { get { return ClockDateTime.DayOfWeek; } } // Returns the day-of-year part of this DateTimeOffset. The returned value // is an integer between 1 and 366. // public int DayOfYear { get { return ClockDateTime.DayOfYear; } } // Returns the hour part of this DateTimeOffset. The returned value is an // integer between 0 and 23. // public int Hour { get { return ClockDateTime.Hour; } } // Returns the millisecond part of this DateTimeOffset. The returned value // is an integer between 0 and 999. // public int Millisecond { get { return ClockDateTime.Millisecond; } } // Returns the minute part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Minute { get { return ClockDateTime.Minute; } } // Returns the month part of this DateTimeOffset. The returned value is an // integer between 1 and 12. // public int Month { get { return ClockDateTime.Month; } } public TimeSpan Offset { get { return new TimeSpan(0, _offsetMinutes, 0); } } // Returns the second part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Second { get { return ClockDateTime.Second; } } // Returns the tick count for this DateTimeOffset. The returned value is // the number of 100-nanosecond intervals that have elapsed since 1/1/0001 // 12:00am. // public long Ticks { get { return ClockDateTime.Ticks; } } public long UtcTicks { get { return UtcDateTime.Ticks; } } // Returns the time-of-day part of this DateTimeOffset. The returned value // is a TimeSpan that indicates the time elapsed since midnight. // public TimeSpan TimeOfDay { get { return ClockDateTime.TimeOfDay; } } // Returns the year part of this DateTimeOffset. The returned value is an // integer between 1 and 9999. // public int Year { get { return ClockDateTime.Year; } } // Returns the DateTimeOffset resulting from adding the given // TimeSpan to this DateTimeOffset. // public DateTimeOffset Add(TimeSpan timeSpan) { return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // days to this DateTimeOffset. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddDays(double days) { return new DateTimeOffset(ClockDateTime.AddDays(days), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // hours to this DateTimeOffset. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddHours(double hours) { return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset); } // Returns the DateTimeOffset resulting from the given number of // milliseconds to this DateTimeOffset. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to this DateTimeOffset. The value // argument is permitted to be negative. // public DateTimeOffset AddMilliseconds(double milliseconds) { return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // minutes to this DateTimeOffset. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddMinutes(double minutes) { return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset); } public DateTimeOffset AddMonths(int months) { return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // seconds to this DateTimeOffset. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddSeconds(double seconds) { return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // 100-nanosecond ticks to this DateTimeOffset. The value argument // is permitted to be negative. // public DateTimeOffset AddTicks(long ticks) { return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // years to this DateTimeOffset. The result is computed by incrementing // (or decrementing) the year part of this DateTimeOffset by value // years. If the month and day of this DateTimeOffset is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of this DateTimeOffset. // public DateTimeOffset AddYears(int years) { return new DateTimeOffset(ClockDateTime.AddYears(years), Offset); } // Compares two DateTimeOffset values, returning an integer that indicates // their relationship. // public static int Compare(DateTimeOffset first, DateTimeOffset second) { return DateTime.Compare(first.UtcDateTime, second.UtcDateTime); } // Compares this DateTimeOffset to a given object. This method provides an // implementation of the IComparable interface. The object // argument must be another DateTimeOffset, or otherwise an exception // occurs. Null is considered less than any instance. // int IComparable.CompareTo(Object obj) { if (obj == null) return 1; if (!(obj is DateTimeOffset)) { throw new ArgumentException(SR.Arg_MustBeDateTimeOffset); } DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime; DateTime utc = UtcDateTime; if (utc > objUtc) return 1; if (utc < objUtc) return -1; return 0; } public int CompareTo(DateTimeOffset other) { DateTime otherUtc = other.UtcDateTime; DateTime utc = UtcDateTime; if (utc > otherUtc) return 1; if (utc < otherUtc) return -1; return 0; } // Checks if this DateTimeOffset is equal to a given object. Returns // true if the given object is a boxed DateTimeOffset and its value // is equal to the value of this DateTimeOffset. Returns false // otherwise. // public override bool Equals(Object obj) { if (obj is DateTimeOffset) { return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime); } return false; } public bool Equals(DateTimeOffset other) { return UtcDateTime.Equals(other.UtcDateTime); } public bool EqualsExact(DateTimeOffset other) { // // returns true when the ClockDateTime, Kind, and Offset match // // currently the Kind should always be Unspecified, but there is always the possibility that a future version // of DateTimeOffset overloads the Kind field // return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind); } // Compares two DateTimeOffset values for equality. Returns true if // the two DateTimeOffset values are equal, or false if they are // not equal. // public static bool Equals(DateTimeOffset first, DateTimeOffset second) { return DateTime.Equals(first.UtcDateTime, second.UtcDateTime); } // Creates a DateTimeOffset from a Windows filetime. A Windows filetime is // a long representing the date and time as the number of // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am. // public static DateTimeOffset FromFileTime(long fileTime) { return new DateTimeOffset(DateTime.FromFileTime(fileTime)); } public static DateTimeOffset FromUnixTimeSeconds(long seconds) { if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds) { throw new ArgumentOutOfRangeException(nameof(seconds), SR.Format(SR.ArgumentOutOfRange_Range, UnixMinSeconds, UnixMaxSeconds)); } long ticks = seconds * TimeSpan.TicksPerSecond + DateTime.UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) { const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) { throw new ArgumentOutOfRangeException(nameof(milliseconds), SR.Format(SR.ArgumentOutOfRange_Range, MinMilliseconds, MaxMilliseconds)); } long ticks = milliseconds * TimeSpan.TicksPerMillisecond + DateTime.UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } // ----- SECTION: private serialization instance methods ----------------* void IDeserializationCallback.OnDeserialization(Object sender) { try { _offsetMinutes = ValidateOffset(Offset); _dateTime = ValidateDate(ClockDateTime, Offset); } catch (ArgumentException e) { throw new SerializationException(SR.Serialization_InvalidData, e); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue("DateTime", _dateTime); // Do not rename (binary serialization) info.AddValue("OffsetMinutes", _offsetMinutes); // Do not rename (binary serialization) } private DateTimeOffset(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } _dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime)); // Do not rename (binary serialization) _offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16)); // Do not rename (binary serialization) } // Returns the hash code for this DateTimeOffset. // public override int GetHashCode() { return UtcDateTime.GetHashCode(); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return Parse(input, formatProvider, DateTimeStyles.None); } public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset Parse(ReadOnlySpan<char> input, IFormatProvider formatProvider = null, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return ParseExact(input, format, formatProvider, DateTimeStyles.None); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, DateTimeStyles styles) { if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return ParseExact(input, (ReadOnlySpan<char>)format, formatProvider, styles); } public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); DateTime dateResult = DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset); return new DateTimeOffset(dateResult.Ticks, offset); } public TimeSpan Subtract(DateTimeOffset value) { return UtcDateTime.Subtract(value.UtcDateTime); } public DateTimeOffset Subtract(TimeSpan value) { return new DateTimeOffset(ClockDateTime.Subtract(value), Offset); } public long ToFileTime() { return UtcDateTime.ToFileTime(); } public long ToUnixTimeSeconds() { // Truncate sub-second precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times. // // For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0 // ticks = 621355967990010000 // ticksFromEpoch = ticks - DateTime.UnixEpochTicks = -9990000 // secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0 // // Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division, // whereas we actually always want to round *down* when converting to Unix time. This happens // automatically for positive Unix time values. Now the example becomes: // seconds = ticks / TimeSpan.TicksPerSecond = 62135596799 // secondsFromEpoch = seconds - UnixEpochSeconds = -1 // // In other words, we want to consistently round toward the time 1/1/0001 00:00:00, // rather than toward the Unix Epoch (1/1/1970 00:00:00). long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond; return seconds - UnixEpochSeconds; } public long ToUnixTimeMilliseconds() { // Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond; return milliseconds - UnixEpochMilliseconds; } public DateTimeOffset ToLocalTime() { return ToLocalTime(false); } internal DateTimeOffset ToLocalTime(bool throwOnOverflow) { return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow)); } public override String ToString() { return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset); } public String ToString(String format) { return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset); } public String ToString(IFormatProvider formatProvider) { return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset); } public String ToString(String format, IFormatProvider formatProvider) { return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset); } // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures public bool TryFormat(Span<char> destination, out int charsWritten, string format, IFormatProvider provider) => TryFormat(destination, out charsWritten, (ReadOnlySpan<char>)format, provider); public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider formatProvider = null) => DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset); public DateTimeOffset ToUniversalTime() { return new DateTimeOffset(UtcDateTime); } public static Boolean TryParse(String input, out DateTimeOffset result) { TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParse(ReadOnlySpan<char> input, out DateTimeOffset result) { bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out DateTime dateResult, out TimeSpan offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) { result = default(DateTimeOffset); return false; } TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null || format == null) { result = default(DateTimeOffset); return false; } TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures public static bool TryParseExact(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { if (format == null) { result = default; return false; } return TryParseExact(input, (ReadOnlySpan<char>)format, formatProvider, styles, out result); } public static bool TryParseExact( ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); bool parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) { result = default(DateTimeOffset); return false; } TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParseExact( ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); bool parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } // Ensures the TimeSpan is valid to go in a DateTimeOffset. private static Int16 ValidateOffset(TimeSpan offset) { Int64 ticks = offset.Ticks; if (ticks % TimeSpan.TicksPerMinute != 0) { throw new ArgumentException(SR.Argument_OffsetPrecision, nameof(offset)); } if (ticks < MinOffset || ticks > MaxOffset) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_OffsetOutOfRange); } return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute); } // Ensures that the time and offset are in range. private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) { // The key validation is that both the UTC and clock times fit. The clock time is validated // by the DateTime constructor. Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated."); // This operation cannot overflow because offset should have already been validated to be within // 14 hours and the DateTime instance is more than that distance from the boundaries of Int64. Int64 utcTicks = dateTime.Ticks - offset.Ticks; if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_UTCOutOfRange); } // make sure the Kind is set to Unspecified // return new DateTime(utcTicks, DateTimeKind.Unspecified); } private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) { if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidDateTimeStyles, parameterName); } if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) { throw new ArgumentException(SR.Argument_ConflictingDateTimeStyles, parameterName); } if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) { throw new ArgumentException(SR.Argument_DateTimeOffsetInvalidDateTimeStyles, parameterName); } // RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatibility with DateTime style &= ~DateTimeStyles.RoundtripKind; // AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse style &= ~DateTimeStyles.AssumeLocal; return style; } // Operators public static implicit operator DateTimeOffset(DateTime dateTime) { return new DateTimeOffset(dateTime); } public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset); } public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset); } public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime - right.UtcDateTime; } public static bool operator ==(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime == right.UtcDateTime; } public static bool operator !=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime != right.UtcDateTime; } public static bool operator <(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime < right.UtcDateTime; } public static bool operator <=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime <= right.UtcDateTime; } public static bool operator >(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime > right.UtcDateTime; } public static bool operator >=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime >= right.UtcDateTime; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Principal; using Xunit; using System.Text; using System.ComponentModel; using System.Security; namespace System.Diagnostics.Tests { public partial class ProcessStartInfoTests : ProcessTestBase { [Fact] public void TestEnvironmentProperty() { Assert.NotEqual(0, new Process().StartInfo.Environment.Count); ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. IDictionary<string, string> environment = psi.Environment; Assert.NotEqual(environment.Count, 0); int CountItems = environment.Count; environment.Add("NewKey", "NewValue"); environment.Add("NewKey2", "NewValue2"); Assert.Equal(CountItems + 2, environment.Count); environment.Remove("NewKey"); Assert.Equal(CountItems + 1, environment.Count); //Exception not thrown with invalid key Assert.Throws<ArgumentException>(() => { environment.Add("NewKey2", "NewValue2"); }); //Clear environment.Clear(); Assert.Equal(0, environment.Count); //ContainsKey environment.Add("NewKey", "NewValue"); environment.Add("NewKey2", "NewValue2"); Assert.True(environment.ContainsKey("NewKey")); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.ContainsKey("newkey")); Assert.False(environment.ContainsKey("NewKey99")); //Iterating string result = null; int index = 0; foreach (string e1 in environment.Values) { index++; result += e1; } Assert.Equal(2, index); Assert.Equal("NewValueNewValue2", result); result = null; index = 0; foreach (string e1 in environment.Keys) { index++; result += e1; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); result = null; index = 0; foreach (KeyValuePair<string, string> e1 in environment) { index++; result += e1.Key; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); //Contains Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey", "NewValue"))); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("nEwKeY", "NewValue"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey99", "NewValue99"))); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environment.Contains(new KeyValuePair<string, string>(null, "NewValue99"))); environment.Add(new KeyValuePair<string, string>("NewKey98", "NewValue98")); //Indexed string newIndexItem = environment["NewKey98"]; Assert.Equal("NewValue98", newIndexItem); //TryGetValue string stringout = null; Assert.True(environment.TryGetValue("NewKey", out stringout)); Assert.Equal("NewValue", stringout); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.True(environment.TryGetValue("NeWkEy", out stringout)); Assert.Equal("NewValue", stringout); } stringout = null; Assert.False(environment.TryGetValue("NewKey99", out stringout)); Assert.Equal(null, stringout); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { string stringout1 = null; environment.TryGetValue(null, out stringout1); }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environment.Add(null, "NewValue2")); //Invalid Key to add Assert.Throws<ArgumentException>(() => environment.Add("NewKey2", "NewValue2")); //Remove Item environment.Remove("NewKey98"); environment.Remove("NewKey98"); //2nd occurrence should not assert //Exception not thrown with null key Assert.Throws<ArgumentNullException>(() => { environment.Remove(null); }); //"Exception not thrown with null key" Assert.Throws<KeyNotFoundException>(() => environment["1bB"]); Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey2", "NewValue2"))); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("NEWKeY2", "NewValue2"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey2", "newvalue2"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("newkey2", "newvalue2"))); //Use KeyValuePair Enumerator var x = environment.GetEnumerator(); x.MoveNext(); var y1 = x.Current; Assert.Equal("NewKey NewValue", y1.Key + " " + y1.Value); x.MoveNext(); y1 = x.Current; Assert.Equal("NewKey2 NewValue2", y1.Key + " " + y1.Value); //IsReadonly Assert.False(environment.IsReadOnly); environment.Add(new KeyValuePair<string, string>("NewKey3", "NewValue3")); environment.Add(new KeyValuePair<string, string>("NewKey4", "NewValue4")); //CopyTo KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10]; environment.CopyTo(kvpa, 0); Assert.Equal("NewKey", kvpa[0].Key); Assert.Equal("NewKey3", kvpa[2].Key); environment.CopyTo(kvpa, 6); Assert.Equal("NewKey", kvpa[6].Key); //Exception not thrown with null key Assert.Throws<ArgumentOutOfRangeException>(() => { environment.CopyTo(kvpa, -1); }); //Exception not thrown with null key Assert.Throws<ArgumentException>(() => { environment.CopyTo(kvpa, 9); }); //Exception not thrown with null key Assert.Throws<ArgumentNullException>(() => { KeyValuePair<string, string>[] kvpanull = null; environment.CopyTo(kvpanull, 0); }); } [Fact] public void TestEnvironmentOfChildProcess() { const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings const string ExtraEnvVar = "TestEnvironmentOfChildProcess_SpecialStuff"; Environment.SetEnvironmentVariable(ExtraEnvVar, "\x1234" + Environment.NewLine + "\x5678"); // ensure some Unicode characters and newlines are in the output try { // Schedule a process to see what env vars it gets. Have it write out those variables // to its output stream so we can read them. Process p = CreateProcess(() => { Console.Write(string.Join(ItemSeparator, Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => Convert.ToBase64String(Encoding.UTF8.GetBytes(e.Key + "=" + e.Value))))); return SuccessExitCode; }); p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); // Parse the env vars from the child process var actualEnv = new HashSet<string>(output.Split(new[] { ItemSeparator }, StringSplitOptions.None).Select(s => Encoding.UTF8.GetString(Convert.FromBase64String(s)))); // Validate against StartInfo.Environment. var startInfoEnv = new HashSet<string>(p.StartInfo.Environment.Select(e => e.Key + "=" + e.Value)); Assert.True(startInfoEnv.SetEquals(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", startInfoEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(startInfoEnv)))); // Validate against current process. (Profilers / code coverage tools can add own environment variables // but we start child process without them. Thus the set of variables from the child process could // be a subset of variables from current process.) var envEnv = new HashSet<string>(Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value)); Assert.True(envEnv.IsSupersetOf(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", envEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(envEnv)))); } finally { Environment.SetEnvironmentVariable(ExtraEnvVar, null); } } [PlatformSpecific(TestPlatforms.Windows)] // UseShellExecute currently not supported on Windows on .NET Core [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop UseShellExecute is set to true by default but UseShellExecute=true is not supported on Core")] public void UseShellExecute_GetSetWindows_Success_Netcore() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.False(psi.UseShellExecute); // Calling the setter Assert.Throws<PlatformNotSupportedException>(() => { psi.UseShellExecute = true; }); psi.UseShellExecute = false; // Calling the getter Assert.False(psi.UseShellExecute, "UseShellExecute=true is not supported on onecore."); } [PlatformSpecific(TestPlatforms.Windows)] [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "Desktop UseShellExecute is set to true by default but UseShellExecute=true is not supported on Core")] public void UseShellExecute_GetSetWindows_Success_Netfx() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.True(psi.UseShellExecute); psi.UseShellExecute = false; Assert.False(psi.UseShellExecute); psi.UseShellExecute = true; Assert.True(psi.UseShellExecute); } [PlatformSpecific(TestPlatforms.AnyUnix)] // UseShellExecute currently not supported on Windows [Fact] public void TestUseShellExecuteProperty_SetAndGet_Unix() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.False(psi.UseShellExecute); psi.UseShellExecute = true; Assert.True(psi.UseShellExecute); psi.UseShellExecute = false; Assert.False(psi.UseShellExecute); } [PlatformSpecific(TestPlatforms.AnyUnix)] // UseShellExecute currently not supported on Windows [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void TestUseShellExecuteProperty_Redirects_NotSupported(int std) { Process p = CreateProcessLong(); p.StartInfo.UseShellExecute = true; switch (std) { case 0: p.StartInfo.RedirectStandardInput = true; break; case 1: p.StartInfo.RedirectStandardOutput = true; break; case 2: p.StartInfo.RedirectStandardError = true; break; } Assert.Throws<InvalidOperationException>(() => p.Start()); } [Fact] public void TestArgumentsProperty() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.Equal(string.Empty, psi.Arguments); psi = new ProcessStartInfo("filename", "-arg1 -arg2"); Assert.Equal("-arg1 -arg2", psi.Arguments); psi.Arguments = "-arg3 -arg4"; Assert.Equal("-arg3 -arg4", psi.Arguments); } [Theory, InlineData(true), InlineData(false)] public void TestCreateNoWindowProperty(bool value) { Process testProcess = CreateProcessLong(); try { testProcess.StartInfo.CreateNoWindow = value; testProcess.Start(); Assert.Equal(value, testProcess.StartInfo.CreateNoWindow); } finally { if (!testProcess.HasExited) testProcess.Kill(); Assert.True(testProcess.WaitForExit(WaitInMS)); } } [Fact] public void TestWorkingDirectoryProperty() { // check defaults Assert.Equal(string.Empty, _process.StartInfo.WorkingDirectory); Process p = CreateProcessLong(); p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory(); try { p.Start(); Assert.Equal(Directory.GetCurrentDirectory(), p.StartInfo.WorkingDirectory); } finally { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } [ActiveIssue(12696)] [Fact, PlatformSpecific(TestPlatforms.Windows), OuterLoop] // Uses P/Invokes, Requires admin privileges public void TestUserCredentialsPropertiesOnWindows() { string username = "test", password = "PassWord123!!"; try { Interop.NetUserAdd(username, password); } catch (Exception exc) { Console.Error.WriteLine("TestUserCredentialsPropertiesOnWindows: NetUserAdd failed: {0}", exc.Message); return; // test is irrelevant if we can't add a user } bool hasStarted = false; SafeProcessHandle handle = null; Process p = null; try { p = CreateProcessLong(); p.StartInfo.LoadUserProfile = true; p.StartInfo.UserName = username; p.StartInfo.PasswordInClearText = password; hasStarted = p.Start(); if (Interop.OpenProcessToken(p.SafeHandle, 0x8u, out handle)) { SecurityIdentifier sid; if (Interop.ProcessTokenToSid(handle, out sid)) { string actualUserName = sid.Translate(typeof(NTAccount)).ToString(); int indexOfDomain = actualUserName.IndexOf('\\'); if (indexOfDomain != -1) actualUserName = actualUserName.Substring(indexOfDomain + 1); bool isProfileLoaded = GetNamesOfUserProfiles().Any(profile => profile.Equals(username)); Assert.Equal(username, actualUserName); Assert.True(isProfileLoaded); } } } finally { IEnumerable<uint> collection = new uint[] { 0 /* NERR_Success */, 2221 /* NERR_UserNotFound */ }; Assert.Contains<uint>(Interop.NetUserDel(null, username), collection); if (handle != null) handle.Dispose(); if (hasStarted) { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } } private static List<string> GetNamesOfUserProfiles() { List<string> userNames = new List<string>(); string[] names = Registry.Users.GetSubKeyNames(); for (int i = 1; i < names.Length; i++) { try { SecurityIdentifier sid = new SecurityIdentifier(names[i]); string userName = sid.Translate(typeof(NTAccount)).ToString(); int indexofDomain = userName.IndexOf('\\'); if (indexofDomain != -1) { userName = userName.Substring(indexofDomain + 1); userNames.Add(userName); } } catch (Exception) { } } return userNames; } [Fact] public void TestEnvironmentVariables_Environment_DataRoundTrips() { ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. psi.Environment.Clear(); psi.EnvironmentVariables.Add("NewKey", "NewValue"); psi.Environment.Add("NewKey2", "NewValue2"); Assert.Equal(psi.Environment["NewKey"], psi.EnvironmentVariables["NewKey"]); Assert.Equal(psi.Environment["NewKey2"], psi.EnvironmentVariables["NewKey2"]); Assert.Equal(2, psi.EnvironmentVariables.Count); Assert.Equal(psi.Environment.Count, psi.EnvironmentVariables.Count); Assert.Throws<ArgumentException>(() => { psi.EnvironmentVariables.Add("NewKey2", "NewValue2"); }); psi.EnvironmentVariables.Add("NewKey3", "NewValue3"); Assert.Throws<ArgumentException>(() => { psi.Environment.Add("NewKey3", "NewValue3"); }); psi.EnvironmentVariables.Clear(); Assert.Equal(0, psi.Environment.Count); psi.EnvironmentVariables.Add("NewKey", "NewValue"); psi.EnvironmentVariables.Add("NewKey2", "NewValue2"); string environmentResultKey = ""; string environmentResultValue = ""; foreach(var entry in psi.Environment) { environmentResultKey += entry.Key; environmentResultValue += entry.Value; } Assert.Equal("NewKeyNewKey2", environmentResultKey); Assert.Equal("NewValueNewValue2", environmentResultValue); string envVarResultKey = ""; string envVarResultValue = ""; foreach(KeyValuePair<string, string> entry in psi.EnvironmentVariables) { envVarResultKey += entry.Key; envVarResultValue += entry.Value; } Assert.Equal(environmentResultKey, envVarResultKey); Assert.Equal(environmentResultValue, envVarResultValue); psi.EnvironmentVariables.Add("NewKey3", "NewValue3"); KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[5]; psi.Environment.CopyTo(kvpa, 0); Assert.Equal("NewKey3", kvpa[2].Key); Assert.Equal("NewValue3", kvpa[2].Value); psi.EnvironmentVariables.Remove("NewKey3"); Assert.False(psi.Environment.Contains(new KeyValuePair<string,string>("NewKey3", "NewValue3"))); } [PlatformSpecific(TestPlatforms.Windows)] // Test case is specific to Windows [Fact] public void Verbs_GetWithExeExtension_ReturnsExpected() { var psi = new ProcessStartInfo { FileName = $"{Process.GetCurrentProcess().ProcessName}.exe" }; Assert.Contains("open", psi.Verbs, StringComparer.OrdinalIgnoreCase); if (PlatformDetection.IsNotWindowsNanoServer) { Assert.Contains("runas", psi.Verbs, StringComparer.OrdinalIgnoreCase); Assert.Contains("runasuser", psi.Verbs, StringComparer.OrdinalIgnoreCase); } Assert.DoesNotContain("printto", psi.Verbs, StringComparer.OrdinalIgnoreCase); Assert.DoesNotContain("closed", psi.Verbs, StringComparer.OrdinalIgnoreCase); } [Theory] [InlineData("")] [InlineData("nofileextension")] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoExtension_ReturnsEmpty(string fileName) { var info = new ProcessStartInfo { FileName = fileName }; Assert.Empty(info.Verbs); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoRegisteredExtension_ReturnsEmpty() { var info = new ProcessStartInfo { FileName = "file.nosuchextension" }; Assert.Empty(info.Verbs); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoEmptyStringKey_ReturnsEmpty() { const string Extension = ".noemptykeyextension"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithEmptyStringValue_ReturnsEmpty() { const string Extension = ".emptystringextension"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } tempKey.Key.SetValue("", ""); var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework throws an InvalidCastException for non-string keys. See https://github.com/dotnet/corefx/issues/18187.")] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNonStringValue_ReturnsEmpty() { const string Extension = ".nonstringextension"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } tempKey.Key.SetValue("", 123); var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoShellSubKey_ReturnsEmpty() { const string Extension = ".noshellsubkey"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } tempKey.Key.SetValue("", "nosuchshell"); var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithSubkeys_ReturnsEmpty() { const string Extension = ".customregistryextension"; const string FileName = "file" + Extension; const string SubKeyValue = "customregistryextensionshell"; using (TempRegistryKey extensionKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) using (TempRegistryKey shellKey = new TempRegistryKey(Registry.ClassesRoot, SubKeyValue + "\\shell")) { if (extensionKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } extensionKey.Key.SetValue("", SubKeyValue); shellKey.Key.CreateSubKey("verb1"); shellKey.Key.CreateSubKey("NEW"); shellKey.Key.CreateSubKey("new"); shellKey.Key.CreateSubKey("verb2"); var info = new ProcessStartInfo { FileName = FileName }; Assert.Equal(new string[] { "verb1", "verb2" }, info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetUnix_ReturnsEmpty() { var info = new ProcessStartInfo(); Assert.Empty(info.Verbs); } [PlatformSpecific(TestPlatforms.AnyUnix)] // Test case is specific to Unix [Fact] public void TestEnvironmentVariablesPropertyUnix(){ ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. StringDictionary environmentVariables = psi.EnvironmentVariables; Assert.NotEqual(0, environmentVariables.Count); int CountItems = environmentVariables.Count; environmentVariables.Add("NewKey", "NewValue"); environmentVariables.Add("NewKey2", "NewValue2"); Assert.Equal(CountItems + 2, environmentVariables.Count); environmentVariables.Remove("NewKey"); Assert.Equal(CountItems + 1, environmentVariables.Count); //Exception not thrown with invalid key Assert.Throws<ArgumentException>(() => { environmentVariables.Add("NewKey2", "NewValue2"); }); Assert.False(environmentVariables.ContainsKey("NewKey")); environmentVariables.Add("newkey2", "newvalue2"); Assert.True(environmentVariables.ContainsKey("newkey2")); Assert.Equal("newvalue2", environmentVariables["newkey2"]); Assert.Equal("NewValue2", environmentVariables["NewKey2"]); environmentVariables.Clear(); Assert.Equal(0, environmentVariables.Count); environmentVariables.Add("NewKey", "newvalue"); environmentVariables.Add("newkey2", "NewValue2"); Assert.False(environmentVariables.ContainsKey("newkey")); Assert.False(environmentVariables.ContainsValue("NewValue")); string result = null; int index = 0; foreach (string e1 in environmentVariables.Values) { index++; result += e1; } Assert.Equal(2, index); Assert.Equal("newvalueNewValue2", result); result = null; index = 0; foreach (string e1 in environmentVariables.Keys) { index++; result += e1; } Assert.Equal("NewKeynewkey2", result); Assert.Equal(2, index); result = null; index = 0; foreach (KeyValuePair<string, string> e1 in environmentVariables) { index++; result += e1.Key; } Assert.Equal("NewKeynewkey2", result); Assert.Equal(2, index); //Key not found Assert.Throws<KeyNotFoundException>(() => { string stringout = environmentVariables["NewKey99"]; }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { string stringout = environmentVariables[null]; }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environmentVariables.Add(null, "NewValue2")); //Invalid Key to add Assert.Throws<ArgumentException>(() => environmentVariables.Add("newkey2", "NewValue2")); //Use KeyValuePair Enumerator var x = environmentVariables.GetEnumerator() as IEnumerator<KeyValuePair<string, string>>; x.MoveNext(); var y1 = x.Current; Assert.Equal("NewKey newvalue", y1.Key + " " + y1.Value); x.MoveNext(); y1 = x.Current; Assert.Equal("newkey2 NewValue2", y1.Key + " " + y1.Value); environmentVariables.Add("newkey3", "newvalue3"); KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10]; environmentVariables.CopyTo(kvpa, 0); Assert.Equal("NewKey", kvpa[0].Key); Assert.Equal("newkey3", kvpa[2].Key); Assert.Equal("newvalue3", kvpa[2].Value); string[] kvp = new string[10]; Assert.Throws<ArgumentException>(() => { environmentVariables.CopyTo(kvp, 6); }); environmentVariables.CopyTo(kvpa, 6); Assert.Equal("NewKey", kvpa[6].Key); Assert.Equal("newvalue", kvpa[6].Value); Assert.Throws<ArgumentOutOfRangeException>(() => { environmentVariables.CopyTo(kvpa, -1); }); Assert.Throws<ArgumentException>(() => { environmentVariables.CopyTo(kvpa, 9); }); Assert.Throws<ArgumentNullException>(() => { KeyValuePair<string, string>[] kvpanull = null; environmentVariables.CopyTo(kvpanull, 0); }); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("domain")] [PlatformSpecific(TestPlatforms.Windows)] public void Domain_SetWindows_GetReturnsExpected(string domain) { var info = new ProcessStartInfo { Domain = domain }; Assert.Equal(domain ?? string.Empty, info.Domain); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void Domain_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.Domain); Assert.Throws<PlatformNotSupportedException>(() => info.Domain = "domain"); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("filename")] public void FileName_Set_GetReturnsExpected(string fileName) { var info = new ProcessStartInfo { FileName = fileName }; Assert.Equal(fileName ?? string.Empty, info.FileName); } [Theory] [InlineData(true)] [InlineData(false)] [PlatformSpecific(TestPlatforms.Windows)] public void LoadUserProfile_SetWindows_GetReturnsExpected(bool loadUserProfile) { var info = new ProcessStartInfo { LoadUserProfile = loadUserProfile }; Assert.Equal(loadUserProfile, info.LoadUserProfile); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void LoadUserProfile_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile); Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile = false); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("passwordInClearText")] [PlatformSpecific(TestPlatforms.Windows)] public void PasswordInClearText_SetWindows_GetReturnsExpected(string passwordInClearText) { var info = new ProcessStartInfo { PasswordInClearText = passwordInClearText }; Assert.Equal(passwordInClearText, info.PasswordInClearText); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void PasswordInClearText_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText); Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText = "passwordInClearText"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Password_SetWindows_GetReturnsExpected() { using (SecureString password = new SecureString()) { password.AppendChar('a'); var info = new ProcessStartInfo { Password = password }; Assert.Equal(password, info.Password); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void Password_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.Password); Assert.Throws<PlatformNotSupportedException>(() => info.Password = new SecureString()); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("domain")] [PlatformSpecific(TestPlatforms.Windows)] public void UserName_SetWindows_GetReturnsExpected(string userName) { var info = new ProcessStartInfo { UserName = userName }; Assert.Equal(userName ?? string.Empty, info.UserName); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void UserName_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.UserName); Assert.Throws<PlatformNotSupportedException>(() => info.UserName = "username"); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("verb")] public void Verb_Set_GetReturnsExpected(string verb) { var info = new ProcessStartInfo { Verb = verb }; Assert.Equal(verb ?? string.Empty, info.Verb); } [Theory] [InlineData(ProcessWindowStyle.Normal - 1)] [InlineData(ProcessWindowStyle.Maximized + 1)] public void WindowStyle_SetNoSuchWindowStyle_ThrowsInvalidEnumArgumentException(ProcessWindowStyle style) { var info = new ProcessStartInfo(); Assert.Throws<InvalidEnumArgumentException>(() => info.WindowStyle = style); } [Theory] [InlineData(ProcessWindowStyle.Hidden)] [InlineData(ProcessWindowStyle.Maximized)] [InlineData(ProcessWindowStyle.Minimized)] [InlineData(ProcessWindowStyle.Normal)] public void WindowStyle_Set_GetReturnsExpected(ProcessWindowStyle style) { var info = new ProcessStartInfo { WindowStyle = style }; Assert.Equal(style, info.WindowStyle); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("workingdirectory")] public void WorkingDirectory_Set_GetReturnsExpected(string workingDirectory) { var info = new ProcessStartInfo { WorkingDirectory = workingDirectory }; Assert.Equal(workingDirectory ?? string.Empty, info.WorkingDirectory); } } }
/* * This file is part of AceQL C# Client SDK. * AceQL C# Client SDK: Remote SQL access over HTTP with AceQL HTTP. * Copyright (C) 2020, KawanSoft SAS * (http://www.kawansoft.com). 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 AceQL.Client.Src.Api.Util; using PCLStorage; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace AceQL.Client.Api.Util { /// <summary> /// Class AceQLCommandUtil. /// </summary> internal class AceQLCommandUtil { public static readonly string[] PARM_SEPARATORS = { "(", ")", ";", " ", "+", "-", "/", "*", "=", "\'", "\"", "?", "!", ":", "#", "&", "-", "<", ">", "{", "}", "[", "]", "|", "%", "," }; internal static readonly bool DEBUG; /// <summary> /// The command text /// </summary> private string cmdText; /// <summary> /// The parameters /// </summary> private readonly AceQLParameterCollection Parameters; /// <summary> /// The BLOB ids /// </summary> private readonly List<String> blobIds = new List<string>(); /// <summary> /// The BLOB file streams /// </summary> private readonly List<Stream> blobStreams = new List<Stream>(); private List<long> blobLengths = new List<long>(); /// <summary> /// Gets the BLOB ids. /// </summary> /// <value>The BLOB ids.</value> internal List<string> BlobIds { get { return blobIds; } } /// <summary> /// Gets the BLOB streams. /// </summary> /// <value>The BLOB streams.</value> internal List<Stream> BlobStreams { get { return blobStreams; } } internal List<long> BlobLengths { get { return blobLengths; } set { blobLengths = value; } } /// <summary> /// Initializes a new instance of the <see cref="AceQLCommandUtil"/> class. /// </summary> /// <param name="cmdText">The command text.</param> /// <param name="Parameters">The parameters.</param> /// <exception cref="System.ArgumentNullException"> /// cmdText is null! /// or /// Parameters is null! /// </exception> internal AceQLCommandUtil(String cmdText, AceQLParameterCollection Parameters) { this.cmdText = cmdText ?? throw new ArgumentNullException("cmdText is null!"); this.Parameters = Parameters ?? throw new ArgumentNullException("Parameters is null!"); } /// <summary> /// Gets the prepared statement parameters. /// </summary> /// <returns>The Parameters List</returns> internal Dictionary<string, string> GetPreparedStatementParameters() { HashSet<String> theParamsSetInSqlCommand = GetValidParamsInSqlCommand(); CheckAllParametersExistInSqlCommand(theParamsSetInSqlCommand, this.Parameters); Dictionary<string, string> parametersList = new Dictionary<string, string>(); // For each parameter get the dbType int paramIndex = 0; foreach (var parameterName in theParamsSetInSqlCommand) { AceQLParameter aceQLParameter = this.Parameters.GetAceQLParameter(parameterName); paramIndex++; Debug(""); Debug("parameterName : " + parameterName); Debug("aceQLParameter.Value: " + aceQLParameter.Value + ":"); Debug("paramIndex : " + paramIndex); AceQLNullType aceQLNullType = aceQLParameter.SqlNullType; Object ParmValue = aceQLParameter.Value; //Reconvert SqlType original Java value by diving per 10000 and multiplying per -1: int sqlType = (int)aceQLNullType; sqlType = sqlType / (int)AceQLNullType.CHAR; // For OUT parameters that may be null value if (ParmValue == null) { ParmValue = "NULL"; } if (aceQLParameter.IsNullValue) { String paramType = "TYPE_NULL" + sqlType; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, "NULL"); } else if (ParmValue is Stream) { // All streams are blob for now // This will be enhanced in future version String blobId = BuildUniqueBlobId(); blobIds.Add(blobId); blobStreams.Add((Stream)ParmValue); blobLengths.Add(aceQLParameter.BlobLength); String paramType = "BLOB"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, blobId); } else if (ParmValue is string || ParmValue is String) { String paramType = "VARCHAR"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, ParmValue.ToString()); } else if (ParmValue is long) { String paramType = "BIGINT"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, ParmValue.ToString()); } else if (ParmValue is int) { String paramType = "INTEGER"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, ParmValue.ToString()); } else if (ParmValue is short) { String paramType = "TINYINT"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, ParmValue.ToString()); } else if (ParmValue is bool || ParmValue is Boolean) { String paramType = "BIT"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, ParmValue.ToString()); } else if (ParmValue is float) { String paramType = "REAL"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, ParmValue.ToString().Replace(",", ".")); } else if (ParmValue is double || ParmValue is Double) { String paramType = "DOUBLE_PRECISION"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, ParmValue.ToString().Replace(",", ".")); } else if (ParmValue is DateTime) { String paramType = "TIMESTAMP"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, ConvertToTimestamp((DateTime)ParmValue)); } else if (ParmValue is TimeSpan) { String paramType = "TIME"; parametersList.Add("param_type_" + paramIndex, paramType); parametersList.Add("param_value_" + paramIndex, ConvertToTimestamp((DateTime)ParmValue)); } else { throw new AceQLException("Type of value is not supported. Value: " + ParmValue + " / Type: " + ParmValue.GetType(), 2, (Exception)null, HttpStatusCode.OK); } if (!aceQLParameter.IsNullValue && !(ParmValue is Stream)) { if (aceQLParameter.Direction == Api.ParameterDirection.InputOutput) { parametersList.Add("param_direction_" + paramIndex, "inout"); parametersList.Add("out_param_name_" + paramIndex, aceQLParameter.ParameterName); } else if (aceQLParameter.Direction == Api.ParameterDirection.Output) { parametersList.Add("param_direction_" + paramIndex, "out"); parametersList.Add("out_param_name_" + paramIndex, aceQLParameter.ParameterName); } else { // Defaults to "in" on server } } } return parametersList; } /// <summary> /// Builds a unique Blob ID. /// </summary> /// <returns>a unique Blob ID.</returns> internal static string BuildUniqueBlobId() { String blobId = Guid.NewGuid().ToString() + ".blob"; return blobId; } /// <summary> /// Returns the file corresponding to the trace file. Value is: AceQLPclFolder/trace.txt. /// </summary> /// <returns>the file corresponding to the trace file.</returns> internal static async Task<IFile> GetTraceFileAsync() { IFolder rootFolder = FileSystem.Current.LocalStorage; IFolder folder = await rootFolder.CreateFolderAsync(Parms.ACEQL_PCL_FOLDER, CreationCollisionOption.OpenIfExists).ConfigureAwait(false); //\AppData\Local\KawanSoft\AceQL.Client.Samples\3.0.0.0\AceQLPclFolder string pathTraceTxt = "Trace_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + "_" + Guid.NewGuid().ToString() + ".txt"; IFile file = await folder.CreateFileAsync(pathTraceTxt, CreationCollisionOption.OpenIfExists).ConfigureAwait(false); return file; } /// <summary> /// Checks all parameters exist in SQL command. Will throw an Exception if a parameter is missing. /// </summary> /// <param name="theParamsSetInSqlCommand">The parameters set in SQL command.</param> /// <param name="parameters">The parameters.</param> private static void CheckAllParametersExistInSqlCommand(HashSet<string> theParamsSetInSqlCommand, AceQLParameterCollection parameters) { HashSet<string> parameterNames = new HashSet<string>(); for (int i = 0; i < parameters.Count; i++) { String theParm = parameters[i].ToString(); parameterNames.Add(theParm); } List<string> theParamsListInSqlCommand = theParamsSetInSqlCommand.ToList(); foreach (string theParamInSqlCommand in theParamsListInSqlCommand) { if (!parameterNames.Contains(theParamInSqlCommand)) { throw new ArgumentException("Missing parameter value for parameter name: " + theParamInSqlCommand); } } } /// <summary> /// Gets the valid parameters. /// </summary> /// <returns>HashSet&lt;System.String&gt;.</returns> private HashSet<string> GetValidParamsInSqlCommand() { HashSet<string> theParamsSet = new HashSet<string>(); String[] splits = cmdText.Split(PARM_SEPARATORS, StringSplitOptions.RemoveEmptyEntries); foreach (string splitted in splits) { if (!splitted.StartsWith("@")) { continue; } if (theParamsSet.Contains(splitted.Trim())) { throw new ArgumentException("This parameter is duplicate in SQL command: " + splitted.Trim()); } theParamsSet.Add(splitted.Trim()); } return theParamsSet; } /// <summary> /// Replaces the parms with question marks. /// </summary> /// <returns>System.String.</returns> internal string ReplaceParmsWithQuestionMarks() { for (int i = 0; i < Parameters.Count; i++) { String theParm = Parameters[i].ToString(); cmdText = cmdText.Replace(theParm, "?"); } return cmdText; } /// <summary> /// Dates the time to unix timestamp. /// </summary> /// <param name="dateTime">The UNIX date time in milliseconds</param> /// <returns>String.</returns> internal static String ConvertToTimestamp(DateTime dateTime) { double theDouble = (TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.Utc) - new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalMilliseconds; String theTimeString = theDouble.ToString(CultureInfo.InvariantCulture); // Remove "." or ',' depending on Locale: theTimeString = StringUtils.SubstringBefore(theTimeString, ","); theTimeString = StringUtils.SubstringBefore(theTimeString, "."); return theTimeString; } private static void Debug(string s) { if (DEBUG) { ConsoleEmul.WriteLine(DateTime.Now + " " + s); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview { public class PreviewWorkspaceTests { [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationDefault() { using (var previewWorkspace = new PreviewWorkspace()) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithExplicitHostServices() { var assembly = typeof(ISolutionCrawlerRegistrationService).Assembly; using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly)))) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithSolution() { using (var custom = new AdhocWorkspace()) using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution)) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewAddRemoveProject() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id); Assert.True(previewWorkspace.TryApplyChanges(newSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewProjectChanges() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var addedSolution = previewWorkspace.CurrentSolution.Projects.First() .AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument("document", "").Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(addedSolution)); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); var text = "class C {}"; var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(changedSolution)); Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text); var removedSolution = previewWorkspace.CurrentSolution.Projects.First() .RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0]) .RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution; Assert.True(previewWorkspace.TryApplyChanges(removedSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); } } [WorkItem(923121)] [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewOpenCloseFile() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); var document = project.AddDocument("document", ""); Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution)); previewWorkspace.OpenDocument(document.Id); Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count()); Assert.True(previewWorkspace.IsDocumentOpen(document.Id)); previewWorkspace.CloseDocument(document.Id); Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count()); Assert.False(previewWorkspace.IsDocumentOpen(document.Id)); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewServices() { using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>(); Assert.True(service is PreviewSolutionCrawlerRegistrationService); var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>(); Assert.NotNull(persistentService); var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution); Assert.True(storage is NoOpPersistentStorage); } } [WorkItem(923196)] [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewDiagnostic() { var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource; var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var solution = previewWorkspace.CurrentSolution .AddProject("project", "project.dll", LanguageNames.CSharp) .AddDocument("document", "class { }") .Project .Solution; Assert.True(previewWorkspace.TryApplyChanges(solution)); previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]); previewWorkspace.EnableDiagnostic(); // wait 20 seconds taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } var args = taskSource.Task.Result; Assert.True(args.Diagnostics.Length > 0); } } [Fact] public void TestPreviewDiagnosticTagger() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }")) using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution)) { //// preview workspace and owner of the solution now share solution and its underlying text buffer var hostDocument = workspace.Projects.First().Documents.First(); //// enable preview diagnostics previewWorkspace.EnableDiagnostic(); var spans = SquiggleUtilities.GetErrorSpans(workspace); Assert.Equal(1, spans.Count); } } [Fact] public void TestPreviewDiagnosticTaggerInPreviewPane() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }")) { // set up listener to wait until diagnostic finish running var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService; // no easy way to setup waiter. kind of hacky way to setup waiter var source = new CancellationTokenSource(); var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => { source.Cancel(); source = new CancellationTokenSource(); var cancellationToken = source.Token; Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); }; var hostDocument = workspace.Projects.First().Documents.First(); // make a change to remove squiggle var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id); var oldText = oldDocument.GetTextAsync().Result; var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }"))); // create a diff view var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>(); var diffView = (IWpfDifferenceViewer)previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None).PumpingWaitResult(); var foregroundService = workspace.GetService<IForegroundNotificationService>(); var optionsService = workspace.Services.GetService<IOptionService>(); var waiter = new ErrorSquiggleWaiter(); var listeners = AsynchronousOperationListener.CreateListeners(FeatureAttribute.ErrorSquiggles, waiter); // set up tagger for both buffers var leftBuffer = diffView.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var leftProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners); var leftTagger = leftProvider.CreateTagger<IErrorTag>(leftBuffer); using (var leftDisposable = leftTagger as IDisposable) { var rightBuffer = diffView.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var rightProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners); var rightTagger = rightProvider.CreateTagger<IErrorTag>(rightBuffer); using (var rightDisposable = rightTagger as IDisposable) { // wait up to 20 seconds for diagnostics taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } // wait taggers waiter.CreateWaitTask().PumpingWait(); // check left buffer var leftSnapshot = leftBuffer.CurrentSnapshot; var leftSpans = leftTagger.GetTags(leftSnapshot.GetSnapshotSpanCollection()).ToList(); Assert.Equal(1, leftSpans.Count); // check right buffer var rightSnapshot = rightBuffer.CurrentSnapshot; var rightSpans = rightTagger.GetTags(rightSnapshot.GetSnapshotSpanCollection()).ToList(); Assert.Equal(0, rightSpans.Count); } } } } private class ErrorSquiggleWaiter : AsynchronousOperationListener { } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Security.Cryptography { public abstract partial class Aes : System.Security.Cryptography.SymmetricAlgorithm { protected Aes() { } public static new System.Security.Cryptography.Aes Create() { throw null; } public static new System.Security.Cryptography.Aes Create(string algorithmName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class AesManaged : System.Security.Cryptography.Aes { public AesManaged() { } public override int BlockSize { get { throw null; } set { } } public override int FeedbackSize { get { throw null; } set { } } public override byte[] IV { get { throw null; } set { } } public override byte[] Key { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override void GenerateIV() { } public override void GenerateKey() { } } public abstract partial class AsymmetricKeyExchangeDeformatter { protected AsymmetricKeyExchangeDeformatter() { } public abstract string Parameters { get; set; } public abstract byte[] DecryptKeyExchange(byte[] rgb); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); } public abstract partial class AsymmetricKeyExchangeFormatter { protected AsymmetricKeyExchangeFormatter() { } public abstract string Parameters { get; } public abstract byte[] CreateKeyExchange(byte[] data); public abstract byte[] CreateKeyExchange(byte[] data, System.Type symAlgType); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); } public abstract partial class AsymmetricSignatureDeformatter { protected AsymmetricSignatureDeformatter() { } public abstract void SetHashAlgorithm(string strName); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature); public virtual bool VerifySignature(System.Security.Cryptography.HashAlgorithm hash, byte[] rgbSignature) { throw null; } } public abstract partial class AsymmetricSignatureFormatter { protected AsymmetricSignatureFormatter() { } public abstract byte[] CreateSignature(byte[] rgbHash); public virtual byte[] CreateSignature(System.Security.Cryptography.HashAlgorithm hash) { throw null; } public abstract void SetHashAlgorithm(string strName); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); } public partial class CryptoConfig { public CryptoConfig() { } public static bool AllowOnlyFipsAlgorithms { get { throw null; } } public static void AddAlgorithm(System.Type algorithm, params string[] names) { } public static void AddOID(string oid, params string[] names) { } public static object CreateFromName(string name) { throw null; } public static object CreateFromName(string name, params object[] args) { throw null; } public static byte[] EncodeOID(string str) { throw null; } public static string MapNameToOID(string name) { throw null; } } public abstract partial class DeriveBytes : System.IDisposable { protected DeriveBytes() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract byte[] GetBytes(int cb); public abstract void Reset(); } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public abstract partial class DES : System.Security.Cryptography.SymmetricAlgorithm { protected DES() { } public override byte[] Key { get { throw null; } set { } } public static new System.Security.Cryptography.DES Create() { throw null; } public static new System.Security.Cryptography.DES Create(string algName) { throw null; } public static bool IsSemiWeakKey(byte[] rgbKey) { throw null; } public static bool IsWeakKey(byte[] rgbKey) { throw null; } } public abstract partial class DSA : System.Security.Cryptography.AsymmetricAlgorithm { protected DSA() { } public static new System.Security.Cryptography.DSA Create() { throw null; } public static System.Security.Cryptography.DSA Create(int keySizeInBits) { throw null; } public static new System.Security.Cryptography.DSA Create(string algName) { throw null; } public static System.Security.Cryptography.DSA Create(System.Security.Cryptography.DSAParameters parameters) { throw null; } public abstract byte[] CreateSignature(byte[] rgbHash); public abstract System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters); public override void FromXmlString(string xmlString) { } protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract void ImportParameters(System.Security.Cryptography.DSAParameters parameters); public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public override string ToXmlString(bool includePrivateParameters) { throw null; } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature); } public partial struct DSAParameters { public int Counter; public byte[] G; public byte[] J; public byte[] P; public byte[] Q; public byte[] Seed; public byte[] X; public byte[] Y; } public partial class DSASignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter { public DSASignatureDeformatter() { } public DSASignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; } } public partial class DSASignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter { public DSASignatureFormatter() { } public DSASignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override byte[] CreateSignature(byte[] rgbHash) { throw null; } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial struct ECCurve { private object _dummy; public byte[] A; public byte[] B; public byte[] Cofactor; public System.Security.Cryptography.ECCurve.ECCurveType CurveType; public System.Security.Cryptography.ECPoint G; public System.Nullable<System.Security.Cryptography.HashAlgorithmName> Hash; public byte[] Order; public byte[] Polynomial; public byte[] Prime; public byte[] Seed; public bool IsCharacteristic2 { get { throw null; } } public bool IsExplicit { get { throw null; } } public bool IsNamed { get { throw null; } } public bool IsPrime { get { throw null; } } public System.Security.Cryptography.Oid Oid { get { throw null; } } public static System.Security.Cryptography.ECCurve CreateFromFriendlyName(string oidFriendlyName) { throw null; } public static System.Security.Cryptography.ECCurve CreateFromOid(System.Security.Cryptography.Oid curveOid) { throw null; } public static System.Security.Cryptography.ECCurve CreateFromValue(string oidValue) { throw null; } public void Validate() { } public enum ECCurveType { Characteristic2 = 4, Implicit = 0, Named = 5, PrimeMontgomery = 3, PrimeShortWeierstrass = 1, PrimeTwistedEdwards = 2, } public static partial class NamedCurves { public static System.Security.Cryptography.ECCurve brainpoolP160r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP160t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP192r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP192t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP224r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP224t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP256r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP256t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP320r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP320t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP384r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP384t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP512r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP512t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve nistP256 { get { throw null; } } public static System.Security.Cryptography.ECCurve nistP384 { get { throw null; } } public static System.Security.Cryptography.ECCurve nistP521 { get { throw null; } } } } public abstract partial class ECDiffieHellman : System.Security.Cryptography.AsymmetricAlgorithm { protected ECDiffieHellman() { } public override string KeyExchangeAlgorithm { get { throw null; } } public abstract System.Security.Cryptography.ECDiffieHellmanPublicKey PublicKey { get; } public override string SignatureAlgorithm { get { throw null; } } public static new System.Security.Cryptography.ECDiffieHellman Create() { throw null; } public static System.Security.Cryptography.ECDiffieHellman Create(System.Security.Cryptography.ECCurve curve) { throw null; } public static System.Security.Cryptography.ECDiffieHellman Create(System.Security.Cryptography.ECParameters parameters) { throw null; } public static new System.Security.Cryptography.ECDiffieHellman Create(string algorithm) { throw null; } public byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] secretPrepend, byte[] secretAppend) { throw null; } public byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] hmacKey) { throw null; } public virtual byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend) { throw null; } public virtual byte[] DeriveKeyMaterial(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey) { throw null; } public virtual byte[] DeriveKeyTls(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; } public override void FromXmlString(string xmlString) { } public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { } public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { } public override string ToXmlString(bool includePrivateParameters) { throw null; } } public abstract partial class ECDiffieHellmanPublicKey : System.IDisposable { protected ECDiffieHellmanPublicKey() { } protected ECDiffieHellmanPublicKey(byte[] keyBlob) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual byte[] ToByteArray() { throw null; } public virtual string ToXmlString() { throw null; } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters() { throw null; } public virtual System.Security.Cryptography.ECParameters ExportParameters() { throw null; } } public abstract partial class ECDsa : System.Security.Cryptography.AsymmetricAlgorithm { protected ECDsa() { } public override string KeyExchangeAlgorithm { get { throw null; } } public override string SignatureAlgorithm { get { throw null; } } public static new System.Security.Cryptography.ECDsa Create() { throw null; } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECCurve curve) { throw null; } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECParameters parameters) { throw null; } public static new System.Security.Cryptography.ECDsa Create(string algorithm) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; } public override void FromXmlString(string xmlString) { } public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { } protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { } public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract byte[] SignHash(byte[] hash); public override string ToXmlString(bool includePrivateParameters) { throw null; } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract bool VerifyHash(byte[] hash, byte[] signature); } public partial struct ECParameters { public System.Security.Cryptography.ECCurve Curve; public byte[] D; public System.Security.Cryptography.ECPoint Q; public void Validate() { } } public partial struct ECPoint { public byte[] X; public byte[] Y; } public partial class HMACMD5 : System.Security.Cryptography.HMAC { public HMACMD5() { } public HMACMD5(byte[] key) { } public override byte[] Key { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA1 : System.Security.Cryptography.HMAC { public HMACSHA1() { } public HMACSHA1(byte[] key) { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public HMACSHA1(byte[] key, bool useManagedSha1) { } public override byte[] Key { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA256 : System.Security.Cryptography.HMAC { public HMACSHA256() { } public HMACSHA256(byte[] key) { } public override byte[] Key { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA384 : System.Security.Cryptography.HMAC { public HMACSHA384() { } public HMACSHA384(byte[] key) { } public override byte[] Key { get { throw null; } set { } } public bool ProduceLegacyHmacValues { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA512 : System.Security.Cryptography.HMAC { public HMACSHA512() { } public HMACSHA512(byte[] key) { } public override byte[] Key { get { throw null; } set { } } public bool ProduceLegacyHmacValues { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public sealed partial class IncrementalHash : System.IDisposable { internal IncrementalHash() { } public System.Security.Cryptography.HashAlgorithmName AlgorithmName { get { throw null; } } public void AppendData(byte[] data) { } public void AppendData(byte[] data, int offset, int count) { } public static System.Security.Cryptography.IncrementalHash CreateHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public static System.Security.Cryptography.IncrementalHash CreateHMAC(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] key) { throw null; } public void Dispose() { } public byte[] GetHashAndReset() { throw null; } } public abstract partial class MaskGenerationMethod { public abstract byte[] GenerateMask(byte[] rgbSeed, int cbReturn); } public abstract partial class MD5 : System.Security.Cryptography.HashAlgorithm { protected MD5() { } public static new System.Security.Cryptography.MD5 Create() { throw null; } public static new System.Security.Cryptography.MD5 Create(string algName) { throw null; } } public partial class PKCS1MaskGenerationMethod : System.Security.Cryptography.MaskGenerationMethod { public PKCS1MaskGenerationMethod() { } public string HashName { get { throw null; } set { } } public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn) { throw null; } } public abstract partial class RandomNumberGenerator : System.IDisposable { protected RandomNumberGenerator() { } public static System.Security.Cryptography.RandomNumberGenerator Create() { throw null; } public static System.Security.Cryptography.RandomNumberGenerator Create(string rngName) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract void GetBytes(byte[] data); public virtual void GetBytes(byte[] data, int offset, int count) { } public virtual void GetNonZeroBytes(byte[] data) { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public abstract partial class RC2 : System.Security.Cryptography.SymmetricAlgorithm { protected int EffectiveKeySizeValue; protected RC2() { } public virtual int EffectiveKeySize { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public static new System.Security.Cryptography.RC2 Create() { throw null; } public static new System.Security.Cryptography.RC2 Create(string AlgName) { throw null; } } public partial class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes { public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public Rfc2898DeriveBytes(string password, byte[] salt) { } public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(string password, byte[] salt, int iterations, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public Rfc2898DeriveBytes(string password, int saltSize) { } public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { } public Rfc2898DeriveBytes(string password, int saltSize, int iterations, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public System.Security.Cryptography.HashAlgorithmName HashAlgorithm { get { throw null; } } public int IterationCount { get { throw null; } set { } } public byte[] Salt { get { throw null; } set { } } public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override byte[] GetBytes(int cb) { throw null; } public override void Reset() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public abstract partial class Rijndael : System.Security.Cryptography.SymmetricAlgorithm { protected Rijndael() { } public static new System.Security.Cryptography.Rijndael Create() { throw null; } public static new System.Security.Cryptography.Rijndael Create(string algName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class RijndaelManaged : System.Security.Cryptography.Rijndael { public RijndaelManaged() { } public override int BlockSize { get { throw null; } set { } } public override byte[] IV { get { throw null; } set { } } public override byte[] Key { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override void GenerateIV() { } public override void GenerateKey() { } } public abstract partial class RSA : System.Security.Cryptography.AsymmetricAlgorithm { protected RSA() { } public override string KeyExchangeAlgorithm { get { throw null; } } public override string SignatureAlgorithm { get { throw null; } } public static new System.Security.Cryptography.RSA Create() { throw null; } public static System.Security.Cryptography.RSA Create(int keySizeInBits) { throw null; } public static System.Security.Cryptography.RSA Create(System.Security.Cryptography.RSAParameters parameters) { throw null; } public static new System.Security.Cryptography.RSA Create(string algName) { throw null; } public virtual byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; } public virtual byte[] DecryptValue(byte[] rgb) { throw null; } public virtual byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; } public virtual byte[] EncryptValue(byte[] rgb) { throw null; } public abstract System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters); public override void FromXmlString(string xmlString) { } protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract void ImportParameters(System.Security.Cryptography.RSAParameters parameters); public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public override string ToXmlString(bool includePrivateParameters) { throw null; } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } } public sealed partial class RSAEncryptionPadding : System.IEquatable<System.Security.Cryptography.RSAEncryptionPadding> { internal RSAEncryptionPadding() { } public System.Security.Cryptography.RSAEncryptionPaddingMode Mode { get { throw null; } } public System.Security.Cryptography.HashAlgorithmName OaepHashAlgorithm { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA1 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA256 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA384 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA512 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding Pkcs1 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding CreateOaep(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public override bool Equals(object obj) { throw null; } public bool Equals(System.Security.Cryptography.RSAEncryptionPadding other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; } public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; } public override string ToString() { throw null; } } public enum RSAEncryptionPaddingMode { Oaep = 1, Pkcs1 = 0, } public partial class RSAOAEPKeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter { public RSAOAEPKeyExchangeDeformatter() { } public RSAOAEPKeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override string Parameters { get { throw null; } set { } } public override byte[] DecryptKeyExchange(byte[] rgbData) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial class RSAOAEPKeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter { public RSAOAEPKeyExchangeFormatter() { } public RSAOAEPKeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public byte[] Parameter { get { throw null; } set { } } public override string Parameters { get { throw null; } } public System.Security.Cryptography.RandomNumberGenerator Rng { get { throw null; } set { } } public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; } public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial struct RSAParameters { public byte[] D; public byte[] DP; public byte[] DQ; public byte[] Exponent; public byte[] InverseQ; public byte[] Modulus; public byte[] P; public byte[] Q; } public partial class RSAPKCS1KeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter { public RSAPKCS1KeyExchangeDeformatter() { } public RSAPKCS1KeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override string Parameters { get { throw null; } set { } } public System.Security.Cryptography.RandomNumberGenerator RNG { get { throw null; } set { } } public override byte[] DecryptKeyExchange(byte[] rgbIn) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial class RSAPKCS1KeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter { public RSAPKCS1KeyExchangeFormatter() { } public RSAPKCS1KeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override string Parameters { get { throw null; } } public System.Security.Cryptography.RandomNumberGenerator Rng { get { throw null; } set { } } public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; } public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial class RSAPKCS1SignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter { public RSAPKCS1SignatureDeformatter() { } public RSAPKCS1SignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; } } public partial class RSAPKCS1SignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter { public RSAPKCS1SignatureFormatter() { } public RSAPKCS1SignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override byte[] CreateSignature(byte[] rgbHash) { throw null; } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public sealed partial class RSASignaturePadding : System.IEquatable<System.Security.Cryptography.RSASignaturePadding> { internal RSASignaturePadding() { } public System.Security.Cryptography.RSASignaturePaddingMode Mode { get { throw null; } } public static System.Security.Cryptography.RSASignaturePadding Pkcs1 { get { throw null; } } public static System.Security.Cryptography.RSASignaturePadding Pss { get { throw null; } } public override bool Equals(object obj) { throw null; } public bool Equals(System.Security.Cryptography.RSASignaturePadding other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; } public static bool operator !=(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; } public override string ToString() { throw null; } } public enum RSASignaturePaddingMode { Pkcs1 = 0, Pss = 1, } public abstract partial class SHA1 : System.Security.Cryptography.HashAlgorithm { protected SHA1() { } public static new System.Security.Cryptography.SHA1 Create() { throw null; } public static new System.Security.Cryptography.SHA1 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA1Managed : System.Security.Cryptography.SHA1 { public SHA1Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class SHA256 : System.Security.Cryptography.HashAlgorithm { protected SHA256() { } public static new System.Security.Cryptography.SHA256 Create() { throw null; } public static new System.Security.Cryptography.SHA256 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA256Managed : System.Security.Cryptography.SHA256 { public SHA256Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class SHA384 : System.Security.Cryptography.HashAlgorithm { protected SHA384() { } public static new System.Security.Cryptography.SHA384 Create() { throw null; } public static new System.Security.Cryptography.SHA384 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA384Managed : System.Security.Cryptography.SHA384 { public SHA384Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class SHA512 : System.Security.Cryptography.HashAlgorithm { protected SHA512() { } public static new System.Security.Cryptography.SHA512 Create() { throw null; } public static new System.Security.Cryptography.SHA512 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA512Managed : System.Security.Cryptography.SHA512 { public SHA512Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class SignatureDescription { public SignatureDescription() { } public SignatureDescription(System.Security.SecurityElement el) { } public string DeformatterAlgorithm { get { throw null; } set { } } public string DigestAlgorithm { get { throw null; } set { } } public string FormatterAlgorithm { get { throw null; } set { } } public string KeyAlgorithm { get { throw null; } set { } } public virtual System.Security.Cryptography.AsymmetricSignatureDeformatter CreateDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; } public virtual System.Security.Cryptography.HashAlgorithm CreateDigest() { throw null; } public virtual System.Security.Cryptography.AsymmetricSignatureFormatter CreateFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; } } public abstract partial class TripleDES : System.Security.Cryptography.SymmetricAlgorithm { protected TripleDES() { } public override byte[] Key { get { throw null; } set { } } public static new System.Security.Cryptography.TripleDES Create() { throw null; } public static new System.Security.Cryptography.TripleDES Create(string str) { throw null; } public static bool IsWeakKey(byte[] rgbKey) { throw null; } } }
using System; using System.Collections.Generic; /* * Copyright 2007 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.qrcode { using BarcodeFormat = com.google.zxing.BarcodeFormat; using BinaryBitmap = com.google.zxing.BinaryBitmap; using ChecksumException = com.google.zxing.ChecksumException; using DecodeHintType = com.google.zxing.DecodeHintType; using FormatException = com.google.zxing.FormatException; using NotFoundException = com.google.zxing.NotFoundException; using Reader = com.google.zxing.Reader; using Result = com.google.zxing.Result; using ResultMetadataType = com.google.zxing.ResultMetadataType; using ResultPoint = com.google.zxing.ResultPoint; using BitMatrix = com.google.zxing.common.BitMatrix; using DecoderResult = com.google.zxing.common.DecoderResult; using DetectorResult = com.google.zxing.common.DetectorResult; using Decoder = com.google.zxing.qrcode.decoder.Decoder; using Detector = com.google.zxing.qrcode.detector.Detector; /// <summary> /// This implementation can detect and decode QR Codes in an image. /// /// @author Sean Owen /// </summary> public class QRCodeReader : com.google.zxing.Reader { private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0]; private readonly Decoder decoder = new Decoder(); protected internal virtual Decoder Decoder { get { return decoder; } } /// <summary> /// Locates and decodes a QR code in an image. /// </summary> /// <returns> a String representing the content encoded by the QR code </returns> /// <exception cref="NotFoundException"> if a QR code cannot be found </exception> /// <exception cref="FormatException"> if a QR code cannot be decoded </exception> /// <exception cref="ChecksumException"> if error correction fails </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException public Result decode(BinaryBitmap image) { return decode(image, null); } //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints) { DecoderResult decoderResult; ResultPoint[] points; if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) { BitMatrix bits = extractPureBits(image.BlackMatrix); decoderResult = decoder.decode(bits, hints); points = NO_POINTS; } else { DetectorResult detectorResult = (new Detector(image.BlackMatrix)).detect(hints); decoderResult = decoder.decode(detectorResult.Bits, hints); points = detectorResult.Points; } Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE); IList<sbyte[]> byteSegments = decoderResult.ByteSegments; if (byteSegments != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); } string ecLevel = decoderResult.ECLevel; if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } return result; } public void reset() { // do nothing } /// <summary> /// This method detects a code in a "pure" image -- that is, pure monochrome image /// which contains only an unrotated, unskewed, image of a code, with some white border /// around it. This is a specialized method that works exceptionally fast in this special /// case. /// </summary> /// <seealso cref= com.google.zxing.pdf417.PDF417Reader#extractPureBits(BitMatrix) </seealso> /// <seealso cref= com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix) </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static com.google.zxing.common.BitMatrix extractPureBits(com.google.zxing.common.BitMatrix image) throws com.google.zxing.NotFoundException private static BitMatrix extractPureBits(BitMatrix image) { int[] leftTopBlack = image.TopLeftOnBit; int[] rightBottomBlack = image.BottomRightOnBit; if (leftTopBlack == null || rightBottomBlack == null) { throw NotFoundException.NotFoundInstance; } float moduleSize = getModuleSize(leftTopBlack, image); int top = leftTopBlack[1]; int bottom = rightBottomBlack[1]; int left = leftTopBlack[0]; int right = rightBottomBlack[0]; if (bottom - top != right - left) { // Special case, where bottom-right module wasn't black so we found something else in the last row // Assume it's a square, so use height as the width right = left + (bottom - top); } int matrixWidth = (int)Math.Round((right - left + 1) / moduleSize); int matrixHeight = (int) Math.Round((bottom - top + 1) / moduleSize); if (matrixWidth <= 0 || matrixHeight <= 0) { throw NotFoundException.NotFoundInstance; } if (matrixHeight != matrixWidth) { // Only possibly decode square regions throw NotFoundException.NotFoundInstance; } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = (int)(moduleSize / 2.0f); top += nudge; left += nudge; // Now just read off the bits BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); for (int y = 0; y < matrixHeight; y++) { int iOffset = top + (int)(y * moduleSize); for (int x = 0; x < matrixWidth; x++) { if (image.get(left + (int)(x * moduleSize), iOffset)) { bits.set(x, y); } } } return bits; } //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static float moduleSize(int[] leftTopBlack, com.google.zxing.common.BitMatrix image) throws com.google.zxing.NotFoundException private static float getModuleSize(int[] leftTopBlack, BitMatrix image) { int height = image.Height; int width = image.Width; int x = leftTopBlack[0]; int y = leftTopBlack[1]; bool inBlack = true; int transitions = 0; while (x < width && y < height) { if (inBlack != image.get(x, y)) { if (++transitions == 5) { break; } inBlack = !inBlack; } x++; y++; } if (x == width || y == height) { throw NotFoundException.NotFoundInstance; } return (x - leftTopBlack[0]) / 7.0f; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal abstract class ExprVisitorBase { public EXPR Visit(EXPR pExpr) { if (pExpr == null) { return null; } EXPR pResult; if (IsCachedExpr(pExpr, out pResult)) { return pResult; } if (pExpr.isSTMT()) { return CacheExprMapping(pExpr, DispatchStatementList(pExpr.asSTMT())); } return CacheExprMapping(pExpr, Dispatch(pExpr)); } ///////////////////////////////////////////////////////////////////////////////// private EXPRSTMT DispatchStatementList(EXPRSTMT expr) { Debug.Assert(expr != null); EXPRSTMT first = expr; EXPRSTMT pexpr = first; while (pexpr != null) { // If the processor replaces the statement -- potentially with // null, another statement, or a list of statements -- then we // make sure that the statement list is hooked together correctly. EXPRSTMT next = pexpr.GetOptionalNextStatement(); EXPRSTMT old = pexpr; // Unhook the next one. pexpr.SetOptionalNextStatement(null); EXPR result = Dispatch(pexpr); Debug.Assert(result == null || result.isSTMT()); if (pexpr == first) { first = result?.asSTMT(); } else { pexpr.SetOptionalNextStatement(result?.asSTMT()); } // A transformation may return back a list of statements (or // if the statements have been determined to be unnecessary, // perhaps it has simply returned null.) // // Skip visiting the new list, then hook the tail of the old list // up to the end of the new list. while (pexpr.GetOptionalNextStatement() != null) { pexpr = pexpr.GetOptionalNextStatement(); } // Re-hook the next pointer. pexpr.SetOptionalNextStatement(next); } return first; } ///////////////////////////////////////////////////////////////////////////////// private bool IsCachedExpr(EXPR pExpr, out EXPR pTransformedExpr) { pTransformedExpr = null; return false; } ///////////////////////////////////////////////////////////////////////////////// private EXPR CacheExprMapping(EXPR pExpr, EXPR pTransformedExpr) { return pTransformedExpr; } protected virtual EXPR Dispatch(EXPR pExpr) { switch (pExpr.kind) { case ExpressionKind.EK_BLOCK: return VisitBLOCK(pExpr as EXPRBLOCK); case ExpressionKind.EK_RETURN: return VisitRETURN(pExpr as EXPRRETURN); case ExpressionKind.EK_BINOP: return VisitBINOP(pExpr as EXPRBINOP); case ExpressionKind.EK_UNARYOP: return VisitUNARYOP(pExpr as EXPRUNARYOP); case ExpressionKind.EK_ASSIGNMENT: return VisitASSIGNMENT(pExpr as EXPRASSIGNMENT); case ExpressionKind.EK_LIST: return VisitLIST(pExpr as EXPRLIST); case ExpressionKind.EK_QUESTIONMARK: return VisitQUESTIONMARK(pExpr as EXPRQUESTIONMARK); case ExpressionKind.EK_ARRAYINDEX: return VisitARRAYINDEX(pExpr as EXPRARRAYINDEX); case ExpressionKind.EK_ARRAYLENGTH: return VisitARRAYLENGTH(pExpr as EXPRARRAYLENGTH); case ExpressionKind.EK_CALL: return VisitCALL(pExpr as EXPRCALL); case ExpressionKind.EK_EVENT: return VisitEVENT(pExpr as EXPREVENT); case ExpressionKind.EK_FIELD: return VisitFIELD(pExpr as EXPRFIELD); case ExpressionKind.EK_LOCAL: return VisitLOCAL(pExpr as EXPRLOCAL); case ExpressionKind.EK_THISPOINTER: return VisitTHISPOINTER(pExpr as EXPRTHISPOINTER); case ExpressionKind.EK_CONSTANT: return VisitCONSTANT(pExpr as ExprConstant); case ExpressionKind.EK_TYPEARGUMENTS: return VisitTYPEARGUMENTS(pExpr as EXPRTYPEARGUMENTS); case ExpressionKind.EK_TYPEORNAMESPACE: return VisitTYPEORNAMESPACE(pExpr as EXPRTYPEORNAMESPACE); case ExpressionKind.EK_CLASS: return VisitCLASS(pExpr as EXPRCLASS); case ExpressionKind.EK_FUNCPTR: return VisitFUNCPTR(pExpr as EXPRFUNCPTR); case ExpressionKind.EK_PROP: return VisitPROP(pExpr as EXPRPROP); case ExpressionKind.EK_MULTI: return VisitMULTI(pExpr as EXPRMULTI); case ExpressionKind.EK_MULTIGET: return VisitMULTIGET(pExpr as EXPRMULTIGET); case ExpressionKind.EK_WRAP: return VisitWRAP(pExpr as EXPRWRAP); case ExpressionKind.EK_CONCAT: return VisitCONCAT(pExpr as EXPRCONCAT); case ExpressionKind.EK_ARRINIT: return VisitARRINIT(pExpr as EXPRARRINIT); case ExpressionKind.EK_CAST: return VisitCAST(pExpr as EXPRCAST); case ExpressionKind.EK_USERDEFINEDCONVERSION: return VisitUSERDEFINEDCONVERSION(pExpr as EXPRUSERDEFINEDCONVERSION); case ExpressionKind.EK_TYPEOF: return VisitTYPEOF(pExpr as EXPRTYPEOF); case ExpressionKind.EK_ZEROINIT: return VisitZEROINIT(pExpr as EXPRZEROINIT); case ExpressionKind.EK_USERLOGOP: return VisitUSERLOGOP(pExpr as EXPRUSERLOGOP); case ExpressionKind.EK_MEMGRP: return VisitMEMGRP(pExpr as EXPRMEMGRP); case ExpressionKind.EK_BOUNDLAMBDA: return VisitBOUNDLAMBDA(pExpr as EXPRBOUNDLAMBDA); case ExpressionKind.EK_UNBOUNDLAMBDA: return VisitUNBOUNDLAMBDA(pExpr as EXPRUNBOUNDLAMBDA); case ExpressionKind.EK_HOISTEDLOCALEXPR: return VisitHOISTEDLOCALEXPR(pExpr as EXPRHOISTEDLOCALEXPR); case ExpressionKind.EK_FIELDINFO: return VisitFIELDINFO(pExpr as EXPRFIELDINFO); case ExpressionKind.EK_METHODINFO: return VisitMETHODINFO(pExpr as EXPRMETHODINFO); // Binary operators case ExpressionKind.EK_EQUALS: return VisitEQUALS(pExpr.asBIN()); case ExpressionKind.EK_COMPARE: return VisitCOMPARE(pExpr.asBIN()); case ExpressionKind.EK_NE: return VisitNE(pExpr.asBIN()); case ExpressionKind.EK_LT: return VisitLT(pExpr.asBIN()); case ExpressionKind.EK_LE: return VisitLE(pExpr.asBIN()); case ExpressionKind.EK_GT: return VisitGT(pExpr.asBIN()); case ExpressionKind.EK_GE: return VisitGE(pExpr.asBIN()); case ExpressionKind.EK_ADD: return VisitADD(pExpr.asBIN()); case ExpressionKind.EK_SUB: return VisitSUB(pExpr.asBIN()); case ExpressionKind.EK_MUL: return VisitMUL(pExpr.asBIN()); case ExpressionKind.EK_DIV: return VisitDIV(pExpr.asBIN()); case ExpressionKind.EK_MOD: return VisitMOD(pExpr.asBIN()); case ExpressionKind.EK_BITAND: return VisitBITAND(pExpr.asBIN()); case ExpressionKind.EK_BITOR: return VisitBITOR(pExpr.asBIN()); case ExpressionKind.EK_BITXOR: return VisitBITXOR(pExpr.asBIN()); case ExpressionKind.EK_LSHIFT: return VisitLSHIFT(pExpr.asBIN()); case ExpressionKind.EK_RSHIFT: return VisitRSHIFT(pExpr.asBIN()); case ExpressionKind.EK_LOGAND: return VisitLOGAND(pExpr.asBIN()); case ExpressionKind.EK_LOGOR: return VisitLOGOR(pExpr.asBIN()); case ExpressionKind.EK_SEQUENCE: return VisitSEQUENCE(pExpr.asBIN()); case ExpressionKind.EK_SEQREV: return VisitSEQREV(pExpr.asBIN()); case ExpressionKind.EK_SAVE: return VisitSAVE(pExpr.asBIN()); case ExpressionKind.EK_SWAP: return VisitSWAP(pExpr.asBIN()); case ExpressionKind.EK_INDIR: return VisitINDIR(pExpr.asBIN()); case ExpressionKind.EK_STRINGEQ: return VisitSTRINGEQ(pExpr.asBIN()); case ExpressionKind.EK_STRINGNE: return VisitSTRINGNE(pExpr.asBIN()); case ExpressionKind.EK_DELEGATEEQ: return VisitDELEGATEEQ(pExpr.asBIN()); case ExpressionKind.EK_DELEGATENE: return VisitDELEGATENE(pExpr.asBIN()); case ExpressionKind.EK_DELEGATEADD: return VisitDELEGATEADD(pExpr.asBIN()); case ExpressionKind.EK_DELEGATESUB: return VisitDELEGATESUB(pExpr.asBIN()); case ExpressionKind.EK_EQ: return VisitEQ(pExpr.asBIN()); // Unary operators case ExpressionKind.EK_TRUE: return VisitTRUE(pExpr.asUnaryOperator()); case ExpressionKind.EK_FALSE: return VisitFALSE(pExpr.asUnaryOperator()); case ExpressionKind.EK_INC: return VisitINC(pExpr.asUnaryOperator()); case ExpressionKind.EK_DEC: return VisitDEC(pExpr.asUnaryOperator()); case ExpressionKind.EK_LOGNOT: return VisitLOGNOT(pExpr.asUnaryOperator()); case ExpressionKind.EK_NEG: return VisitNEG(pExpr.asUnaryOperator()); case ExpressionKind.EK_UPLUS: return VisitUPLUS(pExpr.asUnaryOperator()); case ExpressionKind.EK_BITNOT: return VisitBITNOT(pExpr.asUnaryOperator()); case ExpressionKind.EK_ADDR: return VisitADDR(pExpr.asUnaryOperator()); case ExpressionKind.EK_DECIMALNEG: return VisitDECIMALNEG(pExpr.asUnaryOperator()); case ExpressionKind.EK_DECIMALINC: return VisitDECIMALINC(pExpr.asUnaryOperator()); case ExpressionKind.EK_DECIMALDEC: return VisitDECIMALDEC(pExpr.asUnaryOperator()); default: throw Error.InternalCompilerError(); } } private void VisitChildren(EXPR pExpr) { Debug.Assert(pExpr != null); EXPR exprRet = null; // Lists are a special case. We treat a list not as a // binary node but rather as a node with n children. if (pExpr.isLIST()) { EXPRLIST list = pExpr.asLIST(); while (true) { list.SetOptionalElement(Visit(list.GetOptionalElement())); if (list.GetOptionalNextListNode() == null) { return; } if (!list.GetOptionalNextListNode().isLIST()) { list.SetOptionalNextListNode(Visit(list.GetOptionalNextListNode())); return; } list = list.GetOptionalNextListNode().asLIST(); } } switch (pExpr.kind) { default: if (pExpr.isUnaryOperator()) { goto VISIT_EXPRUNARYOP; } Debug.Assert(pExpr.isBIN()); goto VISIT_EXPRBINOP; VISIT_EXPR: break; VISIT_BASE_EXPRSTMT: goto VISIT_EXPR; VISIT_EXPRSTMT: goto VISIT_BASE_EXPRSTMT; case ExpressionKind.EK_BINOP: goto VISIT_EXPRBINOP; VISIT_BASE_EXPRBINOP: goto VISIT_EXPR; VISIT_EXPRBINOP: exprRet = Visit((pExpr as EXPRBINOP).GetOptionalLeftChild()); (pExpr as EXPRBINOP).SetOptionalLeftChild(exprRet as EXPR); exprRet = Visit((pExpr as EXPRBINOP).GetOptionalRightChild()); (pExpr as EXPRBINOP).SetOptionalRightChild(exprRet as EXPR); goto VISIT_BASE_EXPRBINOP; case ExpressionKind.EK_LIST: goto VISIT_EXPRLIST; VISIT_BASE_EXPRLIST: goto VISIT_EXPR; VISIT_EXPRLIST: exprRet = Visit((pExpr as EXPRLIST).GetOptionalElement()); (pExpr as EXPRLIST).SetOptionalElement(exprRet as EXPR); exprRet = Visit((pExpr as EXPRLIST).GetOptionalNextListNode()); (pExpr as EXPRLIST).SetOptionalNextListNode(exprRet as EXPR); goto VISIT_BASE_EXPRLIST; case ExpressionKind.EK_ASSIGNMENT: goto VISIT_EXPRASSIGNMENT; VISIT_BASE_EXPRASSIGNMENT: goto VISIT_EXPR; VISIT_EXPRASSIGNMENT: exprRet = Visit((pExpr as EXPRASSIGNMENT).GetLHS()); Debug.Assert(exprRet != null); (pExpr as EXPRASSIGNMENT).SetLHS(exprRet as EXPR); exprRet = Visit((pExpr as EXPRASSIGNMENT).GetRHS()); Debug.Assert(exprRet != null); (pExpr as EXPRASSIGNMENT).SetRHS(exprRet as EXPR); goto VISIT_BASE_EXPRASSIGNMENT; case ExpressionKind.EK_QUESTIONMARK: goto VISIT_EXPRQUESTIONMARK; VISIT_BASE_EXPRQUESTIONMARK: goto VISIT_EXPR; VISIT_EXPRQUESTIONMARK: exprRet = Visit((pExpr as EXPRQUESTIONMARK).GetTestExpression()); Debug.Assert(exprRet != null); (pExpr as EXPRQUESTIONMARK).SetTestExpression(exprRet as EXPR); exprRet = Visit((pExpr as EXPRQUESTIONMARK).GetConsequence()); Debug.Assert(exprRet != null); (pExpr as EXPRQUESTIONMARK).SetConsequence(exprRet as EXPRBINOP); goto VISIT_BASE_EXPRQUESTIONMARK; case ExpressionKind.EK_ARRAYINDEX: goto VISIT_EXPRARRAYINDEX; VISIT_BASE_EXPRARRAYINDEX: goto VISIT_EXPR; VISIT_EXPRARRAYINDEX: exprRet = Visit((pExpr as EXPRARRAYINDEX).GetArray()); Debug.Assert(exprRet != null); (pExpr as EXPRARRAYINDEX).SetArray(exprRet as EXPR); exprRet = Visit((pExpr as EXPRARRAYINDEX).GetIndex()); Debug.Assert(exprRet != null); (pExpr as EXPRARRAYINDEX).SetIndex(exprRet as EXPR); goto VISIT_BASE_EXPRARRAYINDEX; case ExpressionKind.EK_ARRAYLENGTH: goto VISIT_EXPRARRAYLENGTH; VISIT_BASE_EXPRARRAYLENGTH: goto VISIT_EXPR; VISIT_EXPRARRAYLENGTH: exprRet = Visit((pExpr as EXPRARRAYLENGTH).GetArray()); Debug.Assert(exprRet != null); (pExpr as EXPRARRAYLENGTH).SetArray(exprRet as EXPR); goto VISIT_BASE_EXPRARRAYLENGTH; case ExpressionKind.EK_UNARYOP: goto VISIT_EXPRUNARYOP; VISIT_BASE_EXPRUNARYOP: goto VISIT_EXPR; VISIT_EXPRUNARYOP: exprRet = Visit((pExpr as EXPRUNARYOP).Child); Debug.Assert(exprRet != null); (pExpr as EXPRUNARYOP).Child = exprRet as EXPR; goto VISIT_BASE_EXPRUNARYOP; case ExpressionKind.EK_USERLOGOP: goto VISIT_EXPRUSERLOGOP; VISIT_BASE_EXPRUSERLOGOP: goto VISIT_EXPR; VISIT_EXPRUSERLOGOP: exprRet = Visit((pExpr as EXPRUSERLOGOP).TrueFalseCall); Debug.Assert(exprRet != null); (pExpr as EXPRUSERLOGOP).TrueFalseCall = exprRet as EXPR; exprRet = Visit((pExpr as EXPRUSERLOGOP).OperatorCall); Debug.Assert(exprRet != null); (pExpr as EXPRUSERLOGOP).OperatorCall = exprRet as EXPRCALL; exprRet = Visit((pExpr as EXPRUSERLOGOP).FirstOperandToExamine); Debug.Assert(exprRet != null); (pExpr as EXPRUSERLOGOP).FirstOperandToExamine = exprRet as EXPR; goto VISIT_BASE_EXPRUSERLOGOP; case ExpressionKind.EK_TYPEOF: goto VISIT_EXPRTYPEOF; VISIT_BASE_EXPRTYPEOF: goto VISIT_EXPR; VISIT_EXPRTYPEOF: exprRet = Visit((pExpr as EXPRTYPEOF).GetSourceType()); (pExpr as EXPRTYPEOF).SetSourceType(exprRet as EXPRTYPEORNAMESPACE); goto VISIT_BASE_EXPRTYPEOF; case ExpressionKind.EK_CAST: goto VISIT_EXPRCAST; VISIT_BASE_EXPRCAST: goto VISIT_EXPR; VISIT_EXPRCAST: exprRet = Visit((pExpr as EXPRCAST).GetArgument()); Debug.Assert(exprRet != null); (pExpr as EXPRCAST).SetArgument(exprRet as EXPR); exprRet = Visit((pExpr as EXPRCAST).GetDestinationType()); (pExpr as EXPRCAST).SetDestinationType(exprRet as EXPRTYPEORNAMESPACE); goto VISIT_BASE_EXPRCAST; case ExpressionKind.EK_USERDEFINEDCONVERSION: goto VISIT_EXPRUSERDEFINEDCONVERSION; VISIT_BASE_EXPRUSERDEFINEDCONVERSION: goto VISIT_EXPR; VISIT_EXPRUSERDEFINEDCONVERSION: exprRet = Visit((pExpr as EXPRUSERDEFINEDCONVERSION).UserDefinedCall); Debug.Assert(exprRet != null); (pExpr as EXPRUSERDEFINEDCONVERSION).UserDefinedCall = exprRet as EXPR; goto VISIT_BASE_EXPRUSERDEFINEDCONVERSION; case ExpressionKind.EK_ZEROINIT: goto VISIT_EXPRZEROINIT; VISIT_BASE_EXPRZEROINIT: goto VISIT_EXPR; VISIT_EXPRZEROINIT: exprRet = Visit((pExpr as EXPRZEROINIT).OptionalArgument); (pExpr as EXPRZEROINIT).OptionalArgument = exprRet as EXPR; // Used for when we zeroinit 0 parameter constructors for structs/enums. exprRet = Visit((pExpr as EXPRZEROINIT).OptionalConstructorCall); (pExpr as EXPRZEROINIT).OptionalConstructorCall = exprRet as EXPR; goto VISIT_BASE_EXPRZEROINIT; case ExpressionKind.EK_BLOCK: goto VISIT_EXPRBLOCK; VISIT_BASE_EXPRBLOCK: goto VISIT_EXPRSTMT; VISIT_EXPRBLOCK: exprRet = Visit((pExpr as EXPRBLOCK).GetOptionalStatements()); (pExpr as EXPRBLOCK).SetOptionalStatements(exprRet as EXPRSTMT); goto VISIT_BASE_EXPRBLOCK; case ExpressionKind.EK_MEMGRP: goto VISIT_EXPRMEMGRP; VISIT_BASE_EXPRMEMGRP: goto VISIT_EXPR; VISIT_EXPRMEMGRP: // The object expression. NULL for a static invocation. exprRet = Visit((pExpr as EXPRMEMGRP).GetOptionalObject()); (pExpr as EXPRMEMGRP).SetOptionalObject(exprRet as EXPR); goto VISIT_BASE_EXPRMEMGRP; case ExpressionKind.EK_CALL: goto VISIT_EXPRCALL; VISIT_BASE_EXPRCALL: goto VISIT_EXPR; VISIT_EXPRCALL: exprRet = Visit((pExpr as EXPRCALL).GetOptionalArguments()); (pExpr as EXPRCALL).SetOptionalArguments(exprRet as EXPR); exprRet = Visit((pExpr as EXPRCALL).GetMemberGroup()); Debug.Assert(exprRet != null); (pExpr as EXPRCALL).SetMemberGroup(exprRet as EXPRMEMGRP); goto VISIT_BASE_EXPRCALL; case ExpressionKind.EK_PROP: goto VISIT_EXPRPROP; VISIT_BASE_EXPRPROP: goto VISIT_EXPR; VISIT_EXPRPROP: exprRet = Visit((pExpr as EXPRPROP).GetOptionalArguments()); (pExpr as EXPRPROP).SetOptionalArguments(exprRet as EXPR); exprRet = Visit((pExpr as EXPRPROP).GetMemberGroup()); Debug.Assert(exprRet != null); (pExpr as EXPRPROP).SetMemberGroup(exprRet as EXPRMEMGRP); goto VISIT_BASE_EXPRPROP; case ExpressionKind.EK_FIELD: goto VISIT_EXPRFIELD; VISIT_BASE_EXPRFIELD: goto VISIT_EXPR; VISIT_EXPRFIELD: exprRet = Visit((pExpr as EXPRFIELD).GetOptionalObject()); (pExpr as EXPRFIELD).SetOptionalObject(exprRet as EXPR); goto VISIT_BASE_EXPRFIELD; case ExpressionKind.EK_EVENT: goto VISIT_EXPREVENT; VISIT_BASE_EXPREVENT: goto VISIT_EXPR; VISIT_EXPREVENT: exprRet = Visit((pExpr as EXPREVENT).OptionalObject); (pExpr as EXPREVENT).OptionalObject = exprRet as EXPR; goto VISIT_BASE_EXPREVENT; case ExpressionKind.EK_LOCAL: goto VISIT_EXPRLOCAL; VISIT_BASE_EXPRLOCAL: goto VISIT_EXPR; VISIT_EXPRLOCAL: goto VISIT_BASE_EXPRLOCAL; case ExpressionKind.EK_THISPOINTER: goto VISIT_EXPRTHISPOINTER; VISIT_BASE_EXPRTHISPOINTER: goto VISIT_EXPRLOCAL; VISIT_EXPRTHISPOINTER: goto VISIT_BASE_EXPRTHISPOINTER; case ExpressionKind.EK_RETURN: goto VISIT_EXPRRETURN; VISIT_BASE_EXPRRETURN: goto VISIT_EXPRSTMT; VISIT_EXPRRETURN: exprRet = Visit((pExpr as EXPRRETURN).GetOptionalObject()); (pExpr as EXPRRETURN).SetOptionalObject(exprRet as EXPR); goto VISIT_BASE_EXPRRETURN; case ExpressionKind.EK_CONSTANT: goto VISIT_EXPRCONSTANT; VISIT_BASE_EXPRCONSTANT: goto VISIT_EXPR; VISIT_EXPRCONSTANT: // Used for when we zeroinit 0 parameter constructors for structs/enums. exprRet = Visit((pExpr as ExprConstant).OptionalConstructorCall); (pExpr as ExprConstant).OptionalConstructorCall = exprRet as EXPR; goto VISIT_BASE_EXPRCONSTANT; /************************************************************************************************* TYPEEXPRs defined: The following exprs are used to represent the results of type binding, and are defined as follows: TYPEARGUMENTS - This wraps the type arguments for a class. It contains the TypeArray* which is associated with the AggregateType for the instantiation of the class. TYPEORNAMESPACE - This is the base class for this set of EXPRs. When binding a type, the result must be a type or a namespace. This EXPR encapsulates that fact. The lhs member is the EXPR tree that was bound to resolve the type or namespace. TYPEORNAMESPACEERROR - This is the error class for the type or namespace exprs when we don't know what to bind it to. The following three exprs all have a TYPEORNAMESPACE child, which is their fundamental type: POINTERTYPE - This wraps the sym for the pointer type. NULLABLETYPE - This wraps the sym for the nullable type. CLASS - This represents an instantiation of a class. NSPACE - This represents a namespace, which is the intermediate step when attempting to bind a qualified name. ALIAS - This represents an alias *************************************************************************************************/ case ExpressionKind.EK_TYPEARGUMENTS: goto VISIT_EXPRTYPEARGUMENTS; VISIT_BASE_EXPRTYPEARGUMENTS: goto VISIT_EXPR; VISIT_EXPRTYPEARGUMENTS: exprRet = Visit((pExpr as EXPRTYPEARGUMENTS).GetOptionalElements()); (pExpr as EXPRTYPEARGUMENTS).SetOptionalElements(exprRet as EXPR); goto VISIT_BASE_EXPRTYPEARGUMENTS; case ExpressionKind.EK_TYPEORNAMESPACE: goto VISIT_EXPRTYPEORNAMESPACE; VISIT_BASE_EXPRTYPEORNAMESPACE: goto VISIT_EXPR; VISIT_EXPRTYPEORNAMESPACE: goto VISIT_BASE_EXPRTYPEORNAMESPACE; case ExpressionKind.EK_CLASS: goto VISIT_EXPRCLASS; VISIT_BASE_EXPRCLASS: goto VISIT_EXPRTYPEORNAMESPACE; VISIT_EXPRCLASS: goto VISIT_BASE_EXPRCLASS; case ExpressionKind.EK_FUNCPTR: goto VISIT_EXPRFUNCPTR; VISIT_BASE_EXPRFUNCPTR: goto VISIT_EXPR; VISIT_EXPRFUNCPTR: goto VISIT_BASE_EXPRFUNCPTR; case ExpressionKind.EK_MULTIGET: goto VISIT_EXPRMULTIGET; VISIT_BASE_EXPRMULTIGET: goto VISIT_EXPR; VISIT_EXPRMULTIGET: goto VISIT_BASE_EXPRMULTIGET; case ExpressionKind.EK_MULTI: goto VISIT_EXPRMULTI; VISIT_BASE_EXPRMULTI: goto VISIT_EXPR; VISIT_EXPRMULTI: exprRet = Visit((pExpr as EXPRMULTI).GetLeft()); Debug.Assert(exprRet != null); (pExpr as EXPRMULTI).SetLeft(exprRet as EXPR); exprRet = Visit((pExpr as EXPRMULTI).GetOperator()); Debug.Assert(exprRet != null); (pExpr as EXPRMULTI).SetOperator(exprRet as EXPR); goto VISIT_BASE_EXPRMULTI; case ExpressionKind.EK_WRAP: goto VISIT_EXPRWRAP; VISIT_BASE_EXPRWRAP: goto VISIT_EXPR; VISIT_EXPRWRAP: goto VISIT_BASE_EXPRWRAP; case ExpressionKind.EK_CONCAT: goto VISIT_EXPRCONCAT; VISIT_BASE_EXPRCONCAT: goto VISIT_EXPR; VISIT_EXPRCONCAT: exprRet = Visit((pExpr as EXPRCONCAT).GetFirstArgument()); Debug.Assert(exprRet != null); (pExpr as EXPRCONCAT).SetFirstArgument(exprRet as EXPR); exprRet = Visit((pExpr as EXPRCONCAT).GetSecondArgument()); Debug.Assert(exprRet != null); (pExpr as EXPRCONCAT).SetSecondArgument(exprRet as EXPR); goto VISIT_BASE_EXPRCONCAT; case ExpressionKind.EK_ARRINIT: goto VISIT_EXPRARRINIT; VISIT_BASE_EXPRARRINIT: goto VISIT_EXPR; VISIT_EXPRARRINIT: exprRet = Visit((pExpr as EXPRARRINIT).GetOptionalArguments()); (pExpr as EXPRARRINIT).SetOptionalArguments(exprRet as EXPR); exprRet = Visit((pExpr as EXPRARRINIT).GetOptionalArgumentDimensions()); (pExpr as EXPRARRINIT).SetOptionalArgumentDimensions(exprRet as EXPR); goto VISIT_BASE_EXPRARRINIT; case ExpressionKind.EK_NOOP: goto VISIT_EXPRNOOP; VISIT_BASE_EXPRNOOP: goto VISIT_EXPRSTMT; VISIT_EXPRNOOP: goto VISIT_BASE_EXPRNOOP; case ExpressionKind.EK_BOUNDLAMBDA: goto VISIT_EXPRBOUNDLAMBDA; VISIT_BASE_EXPRBOUNDLAMBDA: goto VISIT_EXPR; VISIT_EXPRBOUNDLAMBDA: exprRet = Visit((pExpr as EXPRBOUNDLAMBDA).OptionalBody); (pExpr as EXPRBOUNDLAMBDA).OptionalBody = exprRet as EXPRBLOCK; goto VISIT_BASE_EXPRBOUNDLAMBDA; case ExpressionKind.EK_UNBOUNDLAMBDA: goto VISIT_EXPRUNBOUNDLAMBDA; VISIT_BASE_EXPRUNBOUNDLAMBDA: goto VISIT_EXPR; VISIT_EXPRUNBOUNDLAMBDA: goto VISIT_BASE_EXPRUNBOUNDLAMBDA; case ExpressionKind.EK_HOISTEDLOCALEXPR: goto VISIT_EXPRHOISTEDLOCALEXPR; VISIT_BASE_EXPRHOISTEDLOCALEXPR: goto VISIT_EXPR; VISIT_EXPRHOISTEDLOCALEXPR: goto VISIT_BASE_EXPRHOISTEDLOCALEXPR; case ExpressionKind.EK_FIELDINFO: goto VISIT_EXPRFIELDINFO; VISIT_BASE_EXPRFIELDINFO: goto VISIT_EXPR; VISIT_EXPRFIELDINFO: goto VISIT_BASE_EXPRFIELDINFO; case ExpressionKind.EK_METHODINFO: goto VISIT_EXPRMETHODINFO; VISIT_BASE_EXPRMETHODINFO: goto VISIT_EXPR; VISIT_EXPRMETHODINFO: goto VISIT_BASE_EXPRMETHODINFO; } } protected virtual EXPR VisitEXPR(EXPR pExpr) { VisitChildren(pExpr); return pExpr; } protected virtual EXPR VisitBLOCK(EXPRBLOCK pExpr) { return VisitSTMT(pExpr); } protected virtual EXPR VisitTHISPOINTER(EXPRTHISPOINTER pExpr) { return VisitLOCAL(pExpr); } protected virtual EXPR VisitRETURN(EXPRRETURN pExpr) { return VisitSTMT(pExpr); } protected virtual EXPR VisitCLASS(EXPRCLASS pExpr) { return VisitTYPEORNAMESPACE(pExpr); } protected virtual EXPR VisitSTMT(EXPRSTMT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitBINOP(EXPRBINOP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitLIST(EXPRLIST pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitASSIGNMENT(EXPRASSIGNMENT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitQUESTIONMARK(EXPRQUESTIONMARK pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitARRAYINDEX(EXPRARRAYINDEX pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitARRAYLENGTH(EXPRARRAYLENGTH pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitUNARYOP(EXPRUNARYOP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitUSERLOGOP(EXPRUSERLOGOP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitTYPEOF(EXPRTYPEOF pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitCAST(EXPRCAST pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitUSERDEFINEDCONVERSION(EXPRUSERDEFINEDCONVERSION pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitZEROINIT(EXPRZEROINIT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitMEMGRP(EXPRMEMGRP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitCALL(EXPRCALL pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitPROP(EXPRPROP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitFIELD(EXPRFIELD pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitEVENT(EXPREVENT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitLOCAL(EXPRLOCAL pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitCONSTANT(ExprConstant pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitTYPEARGUMENTS(EXPRTYPEARGUMENTS pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitTYPEORNAMESPACE(EXPRTYPEORNAMESPACE pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitFUNCPTR(EXPRFUNCPTR pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitMULTIGET(EXPRMULTIGET pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitMULTI(EXPRMULTI pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitWRAP(EXPRWRAP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitCONCAT(EXPRCONCAT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitARRINIT(EXPRARRINIT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitBOUNDLAMBDA(EXPRBOUNDLAMBDA pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitUNBOUNDLAMBDA(EXPRUNBOUNDLAMBDA pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitHOISTEDLOCALEXPR(EXPRHOISTEDLOCALEXPR pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitFIELDINFO(EXPRFIELDINFO pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitMETHODINFO(EXPRMETHODINFO pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitEQUALS(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitCOMPARE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitEQ(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitNE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitGE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitADD(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSUB(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDIV(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitBITAND(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitBITOR(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLSHIFT(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLOGAND(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSEQUENCE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSAVE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitINDIR(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSTRINGEQ(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDELEGATEEQ(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDELEGATEADD(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitRANGE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLT(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitMUL(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitBITXOR(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitRSHIFT(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLOGOR(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSEQREV(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSTRINGNE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDELEGATENE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitGT(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitMOD(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSWAP(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDELEGATESUB(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitTRUE(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitINC(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitLOGNOT(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitNEG(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitBITNOT(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitADDR(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitDECIMALNEG(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitDECIMALDEC(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitFALSE(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitDEC(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitUPLUS(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitDECIMALINC(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Linq.Expressions.Compiler; using System.Reflection; using System.Threading; using System.Runtime.CompilerServices; using System.Linq.Expressions; namespace System.Linq.Expressions { /// <summary> /// Creates a <see cref="LambdaExpression"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> [DebuggerTypeProxy(typeof(Expression.LambdaExpressionProxy))] public abstract class LambdaExpression : Expression { private readonly string _name; private readonly Expression _body; private readonly ReadOnlyCollection<ParameterExpression> _parameters; private readonly Type _delegateType; private readonly bool _tailCall; internal LambdaExpression( Type delegateType, string name, Expression body, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters ) { Debug.Assert(delegateType != null); _name = name; _body = body; _parameters = parameters; _delegateType = delegateType; _tailCall = tailCall; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _delegateType; } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Lambda; } } /// <summary> /// Gets the parameters of the lambda expression. /// </summary> public ReadOnlyCollection<ParameterExpression> Parameters { get { return _parameters; } } /// <summary> /// Gets the name of the lambda expression. /// </summary> /// <remarks>Used for debugging purposes.</remarks> public string Name { get { return _name; } } /// <summary> /// Gets the body of the lambda expression. /// </summary> public Expression Body { get { return _body; } } /// <summary> /// Gets the return type of the lambda expression. /// </summary> public Type ReturnType { get { return Type.GetMethod("Invoke").ReturnType; } } /// <summary> /// Gets the value that indicates if the lambda expression will be compiled with /// tail call optimization. /// </summary> public bool TailCall { get { return _tailCall; } } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile() { #if FEATURE_CORECLR return Compiler.LambdaCompiler.Compile(this); #else return new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitLambda(this); } public virtual LambdaExpression Update(Expression body, IEnumerable<ParameterExpression> parameters) { if (body == Body && parameters == Parameters) { return this; } return Expression.Lambda(Type, body, Name, TailCall, parameters); } #if FEATURE_CORECLR internal abstract LambdaExpression Accept(Compiler.StackSpiller spiller); #endif } /// <summary> /// Defines a <see cref="Expression{TDelegate}"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <typeparam name="TDelegate">The type of the delegate.</typeparam> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> public sealed class Expression<TDelegate> : LambdaExpression { public Expression(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) : base(typeof(TDelegate), name, body, tailCall, parameters) { } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile() { #if FEATURE_CORECLR return (TDelegate)(object)Compiler.LambdaCompiler.Compile(this); #else return (TDelegate)(object)new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="body">The <see cref="LambdaExpression.Body">Body</see> property of the result.</param> /// <param name="parameters">The <see cref="LambdaExpression.Parameters">Parameters</see> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public override LambdaExpression Update(Expression body, IEnumerable<ParameterExpression> parameters) { if (body == Body && parameters == Parameters) { return this; } return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters); } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitLambda(this); } #if FEATURE_CORECLR internal override LambdaExpression Accept(Compiler.StackSpiller spiller) { return spiller.Rewrite(this); } internal static LambdaExpression Create(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { return new Expression<TDelegate>(body, name, tailCall, parameters); } #endif } #if !FEATURE_CORECLR // Seperate expression creation class to hide the CreateExpressionFunc function from users reflecting on Expression<T> public class ExpressionCreator<TDelegate> { public static LambdaExpression CreateExpressionFunc(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { return new Expression<TDelegate>(body, name, tailCall, parameters); } } #endif public partial class Expression { /// <summary> /// Creates an Expression{T} given the delegate type. Caches the /// factory method to speed up repeated creations for the same T. /// </summary> internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { // Get or create a delegate to the public Expression.Lambda<T> // method and call that will be used for creating instances of this // delegate type Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression> fastPath; var factories = s_lambdaFactories; if (factories == null) { s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50); } MethodInfo create = null; if (!factories.TryGetValue(delegateType, out fastPath)) { #if FEATURE_CORECLR create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic); #else create = typeof(ExpressionCreator<>).MakeGenericType(delegateType).GetMethod("CreateExpressionFunc", BindingFlags.Static | BindingFlags.Public); #endif if (TypeUtils.CanCache(delegateType)) { factories[delegateType] = fastPath = (Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)create.CreateDelegate(typeof(Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)); } } if (fastPath != null) { return fastPath(body, name, tailCall, parameters); } Debug.Assert(create != null); return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters }); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, tailCall, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, name, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, bool tailCall, IEnumerable<ParameterExpression> parameters) { var parameterList = parameters.ToReadOnly(); ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList); return new Expression<TDelegate>(body, name, tailCall, parameterList); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters) { return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, false, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, tailCall, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters) { return Lambda(body, name, false, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ContractUtils.RequiresNotNull(body, "body"); var parameterList = parameters.ToReadOnly(); int paramCount = parameterList.Count; Type[] typeArgs = new Type[paramCount + 1]; if (paramCount > 0) { var set = new Set<ParameterExpression>(parameterList.Count); for (int i = 0; i < paramCount; i++) { var param = parameterList[i]; ContractUtils.RequiresNotNull(param, "parameter"); typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type; if (set.Contains(param)) { throw Error.DuplicateVariable(param); } set.Add(param); } } typeArgs[paramCount] = body.Type; Type delegateType = Compiler.DelegateHelpers.MakeDelegateType(typeArgs); return CreateLambda(delegateType, body, name, tailCall, parameterList); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters) { var paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList); return CreateLambda(delegateType, body, name, false, paramList); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { var paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList); return CreateLambda(delegateType, body, name, tailCall, paramList); } private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters) { ContractUtils.RequiresNotNull(delegateType, "delegateType"); RequiresCanRead(body, "body"); if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate)) { throw Error.LambdaTypeMustBeDerivedFromSystemDelegate(); } MethodInfo mi; var ldc = s_lambdaDelegateCache; if (!ldc.TryGetValue(delegateType, out mi)) { mi = delegateType.GetMethod("Invoke"); if (TypeUtils.CanCache(delegateType)) { ldc[delegateType] = mi; } } ParameterInfo[] pis = mi.GetParametersCached(); if (pis.Length > 0) { if (pis.Length != parameters.Count) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } var set = new Set<ParameterExpression>(pis.Length); for (int i = 0, n = pis.Length; i < n; i++) { ParameterExpression pex = parameters[i]; ParameterInfo pi = pis[i]; RequiresCanRead(pex, "parameters"); Type pType = pi.ParameterType; if (pex.IsByRef) { if (!pType.IsByRef) { //We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type. throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType); } pType = pType.GetElementType(); } if (!TypeUtils.AreReferenceAssignable(pex.Type, pType)) { throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType); } if (set.Contains(pex)) { throw Error.DuplicateVariable(pex); } set.Add(pex); } } else if (parameters.Count > 0) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type)) { if (!TryQuote(mi.ReturnType, ref body)) { throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType); } } } private static bool ValidateTryGetFuncActionArgs(Type[] typeArgs) { if (typeArgs == null) { throw new ArgumentNullException("typeArgs"); } for (int i = 0, n = typeArgs.Length; i < n; i++) { var a = typeArgs[i]; if (a == null) { throw new ArgumentNullException("typeArgs"); } if (a.IsByRef) { return false; } } return true; } /// <summary> /// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param> /// <returns>The type of a System.Func delegate that has the specified type arguments.</returns> public static Type GetFuncType(params Type[] typeArgs) { if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef(); Type result = Compiler.DelegateHelpers.GetFuncType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForFunc(); } return result; } /// <summary> /// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param> /// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetFuncType(Type[] typeArgs, out Type funcType) { if (ValidateTryGetFuncActionArgs(typeArgs)) { return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) != null; } funcType = null; return false; } /// <summary> /// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param> /// <returns>The type of a System.Action delegate that has the specified type arguments.</returns> public static Type GetActionType(params Type[] typeArgs) { if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef(); Type result = Compiler.DelegateHelpers.GetActionType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForAction(); } return result; } /// <summary> /// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param> /// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetActionType(Type[] typeArgs, out Type actionType) { if (ValidateTryGetFuncActionArgs(typeArgs)) { return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) != null; } actionType = null; return false; } /// <summary> /// Gets a <see cref="Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments. /// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom /// delegate type. /// </summary> /// <param name="typeArgs">The type arguments of the delegate.</param> /// <returns>The delegate type.</returns> /// <remarks> /// As with Func, the last argument is the return type. It can be set /// to System.Void to produce an Action.</remarks> public static Type GetDelegateType(params Type[] typeArgs) { ContractUtils.RequiresNotEmpty(typeArgs, "typeArgs"); ContractUtils.RequiresNotNullItems(typeArgs, "typeArgs"); return Compiler.DelegateHelpers.MakeDelegateType(typeArgs); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using log4net; using Rhino.Queues.Utils; using Rhino.ServiceBus.Exceptions; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.MessageModules; using Rhino.ServiceBus.Messages; using Rhino.ServiceBus.Sagas; namespace Rhino.ServiceBus.Impl { public class DefaultServiceBus : IStartableServiceBus { private readonly IServiceLocator serviceLocator; private readonly ILog logger = LogManager.GetLogger(typeof(DefaultServiceBus)); private readonly IMessageModule[] modules; private readonly IReflection reflection; private readonly ISubscriptionStorage subscriptionStorage; private readonly ITransport transport; private readonly MessageOwnersSelector messageOwners; [ThreadStatic] public static object currentMessage; private readonly IEndpointRouter endpointRouter; private IEnumerable<IServiceBusAware> serviceBusAware = new IServiceBusAware[0]; public DefaultServiceBus( IServiceLocator serviceLocator, ITransport transport, ISubscriptionStorage subscriptionStorage, IReflection reflection, IMessageModule[] modules, MessageOwner[] messageOwners, IEndpointRouter endpointRouter) { this.transport = transport; this.endpointRouter = endpointRouter; this.messageOwners = new MessageOwnersSelector(messageOwners, endpointRouter); this.subscriptionStorage = subscriptionStorage; this.reflection = reflection; this.modules = modules; this.serviceLocator = serviceLocator; } public IMessageModule[] Modules { get { return modules; } } public event Action<Reroute> ReroutedEndpoint; public void Publish(params object[] messages) { if (PublishInternal(messages) == false) throw new MessagePublicationException("There were no subscribers for (" + messages.First() + ")" ); } public void Notify(params object[] messages) { PublishInternal(messages); } public void Reply(params object[] messages) { if (messages == null) throw new ArgumentNullException("messages"); if (messages.Length == 0) throw new MessagePublicationException("Cannot reply with an empty message batch"); transport.Reply(messages); } public void Send(Endpoint endpoint, params object[] messages) { if (messages == null) throw new ArgumentNullException("messages"); if (messages.Length == 0) throw new MessagePublicationException("Cannot send empty message batch"); transport.Send(endpoint, messages); } public void Send(params object[] messages) { Send(messageOwners.GetEndpointForMessageBatch(messages), messages); } public void ConsumeMessages(params object[] messages) { foreach (var message in messages) { var currentMessageInfo = new CurrentMessageInformation { AllMessages = messages, Message = message, MessageId = Guid.NewGuid(), Destination = transport.Endpoint.Uri, Source = transport.Endpoint.Uri, TransportMessageId = "ConsumeMessages" }; Transport_OnMessageArrived(currentMessageInfo); } } public IDisposable AddInstanceSubscription(IMessageConsumer consumer) { var information = new InstanceSubscriptionInformation { Consumer = consumer, InstanceSubscriptionKey = Guid.NewGuid(), ConsumedMessages = reflection.GetMessagesConsumed(consumer), }; subscriptionStorage.AddLocalInstanceSubscription(consumer); SubscribeInstanceSubscription(information); return new DisposableAction(() => { subscriptionStorage.RemoveLocalInstanceSubscription(information.Consumer); UnsubscribeInstanceSubscription(information); information.Dispose(); }); } public Endpoint Endpoint { get { return transport.Endpoint; } } public CurrentMessageInformation CurrentMessageInformation { get { return transport.CurrentMessageInformation; } } public void Dispose() { foreach(var aware in serviceBusAware) aware.BusDisposing(this); transport.Dispose(); transport.MessageArrived -= Transport_OnMessageArrived; foreach (IMessageModule module in modules) { module.Stop(transport, this); } var subscriptionAsModule = subscriptionStorage as IMessageModule; if (subscriptionAsModule != null) subscriptionAsModule.Stop(transport, this); var disposableSubscriptionStorage = subscriptionStorage as IDisposable; if (disposableSubscriptionStorage != null) disposableSubscriptionStorage.Dispose(); foreach(var aware in serviceBusAware) aware.BusDisposed(this); } public void Start() { serviceBusAware = serviceLocator.ResolveAll<IServiceBusAware>(); foreach(var aware in serviceBusAware) aware.BusStarting(this); logger.DebugFormat("Starting the bus for {0}", Endpoint); var subscriptionAsModule = subscriptionStorage as IMessageModule; if (subscriptionAsModule != null) { logger.DebugFormat("Initating subscription storage as message module: {0}", subscriptionAsModule); subscriptionAsModule.Init(transport, this); } foreach (var module in modules) { logger.DebugFormat("Initating message module: {0}", module); module.Init(transport, this); } transport.MessageArrived += Transport_OnMessageArrived; transport.AdministrativeMessageArrived += Transport_OnAdministrativeMessageArrived; subscriptionStorage.Initialize(); transport.Start(); AutomaticallySubscribeConsumerMessages(); foreach(var aware in serviceBusAware) aware.BusStarted(this); } private bool Transport_OnAdministrativeMessageArrived(CurrentMessageInformation info) { var route = info.Message as Reroute; if (route == null) return false; endpointRouter.RemapEndpoint(route.OriginalEndPoint, route.NewEndPoint); var reroutedEndpoint = ReroutedEndpoint; if(reroutedEndpoint!=null) reroutedEndpoint(route); return true; } public void Subscribe(Type type) { foreach (var owner in messageOwners.Of(type)) { logger.InfoFormat("Subscribing {0} on {1}", type.FullName, owner.Endpoint); var endpoint = endpointRouter.GetRoutedEndpoint(owner.Endpoint); endpoint.Transactional = owner.Transactional; Send(endpoint, new AddSubscription { Endpoint = Endpoint, Type = type.FullName }); } } public void Subscribe<T>() { Subscribe(typeof(T)); } public void Unsubscribe<T>() { Unsubscribe(typeof(T)); } public void Unsubscribe(Type type) { foreach (var owner in messageOwners.Of(type)) { var endpoint = endpointRouter.GetRoutedEndpoint(owner.Endpoint); endpoint.Transactional = owner.Transactional; Send(endpoint, new RemoveSubscription { Endpoint = Endpoint, Type = type.FullName }); } } private void SubscribeInstanceSubscription(InstanceSubscriptionInformation information) { foreach (var message in information.ConsumedMessages) { bool subscribed = false; foreach (var owner in messageOwners.Of(message)) { logger.DebugFormat("Instance subscribition for {0} on {1}", message.FullName, owner.Endpoint); subscribed = true; var endpoint = endpointRouter.GetRoutedEndpoint(owner.Endpoint); endpoint.Transactional = owner.Transactional; Send(endpoint, new AddInstanceSubscription { Endpoint = Endpoint.Uri.ToString(), Type = message.FullName, InstanceSubscriptionKey = information.InstanceSubscriptionKey }); } if(subscribed ==false) throw new SubscriptionException("Could not find any owner for message " + message + " that we could subscribe for"); } } public void UnsubscribeInstanceSubscription(InstanceSubscriptionInformation information) { foreach (var message in information.ConsumedMessages) { foreach (var owner in messageOwners.Of(message)) { var endpoint = endpointRouter.GetRoutedEndpoint(owner.Endpoint); endpoint.Transactional = owner.Transactional; Send(endpoint, new RemoveInstanceSubscription { Endpoint = Endpoint.Uri.ToString(), Type = message.FullName, InstanceSubscriptionKey = information.InstanceSubscriptionKey }); } } } /// <summary> /// Send the message with a built in delay in its processing /// </summary> /// <param name="endpoint">The endpoint.</param> /// <param name="time">The time.</param> /// <param name="msgs">The messages.</param> public void DelaySend(Endpoint endpoint, DateTime time, params object[] msgs) { transport.Send(endpoint, time, msgs); } /// <summary> /// Send the message with a built in delay in its processing /// </summary> /// <param name="time">The time.</param> /// <param name="msgs">The messages.</param> public void DelaySend(DateTime time, params object[] msgs) { DelaySend(messageOwners.GetEndpointForMessageBatch(msgs), time, msgs); } private void AutomaticallySubscribeConsumerMessages() { var handlers = serviceLocator.GetAllHandlersFor(typeof(IMessageConsumer)); foreach (var handler in handlers) { var msgs = reflection.GetMessagesConsumed(handler.Implementation, type => type == typeof(OccasionalConsumerOf<>) || type == typeof(Consumer<>.SkipAutomaticSubscription)); foreach (var msg in msgs) { Subscribe(msg); } } } private bool PublishInternal(object[] messages) { if (messages == null) throw new ArgumentNullException("messages"); bool sentMsg = false; if (messages.Length == 0) throw new MessagePublicationException("Cannot publish an empty message batch"); var subscriptions = new HashSet<Uri>(); foreach (var message in messages) { Type messageType = message.GetType(); while (messageType != null) { subscriptions.UnionWith(subscriptionStorage.GetSubscriptionsFor(messageType)); foreach (Type interfaceType in messageType.GetInterfaces()) { subscriptions.UnionWith(subscriptionStorage.GetSubscriptionsFor(interfaceType)); } messageType = messageType.BaseType; } } foreach (Uri subscription in subscriptions) { transport.Send(endpointRouter.GetRoutedEndpoint(subscription), messages); sentMsg = true; } return sentMsg; } public bool Transport_OnMessageArrived(CurrentMessageInformation msg) { var consumers = GatherConsumers(msg); if (consumers.Length == 0) { logger.ErrorFormat("Got message {0}, but had no consumers for it", msg.Message); return false; } try { currentMessage = msg.Message; foreach (var consumer in consumers) { logger.DebugFormat("Invoking consume on {0} for message {1}, from '{2}' to '{3}'", consumer, msg.Message, msg.Source, msg.Destination); var sp = Stopwatch.StartNew(); try { reflection.InvokeConsume(consumer, msg.Message); } catch (Exception e) { if(logger.IsDebugEnabled) { var message = string.Format("Consumer {0} failed to process message {1}", consumer, msg.Message ); logger.Debug(message,e); } throw; } finally { sp.Stop(); var elapsed = sp.Elapsed; logger.DebugFormat("Consumer {0} finished processing {1} in {2}", consumer, msg.Message, elapsed); } var sagaEntity = consumer as IAccessibleSaga; if (sagaEntity == null) continue; PersistSagaInstance(sagaEntity); } return true; } finally { currentMessage = null; foreach (var consumer in consumers) { serviceLocator.Release(consumer); } } } private void PersistSagaInstance(IAccessibleSaga saga) { Type persisterType = reflection.GetGenericTypeOf(typeof(ISagaPersister<>), saga); object persister = serviceLocator.Resolve(persisterType); if (saga.IsCompleted) reflection.InvokeSagaPersisterComplete(persister, saga); else reflection.InvokeSagaPersisterSave(persister, saga); } public object[] GatherConsumers(CurrentMessageInformation msg) { var message = msg.Message; object[] sagas = GetSagasFor(message); var sagaMessage = message as ISagaMessage; var msgType = message.GetType(); object[] instanceConsumers = subscriptionStorage .GetInstanceSubscriptions(msgType); var consumerTypes = reflection.GetGenericTypesOfWithBaseTypes(typeof(ConsumerOf<>), message); var occasionalConsumerTypes = reflection.GetGenericTypesOfWithBaseTypes(typeof(OccasionalConsumerOf<>), message); var consumers = GetAllNonOccasionalConsumers(consumerTypes, occasionalConsumerTypes, sagas); for (var i = 0; i < consumers.Length; i++) { var saga = consumers[i] as IAccessibleSaga; if (saga == null) continue; // if there is an existing saga, we skip the new one var type = saga.GetType(); if (sagas.Any(type.IsInstanceOfType)) { serviceLocator.Release(consumers[i]); consumers[i] = null; continue; } // we do not create new sagas if the saga is not initiated by // the message var initiatedBy = reflection.GetGenericTypeOf(typeof(InitiatedBy<>), msgType); if (initiatedBy.IsInstanceOfType(saga) == false) { serviceLocator.Release(consumers[i]); consumers[i] = null; continue; } saga.Id = sagaMessage != null ? sagaMessage.CorrelationId : GuidCombGenerator.Generate(); } return instanceConsumers .Union(sagas) .Union(consumers.Where(x => x != null)) .ToArray(); } /// <summary> /// Here we don't use ResolveAll from Windsor because we want to get an error /// if a component exists which isn't valid /// </summary> private object[] GetAllNonOccasionalConsumers(IEnumerable<Type> consumerTypes, IEnumerable<Type> occasionalConsumerTypes, IEnumerable<object> instanceOfTypesToSkipResolving) { var allHandlers = new List<IHandler>(); foreach (var consumerType in consumerTypes) { var handlers = serviceLocator.GetAllHandlersFor(consumerType); allHandlers.AddRange(handlers); } var consumers = new List<object>(allHandlers.Count); consumers.AddRange(from handler in allHandlers let implementation = handler.Implementation let occasionalConsumerFound = occasionalConsumerTypes.Any(occasionalConsumerType => occasionalConsumerType.IsAssignableFrom(implementation)) where !occasionalConsumerFound where !instanceOfTypesToSkipResolving.Any(x => x.GetType() == implementation) select handler.Resolve()); return consumers.ToArray(); } private object[] GetSagasFor(object message) { var instances = new List<object>(); Type orchestratesType = reflection.GetGenericTypeOf(typeof(Orchestrates<>), message); Type initiatedByType = reflection.GetGenericTypeOf(typeof(InitiatedBy<>), message); var handlers = serviceLocator.GetAllHandlersFor(orchestratesType) .Union(serviceLocator.GetAllHandlersFor(initiatedByType)); foreach (IHandler sagaHandler in handlers) { Type sagaType = sagaHandler.Implementation; //first try to execute any saga finders. Type sagaFinderType = reflection.GetGenericTypeOf(typeof(ISagaFinder<,>), sagaType, reflection.GetUnproxiedType(message)); var sagaFinderHandlers = serviceLocator.GetAllHandlersFor(sagaFinderType); foreach (var sagaFinderHandler in sagaFinderHandlers) { try { var sagaFinder = sagaFinderHandler.Resolve(); var saga = reflection.InvokeSagaFinderFindBy(sagaFinder, message); if (saga != null) instances.Add(saga); } finally { serviceLocator.Release(sagaFinderHandler); } } //we will try to use an ISagaMessage's Correlation id next. var sagaMessage = message as ISagaMessage; if (sagaMessage == null) continue; Type sagaPersisterType = reflection.GetGenericTypeOf(typeof(ISagaPersister<>), sagaType); object sagaPersister = serviceLocator.Resolve(sagaPersisterType); try { object sagas = reflection.InvokeSagaPersisterGet(sagaPersister, sagaMessage.CorrelationId); if (sagas == null) continue; instances.Add(sagas); } finally { serviceLocator.Release(sagaPersister); } } return instances.ToArray(); } } }
// 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; internal struct VT { public String str; public char b0, b1, b2, b3, b4, b5, b6; } internal class CL { public String str = "test string"; public char b0, b1, b2, b3, b4, b5, b6; } internal class StrAccess1 { public static String str1 = "test string"; public static String[,] str2darr = { { "test string" } }; public static char sb0, sb1, sb2, sb3, sb4, sb5, sb6; public static String f(ref String arg) { return arg; } public static Random rand = new Random(); public static int Main() { bool passed = true; String str2 = "test string"; String[] str1darr = { "string access", "test string" }; Char[,] c2darr = { { '0', '1', '2', '3', '4', '5', '6' }, { 'a', 'b', 'c', 'd', 'e', 'f', 'g' } }; CL cl1 = new CL(); VT vt1; vt1.str = "test string"; char b0, b1, b2, b3, b4, b5, b6; //accessing the strings at different indices. assign to local char b0 = str2[0]; b1 = str1[0]; b2 = cl1.str[0]; b3 = vt1.str[0]; b4 = str1darr[1][0]; b5 = str2darr[0, 0][0]; b6 = f(ref str2)[0]; if ((b0 != b1) || (b1 != b2) || (b2 != b3) || (b3 != b4) || (b4 != b5) || (b5 != b6)) passed = false; if ((str2[4] != str1[4]) || (str1[4] != cl1.str[4]) || (cl1.str[4] != vt1.str[4]) || (vt1.str[4] != str1darr[1][4]) || (str1darr[1][4] != str2darr[0, 0][4]) || (str2darr[0, 0][4] != f(ref str2)[4])) passed = false; b0 = str2[10]; b1 = str1[10]; b2 = cl1.str[10]; b3 = vt1.str[10]; b4 = str1darr[1][10]; b5 = str2darr[0, 0][10]; b6 = f(ref str2)[10]; if ((b0 != b1) || (b1 != b2) || (b2 != b3) || (b3 != b4) || (b4 != b5) || (b5 != b6)) passed = false; int j = rand.Next(0, 10); b0 = str2[j]; b1 = str1[j]; b2 = cl1.str[j]; b3 = vt1.str[j]; b4 = str1darr[1][j]; b5 = str2darr[0, 0][j]; b6 = f(ref str2)[j]; if ((b0 != b1) || (b1 != b2) || (b2 != b3) || (b3 != b4) || (b4 != b5) || (b5 != b6)) passed = false; //accessing the strings at different indices, assign to static char sb0 = str2[1]; sb1 = str1[1]; sb2 = cl1.str[1]; sb3 = vt1.str[1]; sb4 = str1darr[1][1]; sb5 = str2darr[0, 0][1]; sb6 = f(ref str2)[1]; if ((sb0 != sb1) || (sb1 != sb2) || (sb2 != sb3) || (sb3 != sb4) || (sb4 != sb5) || (sb5 != sb6)) passed = false; if ((str2[5] != str1[5]) || (str1[5] != cl1.str[5]) || (cl1.str[5] != vt1.str[5]) || (vt1.str[5] != str1darr[1][5]) || (str1darr[1][5] != str2darr[0, 0][5]) || (str2darr[0, 0][5] != f(ref str2)[5])) passed = false; sb0 = str2[9]; sb1 = str1[9]; sb2 = cl1.str[9]; sb3 = vt1.str[9]; sb4 = str1darr[1][9]; sb5 = str2darr[0, 0][9]; sb6 = f(ref str2)[9]; if ((sb0 != sb1) || (sb1 != sb2) || (sb2 != sb3) || (sb3 != sb4) || (sb4 != sb5) || (sb5 != sb6)) passed = false; j = rand.Next(0, 10); sb0 = str2[j]; sb1 = str1[j]; sb2 = cl1.str[j]; sb3 = vt1.str[j]; sb4 = str1darr[1][j]; sb5 = str2darr[0, 0][j]; sb6 = f(ref str2)[j]; if ((sb0 != sb1) || (sb1 != sb2) || (sb2 != sb3) || (sb3 != sb4) || (sb4 != sb5) || (sb5 != sb6)) passed = false; //accessing the strings at different indices, assign to VT char vt1.b0 = str2[2]; vt1.b1 = str1[2]; vt1.b2 = cl1.str[2]; vt1.b3 = vt1.str[2]; vt1.b4 = str1darr[1][2]; vt1.b5 = str2darr[0, 0][2]; vt1.b6 = f(ref str2)[2]; if ((vt1.b0 != vt1.b1) || (vt1.b1 != vt1.b2) || (vt1.b2 != vt1.b3) || (vt1.b3 != vt1.b4) || (vt1.b4 != vt1.b5) || (vt1.b5 != vt1.b6)) passed = false; if ((str2[6] != str1[6]) || (str1[6] != cl1.str[6]) || (cl1.str[6] != vt1.str[6]) || (vt1.str[6] != str1darr[1][6]) || (str1darr[1][6] != str2darr[0, 0][6]) || (str2darr[0, 0][6] != f(ref str2)[6])) passed = false; vt1.b0 = str2[8]; vt1.b1 = str1[8]; vt1.b2 = cl1.str[8]; vt1.b3 = vt1.str[8]; vt1.b4 = str1darr[1][8]; vt1.b5 = str2darr[0, 0][8]; vt1.b6 = f(ref str2)[8]; if ((vt1.b0 != vt1.b1) || (vt1.b1 != vt1.b2) || (vt1.b2 != vt1.b3) || (vt1.b3 != vt1.b4) || (vt1.b4 != vt1.b5) || (vt1.b5 != vt1.b6)) passed = false; j = rand.Next(0, 10); vt1.b0 = str2[j]; vt1.b1 = str1[j]; vt1.b2 = cl1.str[j]; vt1.b3 = vt1.str[j]; vt1.b4 = str1darr[1][j]; vt1.b5 = str2darr[0, 0][j]; vt1.b6 = f(ref str2)[j]; if ((vt1.b0 != vt1.b1) || (vt1.b1 != vt1.b2) || (vt1.b2 != vt1.b3) || (vt1.b3 != vt1.b4) || (vt1.b4 != vt1.b5) || (vt1.b5 != vt1.b6)) passed = false; //accessing the strings at different indices, assign to CL char cl1.b0 = str2[7]; cl1.b1 = str1[7]; cl1.b2 = cl1.str[7]; cl1.b3 = vt1.str[7]; cl1.b4 = str1darr[1][7]; cl1.b5 = str2darr[0, 0][7]; cl1.b6 = f(ref str2)[7]; if ((cl1.b0 != cl1.b1) || (cl1.b1 != cl1.b2) || (cl1.b2 != cl1.b3) || (cl1.b3 != cl1.b4) || (cl1.b4 != cl1.b5) || (cl1.b5 != cl1.b6)) passed = false; if ((str2[0] != str1[0]) || (str1[0] != cl1.str[0]) || (cl1.str[0] != vt1.str[0]) || (vt1.str[0] != str1darr[1][0]) || (str1darr[1][0] != str2darr[0, 0][0]) || (str2darr[0, 0][0] != f(ref str2)[0])) passed = false; cl1.b0 = str2[4]; cl1.b1 = str1[4]; cl1.b2 = cl1.str[4]; cl1.b3 = vt1.str[4]; cl1.b4 = str1darr[1][4]; cl1.b5 = str2darr[0, 0][4]; cl1.b6 = f(ref str2)[4]; if ((cl1.b0 != cl1.b1) || (cl1.b1 != cl1.b2) || (cl1.b2 != cl1.b3) || (cl1.b3 != cl1.b4) || (cl1.b4 != cl1.b5) || (cl1.b5 != cl1.b6)) passed = false; j = rand.Next(0, 10); cl1.b0 = str2[j]; cl1.b1 = str1[j]; cl1.b2 = cl1.str[j]; cl1.b3 = vt1.str[j]; cl1.b4 = str1darr[1][j]; cl1.b5 = str2darr[0, 0][j]; cl1.b6 = f(ref str2)[j]; if ((cl1.b0 != cl1.b1) || (cl1.b1 != cl1.b2) || (cl1.b2 != cl1.b3) || (cl1.b3 != cl1.b4) || (cl1.b4 != cl1.b5) || (cl1.b5 != cl1.b6)) passed = false; //accessing the strings at different indices, assign to 2d array char c2darr[1, 0] = str2[6]; c2darr[1, 1] = str1[6]; c2darr[1, 2] = cl1.str[6]; c2darr[1, 3] = vt1.str[6]; c2darr[1, 4] = str1darr[1][6]; c2darr[1, 5] = str2darr[0, 0][6]; c2darr[1, 6] = f(ref str2)[6]; if ((c2darr[1, 0] != c2darr[1, 1]) || (c2darr[1, 1] != c2darr[1, 2]) || (c2darr[1, 2] != c2darr[1, 3]) || (c2darr[1, 3] != c2darr[1, 4]) || (c2darr[1, 4] != c2darr[1, 5]) || (c2darr[1, 5] != c2darr[1, 6])) passed = false; if ((str2[0] != str1[0]) || (str1[0] != cl1.str[0]) || (cl1.str[0] != vt1.str[0]) || (vt1.str[0] != str1darr[1][0]) || (str1darr[1][0] != str2darr[0, 0][0]) || (str2darr[0, 0][0] != f(ref str2)[0])) passed = false; c2darr[1, 0] = str2[6]; c2darr[1, 1] = str1[6]; c2darr[1, 2] = cl1.str[6]; c2darr[1, 3] = vt1.str[6]; c2darr[1, 4] = str1darr[1][6]; c2darr[1, 5] = str2darr[0, 0][6]; c2darr[1, 6] = f(ref str2)[6]; if ((c2darr[1, 0] != c2darr[1, 1]) || (c2darr[1, 1] != c2darr[1, 2]) || (c2darr[1, 2] != c2darr[1, 3]) || (c2darr[1, 3] != c2darr[1, 4]) || (c2darr[1, 4] != c2darr[1, 5]) || (c2darr[1, 5] != c2darr[1, 6])) passed = false; j = rand.Next(0, 10); c2darr[1, 0] = str2[j]; c2darr[1, 1] = str1[j]; c2darr[1, 2] = cl1.str[j]; c2darr[1, 3] = vt1.str[j]; c2darr[1, 4] = str1darr[1][j]; c2darr[1, 5] = str2darr[0, 0][j]; c2darr[1, 6] = f(ref str2)[j]; if ((c2darr[1, 0] != c2darr[1, 1]) || (c2darr[1, 1] != c2darr[1, 2]) || (c2darr[1, 2] != c2darr[1, 3]) || (c2darr[1, 3] != c2darr[1, 4]) || (c2darr[1, 4] != c2darr[1, 5]) || (c2darr[1, 5] != c2darr[1, 6])) passed = false; if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
//----------------------------------------------------------------------- // <copyright file="GraphStages.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.Annotations; using Akka.Streams.Dsl; using Akka.Streams.Implementation.Stages; using Akka.Streams.Stage; using Akka.Util; namespace Akka.Streams.Implementation.Fusing { /// <summary> /// TBD /// </summary> public static class GraphStages { /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> /// <returns>TBD</returns> public static SimpleLinearGraphStage<T> Identity<T>() => Implementation.Fusing.Identity<T>.Instance; /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> /// <returns>TBD</returns> internal static GraphStageWithMaterializedValue<FlowShape<T, T>, Task> TerminationWatcher<T>() => Implementation.Fusing.TerminationWatcher<T>.Instance; /// <summary> /// Fusing graphs that have cycles involving FanIn stages might lead to deadlocks if /// demand is not carefully managed. /// /// This means that FanIn stages need to early pull every relevant input on startup. /// This can either be implemented inside the stage itself, or this method can be used, /// which adds a detacher stage to every input. /// </summary> /// <typeparam name="T">TBD</typeparam> /// <param name="stage">TBD</param> /// <returns>TBD</returns> internal static IGraph<UniformFanInShape<T, T>, NotUsed> WithDetachedInputs<T>(GraphStage<UniformFanInShape<T, T>> stage) { return GraphDsl.Create(builder => { var concat = builder.Add(stage); var detachers = concat.Ins.Select(inlet => { var detacher = builder.Add(new Detacher<T>()); builder.From(detacher).To(inlet); return detacher.Inlet; }).ToArray(); return new UniformFanInShape<T, T>(concat.Out, detachers); }); } } /// <summary> /// INTERNAL API /// </summary> [InternalApi] public class GraphStageModule : AtomicModule { /// <summary> /// TBD /// </summary> public readonly IGraphStageWithMaterializedValue<Shape, object> Stage; /// <summary> /// TBD /// </summary> /// <param name="shape">TBD</param> /// <param name="attributes">TBD</param> /// <param name="stage">TBD</param> public GraphStageModule(Shape shape, Attributes attributes, IGraphStageWithMaterializedValue<Shape, object> stage) { Shape = shape; Attributes = attributes; Stage = stage; } /// <summary> /// TBD /// </summary> public override Shape Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="shape">TBD</param> /// <returns>TBD</returns> public override IModule ReplaceShape(Shape shape) => new CopiedModule(shape, Attributes.None, this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override IModule CarbonCopy() => ReplaceShape(Shape.DeepCopy()); /// <summary> /// TBD /// </summary> public override Attributes Attributes { get; } /// <summary> /// TBD /// </summary> /// <param name="attributes">TBD</param> /// <returns>TBD</returns> public override IModule WithAttributes(Attributes attributes) => new GraphStageModule(Shape, attributes, Stage); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => $"GraphStage({Stage}) [{GetHashCode()}%08x]"; } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="T">TBD</typeparam> [InternalApi] public abstract class SimpleLinearGraphStage<T> : GraphStage<FlowShape<T, T>> { /// <summary> /// TBD /// </summary> public readonly Inlet<T> Inlet; /// <summary> /// TBD /// </summary> public readonly Outlet<T> Outlet; /// <summary> /// TBD /// </summary> protected SimpleLinearGraphStage(string name = null) { name = name ?? GetType().Name; Inlet = new Inlet<T>(name + ".in"); Outlet = new Outlet<T>(name + ".out"); Shape = new FlowShape<T, T>(Inlet, Outlet); } /// <summary> /// TBD /// </summary> public override FlowShape<T, T> Shape { get; } } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class Identity<T> : SimpleLinearGraphStage<T> { #region internal classes private sealed class Logic : InAndOutGraphStageLogic { private readonly Identity<T> _stage; public Logic(Identity<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Inlet, this); SetHandler(stage.Outlet, this); } public override void OnPush() => Push(_stage.Outlet, Grab(_stage.Inlet)); public override void OnPull() => Pull(_stage.Inlet); } #endregion /// <summary> /// TBD /// </summary> public static readonly Identity<T> Instance = new Identity<T>(); private Identity() { } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = Attributes.CreateName("identityOp"); /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="T">TBD</typeparam> [InternalApi] public sealed class Detacher<T> : SimpleLinearGraphStage<T> { #region internal classes private sealed class Logic : InAndOutGraphStageLogic { private readonly Detacher<T> _stage; public Logic(Detacher<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Inlet, this); SetHandler(stage.Outlet, this); } public override void PreStart() => TryPull(_stage.Inlet); public override void OnPush() { var outlet = _stage.Outlet; if (IsAvailable(outlet)) { var inlet = _stage.Inlet; Push(outlet, Grab(inlet)); TryPull(inlet); } } public override void OnUpstreamFinish() { if (!IsAvailable(_stage.Inlet)) CompleteStage(); } public override void OnPull() { var inlet = _stage.Inlet; if (IsAvailable(inlet)) { var outlet = _stage.Outlet; Push(outlet, Grab(inlet)); if (IsClosed(inlet)) CompleteStage(); else Pull(inlet); } } } #endregion /// <summary> /// TBD /// </summary> public Detacher() : base("Detacher") { } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = Attributes.CreateName("Detacher"); /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "Detacher"; } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class TerminationWatcher<T> : GraphStageWithMaterializedValue<FlowShape<T, T>, Task> { /// <summary> /// TBD /// </summary> public static readonly TerminationWatcher<T> Instance = new TerminationWatcher<T>(); #region internal classes private sealed class Logic : InAndOutGraphStageLogic { private readonly TerminationWatcher<T> _stage; private readonly TaskCompletionSource<NotUsed> _finishPromise; public Logic(TerminationWatcher<T> stage, TaskCompletionSource<NotUsed> finishPromise) : base(stage.Shape) { _stage = stage; _finishPromise = finishPromise; SetHandler(stage._inlet, this); SetHandler(stage._outlet, this); } public override void OnPush() => Push(_stage._outlet, Grab(_stage._inlet)); public override void OnUpstreamFinish() { _finishPromise.TrySetResult(NotUsed.Instance); CompleteStage(); } public override void OnUpstreamFailure(Exception e) { _finishPromise.TrySetException(e); FailStage(e); } public override void OnPull() => Pull(_stage._inlet); public override void OnDownstreamFinish() { _finishPromise.TrySetResult(NotUsed.Instance); CompleteStage(); } } #endregion private readonly Inlet<T> _inlet = new Inlet<T>("terminationWatcher.in"); private readonly Outlet<T> _outlet = new Outlet<T>("terminationWatcher.out"); private TerminationWatcher() { Shape = new FlowShape<T, T>(_inlet, _outlet); } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.TerminationWatcher; /// <summary> /// TBD /// </summary> public override FlowShape<T, T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<Task> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var finishPromise = new TaskCompletionSource<NotUsed>(); return new LogicAndMaterializedValue<Task>(new Logic(this, finishPromise), finishPromise.Task); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "TerminationWatcher"; } // TODO: fix typo /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class FLowMonitorImpl<T> : AtomicReference<object>, IFlowMonitor { /// <summary> /// TBD /// </summary> public FLowMonitorImpl() : base(FlowMonitor.Initialized.Instance) { } /// <summary> /// TBD /// </summary> public FlowMonitor.IStreamState State { get { var value = Value; if(value is T) return new FlowMonitor.Received<T>((T)value); return value as FlowMonitor.IStreamState; } } } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class MonitorFlow<T> : GraphStageWithMaterializedValue<FlowShape<T, T>, IFlowMonitor> { #region Logic private sealed class Logic : InAndOutGraphStageLogic { private readonly MonitorFlow<T> _stage; private readonly FLowMonitorImpl<T> _monitor; public Logic(MonitorFlow<T> stage, FLowMonitorImpl<T> monitor) : base(stage.Shape) { _stage = stage; _monitor = monitor; SetHandler(stage.In, this); SetHandler(stage.Out, this); } public override void OnPush() { var message = Grab(_stage.In); Push(_stage.Out, message); _monitor.Value = message is FlowMonitor.IStreamState ? new FlowMonitor.Received<T>(message) : (object)message; } public override void OnUpstreamFinish() { CompleteStage(); _monitor.Value = FlowMonitor.Finished.Instance; } public override void OnUpstreamFailure(Exception e) { FailStage(e); _monitor.Value = new FlowMonitor.Failed(e); } public override void OnPull() => Pull(_stage.In); public override void OnDownstreamFinish() { CompleteStage(); _monitor.Value = FlowMonitor.Finished.Instance; } public override string ToString() => "MonitorFlowLogic"; } #endregion /// <summary> /// TBD /// </summary> public MonitorFlow() { Shape = new FlowShape<T, T>(In, Out); } /// <summary> /// TBD /// </summary> public Inlet<T> In { get; } = new Inlet<T>("MonitorFlow.in"); /// <summary> /// TBD /// </summary> public Outlet<T> Out { get; } = new Outlet<T>("MonitorFlow.out"); /// <summary> /// TBD /// </summary> public override FlowShape<T, T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<IFlowMonitor> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var monitor = new FLowMonitorImpl<T>(); var logic = new Logic(this, monitor); return new LogicAndMaterializedValue<IFlowMonitor>(logic, monitor); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "MonitorFlow"; } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class TickSource<T> : GraphStageWithMaterializedValue<SourceShape<T>, ICancelable> { #region internal classes [SuppressMessage("ReSharper", "MethodSupportsCancellation")] private sealed class Logic : TimerGraphStageLogic, ICancelable { private readonly TickSource<T> _stage; private readonly AtomicBoolean _cancelled = new AtomicBoolean(); private readonly AtomicReference<Action<NotUsed>> _cancelCallback = new AtomicReference<Action<NotUsed>>(null); public Logic(TickSource<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(_stage.Out, EagerTerminateOutput); } public override void PreStart() { _cancelCallback.Value = GetAsyncCallback<NotUsed>(_ => CompleteStage()); if(_cancelled) CompleteStage(); else ScheduleRepeatedly("TickTimer", _stage._initialDelay, _stage._interval); } protected internal override void OnTimer(object timerKey) { if (IsAvailable(_stage.Out) && !_cancelled) Push(_stage.Out, _stage._tick); } public void Cancel() { if(!_cancelled.GetAndSet(true)) _cancelCallback.Value?.Invoke(NotUsed.Instance); } public bool IsCancellationRequested => _cancelled; public CancellationToken Token { get; } public void CancelAfter(TimeSpan delay) => Task.Delay(delay).ContinueWith(_ => Cancel()); public void CancelAfter(int millisecondsDelay) => Task.Delay(millisecondsDelay).ContinueWith(_ => Cancel()); public void Cancel(bool throwOnFirstException) => Cancel(); public override string ToString() => "TickSourceLogic"; } #endregion private readonly TimeSpan _initialDelay; private readonly TimeSpan _interval; private readonly T _tick; /// <summary> /// TBD /// </summary> /// <param name="initialDelay">TBD</param> /// <param name="interval">TBD</param> /// <param name="tick">TBD</param> public TickSource(TimeSpan initialDelay, TimeSpan interval, T tick) { _initialDelay = initialDelay; _interval = interval; _tick = tick; Shape = new SourceShape<T>(Out); } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.TickSource; /// <summary> /// TBD /// </summary> public Outlet<T> Out { get; } = new Outlet<T>("TimerSource.out"); /// <summary> /// TBD /// </summary> public override SourceShape<T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<ICancelable> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var logic = new Logic(this); return new LogicAndMaterializedValue<ICancelable>(logic, logic); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => $"TickSource({_initialDelay}, {_interval}, {_tick})"; } /// <summary> /// TBD /// </summary> public interface IMaterializedValueSource { /// <summary> /// TBD /// </summary> IModule Module { get; } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> IMaterializedValueSource CopySource(); /// <summary> /// TBD /// </summary> Outlet Outlet { get; } /// <summary> /// TBD /// </summary> StreamLayout.IMaterializedValueNode Computation { get; } /// <summary> /// TBD /// </summary> /// <param name="result">TBD</param> void SetValue(object result); } /// <summary> /// INTERNAL API /// /// This source is not reusable, it is only created internally. /// </summary> /// <typeparam name="T">TBD</typeparam> [InternalApi] public sealed class MaterializedValueSource<T> : GraphStage<SourceShape<T>>, IMaterializedValueSource { #region internal classes private sealed class Logic : GraphStageLogic { private readonly MaterializedValueSource<T> _source; public Logic(MaterializedValueSource<T> source) : base(source.Shape) { _source = source; SetHandler(source.Outlet, EagerTerminateOutput); } public override void PreStart() { var cb = GetAsyncCallback<T>(element => Emit(_source.Outlet, element, CompleteStage)); _source._promise.Task.ContinueWith(task => cb(task.Result), TaskContinuationOptions.ExecuteSynchronously); } } #endregion private static readonly Attributes Name = Attributes.CreateName("matValueSource"); /// <summary> /// TBD /// </summary> public StreamLayout.IMaterializedValueNode Computation { get; } Outlet IMaterializedValueSource.Outlet => Outlet; /// <summary> /// TBD /// </summary> public readonly Outlet<T> Outlet; private readonly TaskCompletionSource<T> _promise = new TaskCompletionSource<T>(); /// <summary> /// TBD /// </summary> /// <param name="computation">TBD</param> /// <param name="outlet">TBD</param> public MaterializedValueSource(StreamLayout.IMaterializedValueNode computation, Outlet<T> outlet) { Computation = computation; Outlet = outlet; Shape = new SourceShape<T>(Outlet); } /// <summary> /// TBD /// </summary> /// <param name="computation">TBD</param> public MaterializedValueSource(StreamLayout.IMaterializedValueNode computation) : this(computation, new Outlet<T>("matValue")) { } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes => Name; /// <summary> /// TBD /// </summary> public override SourceShape<T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="value">TBD</param> public void SetValue(T value) => _promise.SetResult(value); void IMaterializedValueSource.SetValue(object result) => SetValue((T)result); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public MaterializedValueSource<T> CopySource() => new MaterializedValueSource<T>(Computation, Outlet); IMaterializedValueSource IMaterializedValueSource.CopySource() => CopySource(); /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => $"MaterializedValueSource({Computation})"; } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class SingleSource<T> : GraphStage<SourceShape<T>> { #region Internal classes private sealed class Logic : OutGraphStageLogic { private readonly SingleSource<T> _stage; public Logic(SingleSource<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); } public override void OnPull() { Push(_stage.Outlet, _stage._element); CompleteStage(); } } #endregion private readonly T _element; /// <summary> /// TBD /// </summary> public readonly Outlet<T> Outlet = new Outlet<T>("single.out"); /// <summary> /// TBD /// </summary> /// <param name="element">TBD</param> public SingleSource(T element) { ReactiveStreamsCompliance.RequireNonNullElement(element); _element = element; Shape = new SourceShape<T>(Outlet); } /// <summary> /// TBD /// </summary> public override SourceShape<T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class TaskSource<T> : GraphStage<SourceShape<T>> { #region Internal classes private sealed class Logic : OutGraphStageLogic { private readonly TaskSource<T> _stage; public Logic(TaskSource<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); } public override void OnPull() { var callback = GetAsyncCallback<Task<T>>(t => { if (!t.IsCanceled && !t.IsFaulted) Emit(_stage.Outlet, t.Result, CompleteStage); else FailStage(t.IsFaulted ? Flatten(t.Exception) : new TaskCanceledException("Task was cancelled.")); }); _stage._task.ContinueWith(t => callback(t), TaskContinuationOptions.ExecuteSynchronously); SetHandler(_stage.Outlet, EagerTerminateOutput); // After first pull we won't produce anything more } private Exception Flatten(AggregateException exception) => exception.InnerExceptions.Count == 1 ? exception.InnerExceptions[0] : exception; } #endregion private readonly Task<T> _task; /// <summary> /// TBD /// </summary> public readonly Outlet<T> Outlet = new Outlet<T>("task.out"); /// <summary> /// TBD /// </summary> /// <param name="task">TBD</param> public TaskSource(Task<T> task) { ReactiveStreamsCompliance.RequireNonNullElement(task); _task = task; Shape = new SourceShape<T>(Outlet); } /// <summary> /// TBD /// </summary> public override SourceShape<T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "TaskSource"; } /// <summary> /// INTERNAL API /// /// Discards all received elements. /// </summary> [InternalApi] public sealed class IgnoreSink<T> : GraphStageWithMaterializedValue<SinkShape<T>, Task> { #region Internal classes private sealed class Logic : InGraphStageLogic { private readonly IgnoreSink<T> _stage; private readonly TaskCompletionSource<int> _completion; public Logic(IgnoreSink<T> stage, TaskCompletionSource<int> completion) : base(stage.Shape) { _stage = stage; _completion = completion; SetHandler(stage.Inlet, this); } public override void PreStart() => Pull(_stage.Inlet); public override void OnPush() => Pull(_stage.Inlet); public override void OnUpstreamFinish() { base.OnUpstreamFinish(); _completion.TrySetResult(0); } public override void OnUpstreamFailure(Exception e) { base.OnUpstreamFailure(e); _completion.TrySetException(e); } } #endregion public IgnoreSink() { Shape = new SinkShape<T>(Inlet); } protected override Attributes InitialAttributes { get; } = DefaultAttributes.IgnoreSink; public Inlet<T> Inlet { get; } = new Inlet<T>("Ignore.in"); public override SinkShape<T> Shape { get; } public override ILogicAndMaterializedValue<Task> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var completion = new TaskCompletionSource<int>(); var logic = new Logic(this, completion); return new LogicAndMaterializedValue<Task>(logic, completion.Task); } public override string ToString() => "IgnoreSink"; } };
// 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.Diagnostics; using System.Collections.Generic; using System.Text; // Managed mirror of NativeFormatWriter.h/.cpp namespace Internal.NativeFormat { #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif abstract class Vertex { internal int _offset = NotPlaced; internal int _iteration = -1; // Iteration that the offset is valid for internal const int NotPlaced = -1; internal const int Placed = -2; internal const int Unified = -3; public Vertex() { } internal abstract void Save(NativeWriter writer); public int VertexOffset { get { Debug.Assert(_offset >= 0); return _offset; } } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class Section { internal List<Vertex> _items = new List<Vertex>(); internal Dictionary<Vertex, Vertex> _placedMap = new Dictionary<Vertex, Vertex>(); public Section() { } public Vertex Place(Vertex vertex) { if (vertex._offset == Vertex.Unified) { Vertex placedVertex; if (_placedMap.TryGetValue(vertex, out placedVertex)) return placedVertex; placedVertex = new PlacedVertex(vertex); _placedMap.Add(vertex, placedVertex); vertex = placedVertex; } Debug.Assert(vertex._offset == Vertex.NotPlaced); vertex._offset = Vertex.Placed; _items.Add(vertex); return vertex; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class NativeWriter { List<Section> _sections = new List<Section>(); enum SavePhase { Initial, Shrinking, Growing } int _iteration = 0; SavePhase _phase; // Current save phase int _offsetAdjustment; // Cumulative offset adjustment compared to previous iteration int _paddingSize; // How much padding was used Dictionary<Vertex, Vertex> _unifier = new Dictionary<Vertex, Vertex>(); NativePrimitiveEncoder _encoder = new NativePrimitiveEncoder(); #if NATIVEFORMAT_COMPRESSION struct Tentative { internal Vertex Vertex; internal int PreviousOffset; } // State used by compression List<Tentative> _tentativelyWritten = new List<Tentative>(); // Tentatively written Vertices. int _compressionDepth = 0; #endif public NativeWriter() { _encoder.Init(); } public Section NewSection() { Section section = new Section(); _sections.Add(section); return section; } public void WriteByte(byte b) { _encoder.WriteByte(b); } public void WriteUInt8(byte value) { _encoder.WriteUInt8(value); } public void WriteUInt16(ushort value) { _encoder.WriteUInt16(value); } public void WriteUInt32(uint value) { _encoder.WriteUInt32(value); } public void WriteUInt64(ulong value) { _encoder.WriteUInt64(value); } public void WriteUnsigned(uint d) { _encoder.WriteUnsigned(d); } public void WriteSigned(int i) { _encoder.WriteSigned(i); } public void WriteUnsignedLong(ulong i) { _encoder.WriteUnsignedLong(i); } public void WriteSignedLong(long i) { _encoder.WriteSignedLong(i); } public void WriteFloat(float value) { _encoder.WriteFloat(value); } public void WriteDouble(double value) { _encoder.WriteDouble(value); } public void WritePad(int size) { while (size > 0) { _encoder.WriteByte(0); size--; } } public bool IsGrowing() { return _phase == SavePhase.Growing; } public void UpdateOffsetAdjustment(int offsetDelta) { switch (_phase) { case SavePhase.Shrinking: _offsetAdjustment = Math.Min(_offsetAdjustment, offsetDelta); break; case SavePhase.Growing: _offsetAdjustment = Math.Max(_offsetAdjustment, offsetDelta); break; default: break; } } public void RollbackTo(int offset) { _encoder.RollbackTo(offset); } public void RollbackTo(int offset, int offsetAdjustment) { _offsetAdjustment = offsetAdjustment; RollbackTo(offset); } public void PatchByteAt(int offset, byte value) { _encoder.PatchByteAt(offset, value); } // Swallow exceptions if invalid encoding is detected. // This is the price we have to pay for using UTF8. Thing like High Surrogate Start Char - '\ud800' // can be expressed in UTF-16 (which is the format used to store ECMA metadata), but don't have // a representation in UTF-8. private static Encoding _stringEncoding = new UTF8Encoding(false, false); public void WriteString(string s) { // The actual bytes are only necessary for the final version during the growing plase if (IsGrowing()) { byte[] bytes = _stringEncoding.GetBytes(s); _encoder.WriteUnsigned((uint)bytes.Length); for (int i = 0; i < bytes.Length; i++) _encoder.WriteByte(bytes[i]); } else { int byteCount = _stringEncoding.GetByteCount(s); _encoder.WriteUnsigned((uint)byteCount); WritePad(byteCount); } } public void WriteRelativeOffset(Vertex val) { if (val._iteration == -1) { // If the offsets are not determined yet, use the maximum possible encoding _encoder.WriteSigned(0x7FFFFFFF); return; } int offset = val._offset; // If the offset was not update in this iteration yet, adjust it by delta we have accumulated in this iteration so far. // This adjustment allows the offsets to converge faster. if (val._iteration < _iteration) offset += _offsetAdjustment; _encoder.WriteSigned(offset - GetCurrentOffset()); } public int GetCurrentOffset() { return _encoder.Size; } public int GetNumberOfIterations() { return _iteration; } public int GetPaddingSize() { return _paddingSize; } public void Save(Stream stream) { _encoder.Clear(); _phase = SavePhase.Initial; foreach (var section in _sections) foreach (var vertex in section._items) { vertex._offset = GetCurrentOffset(); vertex._iteration = _iteration; vertex.Save(this); #if NATIVEFORMAT_COMPRESSION // Ensure that the compressor state is fully flushed Debug.Assert(_TentativelyWritten.Count == 0); Debug.Assert(_compressionDepth == 0); #endif } // Aggresive phase that only allows offsets to shrink. _phase = SavePhase.Shrinking; for (; ; ) { _iteration++; _encoder.Clear(); _offsetAdjustment = 0; foreach (var section in _sections) foreach (var vertex in section._items) { int currentOffset = GetCurrentOffset(); // Only allow the offsets to shrink. _offsetAdjustment = Math.Min(_offsetAdjustment, currentOffset - vertex._offset); vertex._offset += _offsetAdjustment; if (vertex._offset < currentOffset) { // It is possible for the encoding of relative offsets to grow during some iterations. // Ignore this growth because of it should disappear during next iteration. RollbackTo(vertex._offset); } Debug.Assert(vertex._offset == GetCurrentOffset()); vertex._iteration = _iteration; vertex.Save(this); #if NATIVEFORMAT_COMPRESSION // Ensure that the compressor state is fully flushed Debug.Assert(_tentativelyWritten.Count == 0); Debug.Assert(_compressionDepth == 0); #endif } // We are not able to shrink anymore. We cannot just return here. It is possible that we have rolledback // above because of we shrinked too much. if (_offsetAdjustment == 0) break; // Limit number of shrinking interations. This limit is meant to be hit in corner cases only. if (_iteration > 10) break; } // Conservative phase that only allows the offsets to grow. It is guaranteed to converge. _phase = SavePhase.Growing; for (; ; ) { _iteration++; _encoder.Clear(); _offsetAdjustment = 0; _paddingSize = 0; foreach (var section in _sections) foreach (var vertex in section._items) { int currentOffset = GetCurrentOffset(); // Only allow the offsets to grow. _offsetAdjustment = Math.Max(_offsetAdjustment, currentOffset - vertex._offset); vertex._offset += _offsetAdjustment; if (vertex._offset > currentOffset) { // Padding int padding = vertex._offset - currentOffset; _paddingSize += padding; WritePad(padding); } Debug.Assert(vertex._offset == GetCurrentOffset()); vertex._iteration = _iteration; vertex.Save(this); #if NATIVEFORMAT_COMPRESSION // Ensure that the compressor state is fully flushed Debug.Assert(_tentativelyWritten.Count == 0); Debug.Assert(_compressionDepth == 0); #endif } if (_offsetAdjustment == 0) { _encoder.Save(stream); return; } } } #if NATIVEFORMAT_COMPRESSION // TODO: #else internal struct TypeSignatureCompressor { internal TypeSignatureCompressor(NativeWriter pWriter) { } internal void Pack(Vertex vertex) { } } #endif T Unify<T>(T vertex) where T : Vertex { Vertex existing; if (_unifier.TryGetValue(vertex, out existing)) return (T)existing; Debug.Assert(vertex._offset == Vertex.NotPlaced); vertex._offset = Vertex.Unified; _unifier.Add(vertex, vertex); return vertex; } public Vertex GetUnsignedConstant(uint value) { UnsignedConstant vertex = new UnsignedConstant(value); return Unify(vertex); } public Vertex GetTuple(Vertex item1, Vertex item2) { Tuple vertex = new Tuple(item1, item2); return Unify(vertex); } public Vertex GetTuple(Vertex item1, Vertex item2, Vertex item3) { Tuple vertex = new Tuple(item1, item2, item3); return Unify(vertex); } public Vertex GetMethodNameAndSigSignature(string name, Vertex signature) { MethodNameAndSigSignature sig = new MethodNameAndSigSignature( GetStringConstant(name), GetRelativeOffsetSignature(signature)); return Unify(sig); } public Vertex GetStringConstant(string value) { StringConstant vertex = new StringConstant(value); return Unify(vertex); } public Vertex GetRelativeOffsetSignature(Vertex item) { RelativeOffsetSignature sig = new RelativeOffsetSignature(item); return Unify(sig); } public Vertex GetOffsetSignature(Vertex item) { OffsetSignature sig = new OffsetSignature(item); return Unify(sig); } public Vertex GetExternalTypeSignature(uint externalTypeId) { ExternalTypeSignature sig = new ExternalTypeSignature(externalTypeId); return Unify(sig); } public Vertex GetMethodSignature(uint flags, uint fptrReferenceId, Vertex containingType, Vertex methodNameAndSig, Vertex[] args) { MethodSignature sig = new MethodSignature(flags, fptrReferenceId, containingType, methodNameAndSig, args); return Unify(sig); } public Vertex GetFieldSignature(Vertex containingType, string name) { FieldSignature sig = new FieldSignature(containingType, name); return Unify(sig); } public Vertex GetFixupSignature(FixupSignatureKind kind, Vertex signature) { FixupSignature sig = new FixupSignature(kind, signature); return Unify(sig); } public Vertex GetStaticDataSignature(Vertex type, StaticDataKind staticDataKind) { StaticDataSignature sig = new StaticDataSignature(type, staticDataKind); return Unify(sig); } public Vertex GetMethodSlotSignature(Vertex type, uint slot) { MethodSlotSignature sig = new MethodSlotSignature(type, slot); return Unify(sig); } public Vertex GetMethodSigSignature(uint callingConvention, uint genericArgCount, Vertex returnType, Vertex[] parameters) { MethodSigSignature sig = new MethodSigSignature(callingConvention, genericArgCount, returnType, parameters); return Unify(sig); } public Vertex GetModifierTypeSignature(TypeModifierKind modifier, Vertex param) { ModifierTypeSignature sig = new ModifierTypeSignature(modifier, param); return Unify(sig); } public Vertex GetVariableTypeSignature(uint index, bool method) { VariableTypeSignature sig = new VariableTypeSignature(index, method); return Unify(sig); } public Vertex GetInstantiationTypeSignature(Vertex typeDef, Vertex[] arguments) { InstantiationTypeSignature sig = new InstantiationTypeSignature(typeDef, arguments); return Unify(sig); } public Vertex GetMDArrayTypeSignature(Vertex elementType, uint rank, uint[] bounds, uint[] lowerBounds) { MDArrayTypeSignature sig = new MDArrayTypeSignature(elementType, rank, bounds, lowerBounds); return Unify(sig); } public Vertex GetCallingConventionConverterSignature(uint flags, Vertex signature) { CallingConventionConverterSignature sig = new CallingConventionConverterSignature(flags, GetRelativeOffsetSignature(signature)); return Unify(sig); } } class PlacedVertex : Vertex { Vertex _unified; public PlacedVertex(Vertex unified) { _unified = unified; } internal override void Save(NativeWriter writer) { _unified.Save(writer); } } class UnsignedConstant : Vertex { uint _value; public UnsignedConstant(uint value) { _value = value; } internal override void Save(NativeWriter writer) { writer.WriteUnsigned(_value); } public override int GetHashCode() { return 6659 + ((int)_value) * 19; } public override bool Equals(object other) { if (!(other is UnsignedConstant)) return false; UnsignedConstant p = (UnsignedConstant)other; if (_value != p._value) return false; return true; } } class Tuple : Vertex { private Vertex _item1; private Vertex _item2; private Vertex _item3; public Tuple(Vertex item1, Vertex item2, Vertex item3 = null) { _item1 = item1; _item2 = item2; _item3 = item3; } internal override void Save(NativeWriter writer) { _item1.Save(writer); _item2.Save(writer); if (_item3 != null) _item3.Save(writer); } public override int GetHashCode() { int hash = _item1.GetHashCode() * 93481 + _item2.GetHashCode() + 3492; if (_item3 != null) hash += (hash << 7) + _item3.GetHashCode() * 34987 + 213; return hash; } public override bool Equals(object obj) { Tuple other = obj as Tuple; if (other == null) return false; return Object.Equals(_item1, other._item1) && Object.Equals(_item2, other._item2) && Object.Equals(_item3, other._item3); } } // // Bag of <id, data> pairs. Good for extensible information (e.g. type info) // // Data can be either relative offset of another vertex, or arbitrary integer. // #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class VertexBag : Vertex { enum EntryType { Vertex, Unsigned, Signed } struct Entry { internal BagElementKind _id; internal EntryType _type; internal object _value; internal Entry(BagElementKind id, Vertex value) { _id = id; _type = EntryType.Vertex; _value = value; } internal Entry(BagElementKind id, uint value) { _id = id; _type = EntryType.Unsigned; _value = value; } internal Entry(BagElementKind id, int value) { _id = id; _type = EntryType.Signed; _value = value; } } private List<Entry> _elements; public VertexBag() { _elements = new List<Entry>(); } public void Append(BagElementKind id, Vertex value) { _elements.Add(new Entry(id, value)); } public void AppendUnsigned(BagElementKind id, uint value) { _elements.Add(new Entry(id, value)); } public void AppendSigned(BagElementKind id, int value) { _elements.Add(new Entry(id, value)); } internal override void Save(NativeWriter writer) { foreach (var elem in _elements) { writer.WriteUnsigned((uint)elem._id); switch (elem._type) { case EntryType.Vertex: writer.WriteRelativeOffset((Vertex)elem._value); break; case EntryType.Unsigned: writer.WriteUnsigned((uint)elem._value); break; case EntryType.Signed: writer.WriteSigned((int)elem._value); break; } } writer.WriteUnsigned((uint)BagElementKind.End); } public int ElementsCount => _elements.Count; } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class VertexSequence : Vertex { private List<Vertex> _elements; public VertexSequence() { _elements = new List<Vertex>(); } public void Append(Vertex vertex) { _elements.Add(vertex); } internal override void Save(NativeWriter writer) { writer.WriteUnsigned((uint)_elements.Count); foreach (var elem in _elements) elem.Save(writer); } public override bool Equals(object obj) { var other = obj as VertexSequence; if (other == null || other._elements.Count != _elements.Count) return false; for (int i = 0; i < _elements.Count; i++) if (!Object.Equals(_elements[i], other._elements[i])) return false; return true; } public override int GetHashCode() { int hashCode = 13; foreach (var element in _elements) { int value = (element != null ? element.GetHashCode() : 0) * 0x5498341 + 0x832424; hashCode = hashCode * 31 + value; } return hashCode; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class MethodNameAndSigSignature : Vertex { private Vertex _methodName; private Vertex _signature; public MethodNameAndSigSignature(Vertex methodName, Vertex signature) { _methodName = methodName; _signature = signature; } internal override void Save(NativeWriter writer) { _methodName.Save(writer); _signature.Save(writer); } public override int GetHashCode() { return 509 * 197 + _methodName.GetHashCode() + 647 * _signature.GetHashCode(); } public override bool Equals(object obj) { MethodNameAndSigSignature other = obj as MethodNameAndSigSignature; if (other == null) return false; return Object.Equals(_methodName, other._methodName) && Object.Equals(_signature, other._signature); } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class StringConstant : Vertex { private string _value; public StringConstant(string value) { _value = value; } internal override void Save(NativeWriter writer) { writer.WriteString(_value); } public override int GetHashCode() { return _value.GetHashCode(); } public override bool Equals(object obj) { StringConstant other = obj as StringConstant; if (other == null) return false; return _value == other._value; } } // // Performs indirection to an existing native layout signature by writing out the // relative offset. // #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class RelativeOffsetSignature : Vertex { private Vertex _item; public RelativeOffsetSignature(Vertex item) { _item = item; } internal override void Save(NativeWriter writer) { writer.WriteRelativeOffset(_item); } public override int GetHashCode() { return _item.GetHashCode() >> 3; } public override bool Equals(object obj) { RelativeOffsetSignature other = obj as RelativeOffsetSignature; if (other == null) return false; return Object.Equals(_item, other._item); } } // // Performs indirection to an existing native layout signature using offset from the // beginning of the native format. This allows cross-native layout references. You must // ensure that the native layout writer of the pointee is saved before that of the pointer // so the offsets are locked down. // #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class OffsetSignature : Vertex { private Vertex _item; public OffsetSignature(Vertex item) { _item = item; } internal override void Save(NativeWriter writer) { writer.WriteUnsigned((uint)_item.VertexOffset); } public override int GetHashCode() { return _item.GetHashCode(); } public override bool Equals(object obj) { OffsetSignature other = obj as OffsetSignature; if (other == null) return false; return Object.Equals(_item, other._item); } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class ExternalTypeSignature : Vertex { private uint _externalTypeId; public ExternalTypeSignature(uint externalTypeId) { _externalTypeId = externalTypeId; } internal override void Save(NativeWriter writer) { NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); writer.WriteUnsigned((uint)TypeSignatureKind.External | (_externalTypeId << 4)); compressor.Pack(this); } public override int GetHashCode() { return 32439 + 11 * (int)_externalTypeId; } public override bool Equals(object obj) { ExternalTypeSignature other = obj as ExternalTypeSignature; if (other == null) return false; return _externalTypeId == other._externalTypeId; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class MethodSignature : Vertex { private uint _flags; private uint _fptrReferenceId; private Vertex _containingType; private Vertex _methodNameAndSig; private Vertex[] _args; public MethodSignature(uint flags, uint fptrReferenceId, Vertex containingType, Vertex methodNameAndSig, Vertex[] args) { _flags = flags; _fptrReferenceId = fptrReferenceId; _containingType = containingType; _methodNameAndSig = methodNameAndSig; _args = args; if ((flags & (uint)MethodFlags.HasInstantiation) != 0) Debug.Assert(args != null && args.Length > 0); if ((flags & (uint)MethodFlags.HasFunctionPointer) == 0) Debug.Assert(fptrReferenceId == 0); } internal override void Save(NativeWriter writer) { writer.WriteUnsigned(_flags); if ((_flags & (uint)MethodFlags.HasFunctionPointer) != 0) writer.WriteUnsigned(_fptrReferenceId); _containingType.Save(writer); _methodNameAndSig.Save(writer); if ((_flags & (uint)MethodFlags.HasInstantiation) != 0) { writer.WriteUnsigned((uint)_args.Length); for (uint iArg = 0; _args != null && iArg < _args.Length; iArg++) _args[iArg].Save(writer); } } public override int GetHashCode() { int hash = _args != null ? _args.Length : 0; hash += (hash << 5) + (int)_flags * 23; hash += (hash << 5) + (int)_fptrReferenceId * 119; hash += (hash << 5) + _containingType.GetHashCode(); for (uint iArg = 0; _args != null && iArg < _args.Length; iArg++) hash += (hash << 5) + _args[iArg].GetHashCode(); hash += (hash << 5) + _methodNameAndSig.GetHashCode(); return hash; } public override bool Equals(object obj) { MethodSignature other = obj as MethodSignature; if (other == null) return false; if (!( _flags == other._flags && _fptrReferenceId == other._fptrReferenceId && Object.Equals(_containingType, other._containingType) && Object.Equals(_methodNameAndSig, other._methodNameAndSig))) { return false; } if (_args != null) { if (other._args == null) return false; if (other._args.Length != _args.Length) return false; for (uint iArg = 0; _args != null && iArg < _args.Length; iArg++) if (!Object.Equals(_args[iArg], other._args[iArg])) return false; } else if (other._args != null) return false; return true; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class FieldSignature : Vertex { private Vertex _containingType; private string _name; public FieldSignature(Vertex containingType, string name) { _containingType = containingType; _name = name; } internal override void Save(NativeWriter writer) { _containingType.Save(writer); writer.WriteString(_name); } public override int GetHashCode() { int hash = 113 + 97 * _containingType.GetHashCode(); foreach (char c in _name) hash += (hash << 5) + c * 19; return hash; } public override bool Equals(object obj) { var other = obj as FieldSignature; if (other == null) return false; if (!Object.Equals(other._containingType, _containingType)) return false; if (!Object.Equals(other._name, _name)) return false; return true; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class FixupSignature : Vertex { private FixupSignatureKind _kind; private Vertex _signature; public FixupSignature(FixupSignatureKind kind, Vertex signature) { _kind = kind; _signature = signature; } internal override void Save(NativeWriter writer) { writer.WriteUnsigned((uint)_kind); if (_signature != null) _signature.Save(writer); } public override int GetHashCode() { return 53345 + 97 * (int)_kind + ((_signature != null) ? _signature.GetHashCode() : 0); } public override bool Equals(object obj) { var other = obj as FixupSignature; if (other == null) return false; if (other._kind != _kind) return false; if (!Object.Equals(other._signature, _signature)) return false; return true; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class StaticDataSignature : Vertex { private Vertex _type; private StaticDataKind _staticDataKind; public StaticDataSignature(Vertex type, StaticDataKind staticDataKind) { _type = type; _staticDataKind = staticDataKind; } internal override void Save(NativeWriter writer) { _type.Save(writer); writer.WriteUnsigned((uint)_staticDataKind); } public override int GetHashCode() { return 456789 + 101 * (int)_staticDataKind + _type.GetHashCode(); } public override bool Equals(object obj) { var other = obj as StaticDataSignature; if (other == null) return false; if (!Object.Equals(other._type, _type)) return false; if (other._staticDataKind != _staticDataKind) return false; return true; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class MethodSlotSignature : Vertex { private Vertex _type; private uint _slot; public MethodSlotSignature(Vertex type, uint slot) { _type = type; _slot = slot; } internal override void Save(NativeWriter writer) { _type.Save(writer); writer.WriteUnsigned(_slot); } public override int GetHashCode() { return 124121 + 47 * (int)_slot + _type.GetHashCode(); } public override bool Equals(object obj) { var other = obj as MethodSlotSignature; if (other == null) return false; if (!Object.Equals(other._type, _type)) return false; if (other._slot != _slot) return false; return true; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class MethodSigSignature : Vertex { private uint _callingConvention; private uint _genericArgCount; private Vertex _returnType; private Vertex[] _parameters; public MethodSigSignature(uint callingConvention, uint genericArgCount, Vertex returnType, Vertex[] parameters) { _callingConvention = callingConvention; _returnType = returnType; _genericArgCount = genericArgCount; _parameters = parameters; } internal override void Save(NativeWriter writer) { writer.WriteUnsigned(_callingConvention); // Signatures omit the generic type parameter count for non-generic methods if (_genericArgCount > 0) writer.WriteUnsigned(_genericArgCount); writer.WriteUnsigned((uint)_parameters.Length); _returnType.Save(writer); foreach (var p in _parameters) p.Save(writer); } public override int GetHashCode() { int hash = 317 + 709 * (int)_callingConvention + 953 * (int)_genericArgCount + 31 * _returnType.GetHashCode(); foreach (var p in _parameters) hash += (hash << 5) + p.GetHashCode(); return hash; } public override bool Equals(object obj) { MethodSigSignature other = obj as MethodSigSignature; if (other == null) return false; if (!( _callingConvention == other._callingConvention && _genericArgCount == other._genericArgCount && _parameters.Length == other._parameters.Length && Object.Equals(_returnType, other._returnType))) { return false; } for (int i = 0; i < _parameters.Length; i++) if (!Object.Equals(_parameters[i], other._parameters[i])) return false; return true; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class ModifierTypeSignature : Vertex { private TypeModifierKind _modifier; private Vertex _param; public ModifierTypeSignature(TypeModifierKind modifier, Vertex param) { _modifier = modifier; _param = param; } internal override void Save(NativeWriter writer) { NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); writer.WriteUnsigned((uint)TypeSignatureKind.Modifier | ((uint)_modifier << 4)); _param.Save(writer); compressor.Pack(this); } public override int GetHashCode() { return 432981 + 37 * (int)_modifier + _param.GetHashCode(); } public override bool Equals(object obj) { ModifierTypeSignature other = obj as ModifierTypeSignature; if (other == null) return false; return _modifier == other._modifier && Object.Equals(_param, other._param); } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class VariableTypeSignature : Vertex { private uint _variableId; public VariableTypeSignature(uint index, bool method) { _variableId = (index << 1) | (method ? (uint)1 : 0); } internal override void Save(NativeWriter writer) { NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); writer.WriteUnsigned((uint)TypeSignatureKind.Variable | (_variableId << 4)); compressor.Pack(this); } public override int GetHashCode() { return 6093 + 7 * (int)_variableId; } public override bool Equals(object obj) { VariableTypeSignature other = obj as VariableTypeSignature; if (other == null) return false; return _variableId == other._variableId; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class InstantiationTypeSignature : Vertex { private Vertex _typeDef; private Vertex[] _args; public InstantiationTypeSignature(Vertex typeDef, Vertex[] args) { _typeDef = typeDef; _args = args; } internal override void Save(NativeWriter writer) { NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); writer.WriteUnsigned((uint)TypeSignatureKind.Instantiation | ((uint)_args.Length << 4)); _typeDef.Save(writer); for (int iArg = 0; iArg < _args.Length; iArg++) _args[iArg].Save(writer); compressor.Pack(this); } public override int GetHashCode() { int hash = _args.Length; hash += (hash << 5) + _typeDef.GetHashCode(); for (int iArg = 0; iArg < _args.Length; iArg++) hash += (hash << 5) + _args[iArg].GetHashCode(); return hash; } public override bool Equals(object obj) { InstantiationTypeSignature other = obj as InstantiationTypeSignature; if (other == null) return false; if (_args.Length != other._args.Length || !Object.Equals(_typeDef, other._typeDef)) return false; for (uint iArg = 0; iArg < _args.Length; iArg++) if (!Object.Equals(_args[iArg], other._args[iArg])) return false; return true; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class MDArrayTypeSignature : Vertex { private Vertex _arrayElementType; private uint _rank; private uint[] _bounds; private uint[] _lowerBounds; public MDArrayTypeSignature(Vertex arrayElementType, uint rank, uint[] bounds, uint[] lowerBounds) { Debug.Assert(bounds != null && lowerBounds != null); _arrayElementType = arrayElementType; _rank = rank; _bounds = bounds; _lowerBounds = lowerBounds; } internal override void Save(NativeWriter writer) { NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); writer.WriteUnsigned((uint)TypeSignatureKind.MultiDimArray | ((uint)_rank << 4)); _arrayElementType.Save(writer); writer.WriteUnsigned((uint)_bounds.Length); foreach (uint b in _bounds) writer.WriteUnsigned(b); writer.WriteUnsigned((uint)_lowerBounds.Length); foreach (uint b in _lowerBounds) writer.WriteUnsigned(b); compressor.Pack(this); } public override int GetHashCode() { int hash = 79 + 971 * (int)_rank + 83 * _arrayElementType.GetHashCode(); foreach (uint b in _bounds) hash += (hash << 5) + (int)b * 19; foreach (uint b in _lowerBounds) hash += (hash << 5) + (int)b * 19; return hash; } public override bool Equals(object obj) { MDArrayTypeSignature other = obj as MDArrayTypeSignature; if (other == null) return false; if (!Object.Equals(_arrayElementType, other._arrayElementType) || _rank != other._rank || _bounds.Length != other._bounds.Length || _lowerBounds.Length != other._lowerBounds.Length) { return false; } for (int i = 0; i < _bounds.Length; i++) { if (_bounds[i] != other._bounds[i]) return false; } for (int i = 0; i < _lowerBounds.Length; i++) { if (_lowerBounds[i] != other._lowerBounds[i]) return false; } return true; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class CallingConventionConverterSignature : Vertex { private uint _flags; private Vertex _signature; public CallingConventionConverterSignature(uint flags, Vertex signature) { _flags = flags; _signature = signature; } internal override void Save(NativeWriter writer) { writer.WriteUnsigned(_flags); _signature.Save(writer); } public override int GetHashCode() { return 509 * 197 + ((int)_flags) * 23 + 647 * _signature.GetHashCode(); } public override bool Equals(object obj) { CallingConventionConverterSignature other = obj as CallingConventionConverterSignature; if (other == null) return false; if (_flags != other._flags) return false; if (!_signature.Equals(other._signature)) return false; return true; } } #if NATIVEFORMAT_PUBLICWRITER public #else internal #endif class VertexHashtable : Vertex { struct Entry { public Entry(uint hashcode, Vertex vertex) { Offset = 0; Hashcode = hashcode; Vertex = vertex; } public int Offset; public uint Hashcode; public Vertex Vertex; public static int Comparison(Entry a, Entry b) { return (int)(a.Hashcode /*& mask*/) - (int)(b.Hashcode /*& mask*/); } } private List<Entry> _Entries; // How many entries to target per bucket. Higher fill factor means smaller size, but worse runtime perf. private int _nFillFactor; // Number of buckets choosen for the table. Must be power of two. 0 means that the table is still open for mutation. private uint _nBuckets; // Current size of index entry private int _entryIndexSize; // 0 - uint8, 1 - uint16, 2 - uint32 public const int DefaultFillFactor = 13; public VertexHashtable(int fillFactor = DefaultFillFactor) { _Entries = new List<Entry>(); _nFillFactor = fillFactor; _nBuckets = 0; _entryIndexSize = 0; } public void Append(uint hashcode, Vertex element) { // The table needs to be open for mutation Debug.Assert(_nBuckets == 0); _Entries.Add(new Entry(hashcode, element)); } // Returns 1 + log2(x) rounded up, 0 iff x == 0 static int HighestBit(uint x) { int ret = 0; while (x != 0) { x >>= 1; ret++; } return ret; } // Helper method to back patch entry index in the bucket table static void PatchEntryIndex(NativeWriter writer, int patchOffset, int entryIndexSize, int entryIndex) { if (entryIndexSize == 0) { writer.PatchByteAt(patchOffset, (byte)entryIndex); } else if (entryIndexSize == 1) { writer.PatchByteAt(patchOffset, (byte)entryIndex); writer.PatchByteAt(patchOffset + 1, (byte)(entryIndex >> 8)); } else { writer.PatchByteAt(patchOffset, (byte)entryIndex); writer.PatchByteAt(patchOffset + 1, (byte)(entryIndex >> 8)); writer.PatchByteAt(patchOffset + 2, (byte)(entryIndex >> 16)); writer.PatchByteAt(patchOffset + 3, (byte)(entryIndex >> 24)); } } void ComputeLayout() { uint bucketsEstimate = (uint)(_Entries.Count / _nFillFactor); // Round number of buckets up to the power of two _nBuckets = (uint)(1 << HighestBit(bucketsEstimate)); // Lowest byte of the hashcode is used for lookup within the bucket. Keep it sorted too so that // we can use the ordering to terminate the lookup prematurely. uint mask = ((_nBuckets - 1) << 8) | 0xFF; // sort it by hashcode _Entries.Sort( (a, b) => { return (int)(a.Hashcode & mask) - (int)(b.Hashcode & mask); } ); // Start with maximum size entries _entryIndexSize = 2; } internal override void Save(NativeWriter writer) { // Compute the layout of the table if we have not done it yet if (_nBuckets == 0) ComputeLayout(); int nEntries = _Entries.Count; int startOffset = writer.GetCurrentOffset(); uint bucketMask = (_nBuckets - 1); // Lowest two bits are entry index size, the rest is log2 number of buckets int numberOfBucketsShift = HighestBit(_nBuckets) - 1; writer.WriteByte((byte)((numberOfBucketsShift << 2) | _entryIndexSize)); int bucketsOffset = writer.GetCurrentOffset(); writer.WritePad((int)((_nBuckets + 1) << _entryIndexSize)); // For faster lookup at runtime, we store the first entry index even though it is redundant (the // value can be inferred from number of buckets) PatchEntryIndex(writer, bucketsOffset, _entryIndexSize, writer.GetCurrentOffset() - bucketsOffset); int iEntry = 0; for (int iBucket = 0; iBucket < _nBuckets; iBucket++) { while (iEntry < nEntries) { if (((_Entries[iEntry].Hashcode >> 8) & bucketMask) != iBucket) break; Entry curEntry = _Entries[iEntry]; int currentOffset = writer.GetCurrentOffset(); writer.UpdateOffsetAdjustment(currentOffset - curEntry.Offset); curEntry.Offset = currentOffset; _Entries[iEntry] = curEntry; writer.WriteByte((byte)curEntry.Hashcode); writer.WriteRelativeOffset(curEntry.Vertex); iEntry++; } int patchOffset = bucketsOffset + ((iBucket + 1) << _entryIndexSize); PatchEntryIndex(writer, patchOffset, _entryIndexSize, writer.GetCurrentOffset() - bucketsOffset); } Debug.Assert(iEntry == nEntries); int maxIndexEntry = (writer.GetCurrentOffset() - bucketsOffset); int newEntryIndexSize = 0; if (maxIndexEntry > 0xFF) { newEntryIndexSize++; if (maxIndexEntry > 0xFFFF) newEntryIndexSize++; } if (writer.IsGrowing()) { if (newEntryIndexSize > _entryIndexSize) { // Ensure that the table will be redone with new entry index size writer.UpdateOffsetAdjustment(1); _entryIndexSize = newEntryIndexSize; } } else { if (newEntryIndexSize < _entryIndexSize) { // Ensure that the table will be redone with new entry index size writer.UpdateOffsetAdjustment(-1); _entryIndexSize = newEntryIndexSize; } } } public override bool Equals(object obj) { throw new NotImplementedException(); } public override int GetHashCode() { throw new NotImplementedException(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Test { public class UnionTests { private const int DuplicateFactor = 8; // Get two ranges, with the right starting where the left ends public static IEnumerable<object[]> UnionUnorderedData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts.Cast<int>(), (l, r) => l, rightCounts.Cast<int>())) { yield return parms.Take(4).ToArray(); } } // Union returns only the ordered portion ordered. See Issue #1331 // Get two ranges, both ordered. public static IEnumerable<object[]> UnionData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } // Get two ranges, with only the left being ordered. public static IEnumerable<object[]> UnionFirstOrderedData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] }; } } // Get two ranges, with only the right being ordered. public static IEnumerable<object[]> UnionSecondOrderedData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts)) { yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } // Get two ranges, both sourced from arrays, with duplicate items in each array. // Used in distinctness tests, in contrast to relying on a Select predicate to generate duplicate items. public static IEnumerable<object[]> UnionSourceMultipleData(int[] counts) { foreach (int leftCount in counts.Cast<int>()) { ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel(); foreach (int rightCount in new int[] { 0, 1, Math.Max(DuplicateFactor, leftCount / 2), Math.Max(DuplicateFactor, leftCount) }) { int rightStart = leftCount - Math.Min(leftCount, rightCount) / 2; ParallelQuery<int> right = Enumerable.Range(0, rightCount * DuplicateFactor).Select(x => x % rightCount + rightStart).ToArray().AsParallel(); yield return new object[] { left, leftCount, right, rightCount, Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2 }; } } } // // Union // [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount); foreach (int i in leftQuery.Union(rightQuery)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; foreach (int i in leftQuery.Union(rightQuery)) { Assert.Equal(seen++, i); } Assert.Equal(leftCount + rightCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_FirstOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount); int seen = 0; foreach (int i in leftQuery.Union(rightQuery)) { if (i < leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_FirstOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_SecondOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Union(rightQuery)) { if (i >= leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount + rightCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_SecondOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount); Assert.All(leftQuery.Union(rightQuery).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; Assert.All(leftQuery.Union(rightQuery).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(leftCount + rightCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_FirstOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount); int seen = 0; Assert.All(leftQuery.Union(rightQuery).ToList(), x => { if (x < leftCount) Assert.Equal(seen++, x); else seenUnordered.Add(x); }); Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_FirstOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_SecondOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; Assert.All(leftQuery.Union(rightQuery).ToList(), x => { if (x >= leftCount) Assert.Equal(seen++, x); else seenUnordered.Add(x); }); Assert.Equal(leftCount + rightCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_SecondOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount); foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; int seen = 0; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { Assert.Equal(seen++, i); } Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_FirstOrdered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, expectedCount - leftCount); int seen = 0; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { if (i < leftCount) { Assert.Equal(seen++, i); } else { Assert.Equal(leftCount, seen); seenUnordered.Add(i); } } seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_FirstOrdered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_SecondOrdered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { if (i >= leftCount) { seenUnordered.AssertComplete(); Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_SecondOrdered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount); Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered_Distinct_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; int seen = 0; Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Distinct_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { // The difference between this test and the previous, is that it's not possible to // get non-unique results from ParallelEnumerable.Range()... // Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar, // or via a comparator that considers some elements equal. IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(leftQuery.Union(rightQuery), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { int seen = 0; Assert.All(leftQuery.AsOrdered().Union(rightQuery.AsOrdered()), x => Assert.Equal(seen++, x)); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_FirstOrdered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, count - leftCount); int seen = 0; foreach (int i in leftQuery.AsOrdered().Union(rightQuery)) { if (i < leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_FirstOrdered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_FirstOrdered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_SecondOrdered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Union(rightQuery.AsOrdered())) { if (i >= leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(count, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_SecondOrdered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_SecondOrdered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Fact] public static void Union_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1))); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1), null)); #pragma warning restore 618 } [Fact] public static void Union_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1))); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Union(null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Union(null, EqualityComparer<int>.Default)); } } }
#region Header // // CmdListMarks.cs - list all door marks // // Copyright (C) 2009-2021 by Jeremy Tammik, // Autodesk Inc. All rights reserved. // // Keywords: The Building Coder Revit API C# .NET add-in. // #endregion // Header #region Namespaces using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; #endregion // Namespaces namespace BuildingCoder { [Transaction(TransactionMode.Manual)] internal class CmdListMarks : IExternalCommand { private const string _the_answer = "42"; private static readonly bool _modify_existing_marks = true; public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { var app = commandData.Application; var uidoc = app.ActiveUIDocument; var doc = uidoc.Document; //Autodesk.Revit.Creation.Application creApp = app.Application.Create; //Autodesk.Revit.Creation.Document creDoc = doc.Create; var doors = Util.GetElementsOfType(doc, typeof(FamilyInstance), BuiltInCategory.OST_Doors); var n = doors.Count(); Debug.Print("{0} door{1} found.", n, Util.PluralSuffix(n)); if (0 < n) { var marks = new Dictionary<string, List<Element>>(); foreach (FamilyInstance door in doors) { var mark = door.get_Parameter( BuiltInParameter.ALL_MODEL_MARK) .AsString(); if (!marks.ContainsKey(mark)) marks.Add(mark, new List<Element>()); marks[mark].Add(door); } var keys = new List<string>( marks.Keys); keys.Sort(); n = keys.Count; Debug.Print("{0} door mark{1} found{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); foreach (var mark in keys) { n = marks[mark].Count; Debug.Print(" {0}: {1} door{2}", mark, n, Util.PluralSuffix(n)); } } n = 0; // count how many elements are modified if (_modify_existing_marks) { using var tx = new Transaction(doc); tx.Start("Modify Existing Door Marks"); //ElementSet els = uidoc.Selection.Elements; // 2014 var ids = uidoc.Selection .GetElementIds(); // 2015 //foreach( Element e in els ) // 2014 foreach (var id in ids) // 2015 { var e = doc.GetElement(id); // 2015 if (e is FamilyInstance && null != e.Category && (int) BuiltInCategory.OST_Doors == e.Category.Id.IntegerValue) { e.get_Parameter( BuiltInParameter.ALL_MODEL_MARK) .Set(_the_answer); ++n; } } tx.Commit(); } // return Succeeded only if we wish to commit // the transaction to modify the database: // //return 0 < n // ? Result.Succeeded // : Result.Failed; // // That was only useful before the introduction // of the manual and read-only transaction modes. return Result.Succeeded; } /* public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; Element e; int num = 1; ElementIterator it = doc.Elements; while( it.MoveNext() ) { e = it.Current as Element; try { // get the BuiltInParameter.ALL_MODEL_MARK paremeter. // If the element does not have this paremeter, // get_Parameter method returns null: Parameter p = e.get_Parameter( BuiltInParameter.ALL_MODEL_MARK ); if( p != null ) { // we found an element with the // BuiltInParameter.ALL_MODEL_MARK // parameter. Change the value and // increment our value: p.Set( num.ToString() ); ++num; } } catch( Exception ex ) { Util.ErrorMsg( "Exception: " + ex.Message ); } } doc.EndTransaction(); return Result.Succeeded; } /// <summary> /// Retrieve all elements in the current active document /// having a non-empty value for the given parameter. /// </summary> static int GetElementsWithParameter( List<Element> elements, BuiltInParameter bip, Application app ) { Document doc = app.ActiveUIDocument.Document; Autodesk.Revit.Creation.Application a = app.Create; Filter f = a.Filter.NewParameterFilter( bip, CriteriaFilterType.NotEqual, "" ); return doc.get_Elements( f, elements ); } */ /// <summary> /// Set the 'Mark' parameter value to sequential /// numbers on all structural framing elements. /// https://forums.autodesk.com/t5/revit-api-forum/set-different-value-to-a-set-of-elements/td-p/8004141 /// </summary> private void NumberStructuralFraming(Document doc) { var beams = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_StructuralFraming) .WhereElementIsNotElementType(); using var t = new Transaction(doc); t.Start("Renumber marks"); var mark_number = 3; foreach (FamilyInstance beam in beams) { var p = beam.get_Parameter( BuiltInParameter.ALL_MODEL_MARK); p.Set((mark_number++).ToString()); } t.Commit(); } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Windows.Forms; using ESRI.ArcGIS.Analyst3D; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.GlobeCore; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS; namespace GlobeNavigation { /// <summary> /// Summary description for Form1. /// </summary> public class Navigation : System.Windows.Forms.Form { internal System.Windows.Forms.TrackBar TrackBar1; public System.Windows.Forms.CheckBox chkSpin; public System.Windows.Forms.RadioButton optTools1; public System.Windows.Forms.RadioButton optTools0; public System.Windows.Forms.Button cmdLoadDocument; public System.Windows.Forms.Button cmdZoomOut; public System.Windows.Forms.Button cmdZoomIn; public System.Windows.Forms.Button cmdFullExtent; public System.Windows.Forms.Label Label1; public System.Windows.Forms.Label lblNavigate; public System.Windows.Forms.Label lblZoom; public System.Windows.Forms.Label lblLoad; private System.Windows.Forms.OpenFileDialog openFileDialog1; private ISceneViewer m_ActiveView; private ICamera m_Camera; private IPoint m_pMousePos = new PointClass(); private bool m_bMouseDown; private bool m_bZooming = false; private double m_dSpinSpeed = 0; private double m_dZoom; const double cMinZoom = 1.00002; const double cMaxZoom = 1.1; const double cDistanceZoomLimit = 200.0; private ESRI.ArcGIS.Controls.AxGlobeControl axGlobeControl1; private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Navigation() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { //Release COM objects, check in extension and shutdown ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown(); if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Navigation)); this.TrackBar1 = new System.Windows.Forms.TrackBar(); this.chkSpin = new System.Windows.Forms.CheckBox(); this.optTools1 = new System.Windows.Forms.RadioButton(); this.optTools0 = new System.Windows.Forms.RadioButton(); this.cmdLoadDocument = new System.Windows.Forms.Button(); this.cmdZoomOut = new System.Windows.Forms.Button(); this.cmdZoomIn = new System.Windows.Forms.Button(); this.cmdFullExtent = new System.Windows.Forms.Button(); this.Label1 = new System.Windows.Forms.Label(); this.lblNavigate = new System.Windows.Forms.Label(); this.lblZoom = new System.Windows.Forms.Label(); this.lblLoad = new System.Windows.Forms.Label(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.axGlobeControl1 = new ESRI.ArcGIS.Controls.AxGlobeControl(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); ((System.ComponentModel.ISupportInitialize)(this.TrackBar1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axGlobeControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); this.SuspendLayout(); // // TrackBar1 // this.TrackBar1.Location = new System.Drawing.Point(440, 432); this.TrackBar1.Name = "TrackBar1"; this.TrackBar1.Size = new System.Drawing.Size(104, 45); this.TrackBar1.TabIndex = 26; this.TrackBar1.Scroll += new System.EventHandler(this.TrackBar1_Scroll); // // chkSpin // this.chkSpin.BackColor = System.Drawing.SystemColors.Control; this.chkSpin.Cursor = System.Windows.Forms.Cursors.Default; this.chkSpin.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.chkSpin.ForeColor = System.Drawing.SystemColors.ControlText; this.chkSpin.Location = new System.Drawing.Point(456, 408); this.chkSpin.Name = "chkSpin"; this.chkSpin.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkSpin.Size = new System.Drawing.Size(57, 17); this.chkSpin.TabIndex = 25; this.chkSpin.Text = "Spin"; this.chkSpin.Click += new System.EventHandler(this.chkSpin_Click); // // optTools1 // this.optTools1.Appearance = System.Windows.Forms.Appearance.Button; this.optTools1.BackColor = System.Drawing.SystemColors.Control; this.optTools1.Cursor = System.Windows.Forms.Cursors.Default; this.optTools1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.optTools1.ForeColor = System.Drawing.SystemColors.ControlText; this.optTools1.Location = new System.Drawing.Point(448, 328); this.optTools1.Name = "optTools1"; this.optTools1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.optTools1.Size = new System.Drawing.Size(81, 25); this.optTools1.TabIndex = 20; this.optTools1.TabStop = true; this.optTools1.Text = "Zoom In/Out"; this.optTools1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.optTools1.Click += new System.EventHandler(this.MixedControls_Click); // // optTools0 // this.optTools0.Appearance = System.Windows.Forms.Appearance.Button; this.optTools0.BackColor = System.Drawing.SystemColors.Control; this.optTools0.Cursor = System.Windows.Forms.Cursors.Default; this.optTools0.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.optTools0.ForeColor = System.Drawing.SystemColors.ControlText; this.optTools0.Location = new System.Drawing.Point(448, 288); this.optTools0.Name = "optTools0"; this.optTools0.RightToLeft = System.Windows.Forms.RightToLeft.No; this.optTools0.Size = new System.Drawing.Size(81, 25); this.optTools0.TabIndex = 19; this.optTools0.TabStop = true; this.optTools0.Text = "Navigate"; this.optTools0.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.optTools0.Click += new System.EventHandler(this.MixedControls_Click); // // cmdLoadDocument // this.cmdLoadDocument.BackColor = System.Drawing.SystemColors.Control; this.cmdLoadDocument.Cursor = System.Windows.Forms.Cursors.Default; this.cmdLoadDocument.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.cmdLoadDocument.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdLoadDocument.Location = new System.Drawing.Point(456, 48); this.cmdLoadDocument.Name = "cmdLoadDocument"; this.cmdLoadDocument.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdLoadDocument.Size = new System.Drawing.Size(67, 25); this.cmdLoadDocument.TabIndex = 18; this.cmdLoadDocument.Text = "Load ..."; this.cmdLoadDocument.Click += new System.EventHandler(this.cmdLoadDocument_Click); // // cmdZoomOut // this.cmdZoomOut.BackColor = System.Drawing.SystemColors.Control; this.cmdZoomOut.Cursor = System.Windows.Forms.Cursors.Default; this.cmdZoomOut.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.cmdZoomOut.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdZoomOut.Location = new System.Drawing.Point(440, 168); this.cmdZoomOut.Name = "cmdZoomOut"; this.cmdZoomOut.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdZoomOut.Size = new System.Drawing.Size(99, 25); this.cmdZoomOut.TabIndex = 17; this.cmdZoomOut.Text = "Fixed Zoom Out"; this.cmdZoomOut.Click += new System.EventHandler(this.cmdZoomOut_Click); // // cmdZoomIn // this.cmdZoomIn.BackColor = System.Drawing.SystemColors.Control; this.cmdZoomIn.Cursor = System.Windows.Forms.Cursors.Default; this.cmdZoomIn.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.cmdZoomIn.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdZoomIn.Location = new System.Drawing.Point(440, 136); this.cmdZoomIn.Name = "cmdZoomIn"; this.cmdZoomIn.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdZoomIn.Size = new System.Drawing.Size(99, 25); this.cmdZoomIn.TabIndex = 16; this.cmdZoomIn.Text = "Fixed Zoom In"; this.cmdZoomIn.Click += new System.EventHandler(this.cmdZoomIn_Click); // // cmdFullExtent // this.cmdFullExtent.BackColor = System.Drawing.SystemColors.Control; this.cmdFullExtent.Cursor = System.Windows.Forms.Cursors.Default; this.cmdFullExtent.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.cmdFullExtent.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdFullExtent.Location = new System.Drawing.Point(440, 200); this.cmdFullExtent.Name = "cmdFullExtent"; this.cmdFullExtent.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdFullExtent.Size = new System.Drawing.Size(99, 25); this.cmdFullExtent.TabIndex = 15; this.cmdFullExtent.Text = "Full Extent"; this.cmdFullExtent.Click += new System.EventHandler(this.cmdFullExtent_Click); // // Label1 // this.Label1.BackColor = System.Drawing.SystemColors.Control; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Label1.ForeColor = System.Drawing.SystemColors.Highlight; this.Label1.Location = new System.Drawing.Point(440, 360); this.Label1.Name = "Label1"; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.Size = new System.Drawing.Size(97, 49); this.Label1.TabIndex = 24; this.Label1.Text = "Control the spin speed with the slider."; // // lblNavigate // this.lblNavigate.BackColor = System.Drawing.SystemColors.Control; this.lblNavigate.Cursor = System.Windows.Forms.Cursors.Default; this.lblNavigate.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblNavigate.ForeColor = System.Drawing.SystemColors.Highlight; this.lblNavigate.Location = new System.Drawing.Point(440, 232); this.lblNavigate.Name = "lblNavigate"; this.lblNavigate.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblNavigate.Size = new System.Drawing.Size(105, 49); this.lblNavigate.TabIndex = 23; this.lblNavigate.Text = "Use the option buttons to select a navigation tool. "; // // lblZoom // this.lblZoom.BackColor = System.Drawing.SystemColors.Control; this.lblZoom.Cursor = System.Windows.Forms.Cursors.Default; this.lblZoom.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblZoom.ForeColor = System.Drawing.SystemColors.Highlight; this.lblZoom.Location = new System.Drawing.Point(440, 80); this.lblZoom.Name = "lblZoom"; this.lblZoom.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblZoom.Size = new System.Drawing.Size(104, 49); this.lblZoom.TabIndex = 22; this.lblZoom.Text = "Use the buttons to navigate the Globe data."; // // lblLoad // this.lblLoad.BackColor = System.Drawing.SystemColors.Control; this.lblLoad.Cursor = System.Windows.Forms.Cursors.Default; this.lblLoad.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblLoad.ForeColor = System.Drawing.SystemColors.Highlight; this.lblLoad.Location = new System.Drawing.Point(440, 8); this.lblLoad.Name = "lblLoad"; this.lblLoad.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblLoad.Size = new System.Drawing.Size(97, 33); this.lblLoad.TabIndex = 21; this.lblLoad.Text = "Browse to a 3dd file to load."; // // axGlobeControl1 // this.axGlobeControl1.Location = new System.Drawing.Point(8, 8); this.axGlobeControl1.Name = "axGlobeControl1"; this.axGlobeControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axGlobeControl1.OcxState"))); this.axGlobeControl1.Size = new System.Drawing.Size(424, 464); this.axGlobeControl1.TabIndex = 27; this.axGlobeControl1.OnMouseDown += new ESRI.ArcGIS.Controls.IGlobeControlEvents_Ax_OnMouseDownEventHandler(this.axGlobeControl1_OnMouseDown); this.axGlobeControl1.OnMouseMove += new ESRI.ArcGIS.Controls.IGlobeControlEvents_Ax_OnMouseMoveEventHandler(this.axGlobeControl1_OnMouseMove); this.axGlobeControl1.OnMouseUp += new ESRI.ArcGIS.Controls.IGlobeControlEvents_Ax_OnMouseUpEventHandler(this.axGlobeControl1_OnMouseUp); // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(216, 24); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(200, 50); this.axLicenseControl1.TabIndex = 28; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(552, 478); this.Controls.Add(this.axLicenseControl1); this.Controls.Add(this.axGlobeControl1); this.Controls.Add(this.TrackBar1); this.Controls.Add(this.chkSpin); this.Controls.Add(this.optTools1); this.Controls.Add(this.optTools0); this.Controls.Add(this.cmdLoadDocument); this.Controls.Add(this.cmdZoomOut); this.Controls.Add(this.cmdZoomIn); this.Controls.Add(this.cmdFullExtent); this.Controls.Add(this.Label1); this.Controls.Add(this.lblNavigate); this.Controls.Add(this.lblZoom); this.Controls.Add(this.lblLoad); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.TrackBar1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axGlobeControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if (!RuntimeManager.Bind(ProductCode.Engine)) { if (!RuntimeManager.Bind(ProductCode.Desktop)) { MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down."); return; } } Application.Run(new Navigation()); } private void Form1_Load(object sender, System.EventArgs e) { //Initialize member variables m_ActiveView = axGlobeControl1.GlobeDisplay.ActiveViewer; m_Camera = m_ActiveView.Camera; } private void cmdLoadDocument_Click(object sender, System.EventArgs e) { //Open a file dialog for selecting map documents openFileDialog1.Title = "Globe Documents"; openFileDialog1.DefaultExt = ".3dd"; openFileDialog1.Filter = "Globe Document(*.3dd)|*.3dd"; openFileDialog1.ShowDialog(); //Check a file is selected and that it's a valid Globe document //before attempting to load it if (openFileDialog1.FileName != "") { if (axGlobeControl1.Check3dFile(openFileDialog1.FileName) == true) { axGlobeControl1.Load3dFile(openFileDialog1.FileName); } else { MessageBox.Show("Cannot load " + openFileDialog1.FileName); } } } private void cmdFullExtent_Click(object sender, System.EventArgs e) { IGlobeCamera camera = (IGlobeCamera) m_Camera; //Make sure that the camera is using global coordinates camera.OrientationMode = esriGlobeCameraOrientationMode.esriGlobeCameraOrientationGlobal; //Point the camera at 0,0 in lat,long - this is the default target IPoint target = new PointClass(); target.PutCoords(0.0, 0.0); target.Z = 0.0; m_Camera.Target = target; //Reset the camera to its default values m_Camera.Azimuth = 140; m_Camera.Inclination = 45; m_Camera.ViewingDistance = 4.0; m_Camera.ViewFieldAngle = 30.0; m_Camera.RollAngle = 0.0; m_Camera.RecalcUp(); m_ActiveView.Redraw(false); } private void cmdZoomIn_Click(object sender, System.EventArgs e) { //Reset the camera field of view angle to 0.9 of its previous value double vfa = m_Camera.ViewFieldAngle; m_Camera.ViewFieldAngle = vfa * 0.9; m_ActiveView.Redraw(false); } private void cmdZoomOut_Click(object sender, System.EventArgs e) { //Reset the camera field of view angle to 1.1 times its previous value double vfa = m_Camera.ViewFieldAngle; m_Camera.ViewFieldAngle = vfa * 1.1; m_ActiveView.Redraw(false); } private void CalculateMoveFactors(double dist) { bool bIsAtCenter; int indexGlobe; //See if the camera is pointing at the center of the globe. IGlobeViewer globeViewer = (IGlobeViewer) m_ActiveView; globeViewer.GetIsTargetAtCenter(out bIsAtCenter, out indexGlobe); //If the camera is pointing at the center of the globe then the zoom speed //depends on how far away it is, otherwise the zoom factor is fixed. As the //camera approaches the globe surface (where dist = 1) the zoom speed slows //down. The other factors were worked out by trial and error. if (bIsAtCenter == true) { m_dZoom = cMinZoom + (cMaxZoom - cMinZoom) * (dist - 1.0) / 3.0; } else { m_dZoom = 1.1; } } private void chkSpin_Click(object sender, System.EventArgs e) { if (chkSpin.CheckState == CheckState.Checked) { axGlobeControl1.GlobeViewer.StartSpinning(esriGlobeSpinDirection.esriCounterClockwise); axGlobeControl1.GlobeViewer.SpinSpeed = 3; TrackBar1.Enabled = true; m_dSpinSpeed = 3; } else { axGlobeControl1.GlobeViewer.StopSpinning(); TrackBar1.Enabled = false; m_dSpinSpeed = 0; } } private void TrackBar1_Scroll(object sender, System.EventArgs e) { //The globe should increase its spin speed with every increment greater than //5 and decrease it for every increment less. int sliderPos = (TrackBar1.Value - 5); if (sliderPos == 0) { m_dSpinSpeed = 3; } else if (sliderPos > 0) { m_dSpinSpeed = 3 * (sliderPos + 1); } else { m_dSpinSpeed = 3 / (1 - sliderPos); } axGlobeControl1.GlobeViewer.SpinSpeed = m_dSpinSpeed; } private void MixedControls_Click(object sender, System.EventArgs e) { RadioButton b = (RadioButton) sender; //Set current tool switch (b.Name) { case "optTools0": m_bZooming = false; axGlobeControl1.Navigate = true; axGlobeControl1.MousePointer = esriControlsMousePointer.esriPointerDefault; break; case "optTools1": m_bZooming = true; axGlobeControl1.Navigate = false; axGlobeControl1.MousePointer = esriControlsMousePointer.esriPointerZoom; break; } } private void axGlobeControl1_OnMouseUp(object sender, ESRI.ArcGIS.Controls.IGlobeControlEvents_OnMouseUpEvent e) { //Cancel the zoom operation m_bMouseDown = false; //Navigate can cancel spin - make sure it starts again if (m_dSpinSpeed > 0) { axGlobeControl1.GlobeViewer.StartSpinning(esriGlobeSpinDirection.esriCounterClockwise); } } private void axGlobeControl1_OnMouseMove(object sender, ESRI.ArcGIS.Controls.IGlobeControlEvents_OnMouseMoveEvent e) { if (m_bMouseDown == false) { return; } //If we're in a zoom operation then //Get the difference in mouse position between this and the last one double dx = e.x - m_pMousePos.X; double dy = e.y - m_pMousePos.Y; if ((dx == 0) & (dy == 0)) { return; } //Work out how far the observer is currently from the globe and use this //distance to determine how far to move IPoint observer = m_Camera.Observer; double zObs; double xObs; double yObs; double dist; observer.QueryCoords(out xObs, out yObs); zObs = observer.Z; dist = System.Math.Sqrt(xObs * xObs + yObs * yObs + zObs * zObs); CalculateMoveFactors(dist); //Zoom out and in as the mouse moves up and down the screen respectively if ((dy < 0) & (dist < cDistanceZoomLimit)) { m_Camera.Zoom(m_dZoom); } else if (dy > 0) { m_Camera.Zoom((1 / m_dZoom)); } m_pMousePos.X = e.x; m_pMousePos.Y = e.y; m_ActiveView.Redraw(false); } private void axGlobeControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IGlobeControlEvents_OnMouseDownEvent e) { //Mouse down should initiate a zoom only if the Zoom check box is checked if (m_bZooming == false) { return; } if (e.button == 1) { m_bMouseDown = true; m_pMousePos.X = e.x; m_pMousePos.Y = e.y; } } } }
// // 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.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.RemoteApp; namespace Microsoft.WindowsAzure.Management.RemoteApp { /// <summary> /// RemoteApp user disk operations. /// </summary> internal partial class UserDiskOperations : IServiceOperations<RemoteAppManagementClient>, IUserDiskOperations { /// <summary> /// Initializes a new instance of the UserDiskOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal UserDiskOperations(RemoteAppManagementClient client) { this._client = client; } private RemoteAppManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.RemoteAppManagementClient. /// </summary> public RemoteAppManagementClient Client { get { return this._client; } } /// <summary> /// Copy user disk from one collection to the other and keep the source /// user disk. /// </summary> /// <param name='srcCollectionName'> /// Required. The source collection name. /// </param> /// <param name='dstCollectionName'> /// Required. The destination collection name. /// </param> /// <param name='userUpn'> /// Required. The user upn. /// </param> /// <param name='overwriteExistingUserDisk'> /// Required. A flag denoting if the request is to overwrite the /// existing user disk /// </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> CopyAsync(string srcCollectionName, string dstCollectionName, string userUpn, bool overwriteExistingUserDisk, CancellationToken cancellationToken) { // Validate if (srcCollectionName == null) { throw new ArgumentNullException("srcCollectionName"); } if (dstCollectionName == null) { throw new ArgumentNullException("dstCollectionName"); } if (userUpn == null) { throw new ArgumentNullException("userUpn"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("srcCollectionName", srcCollectionName); tracingParameters.Add("dstCollectionName", dstCollectionName); tracingParameters.Add("userUpn", userUpn); tracingParameters.Add("overwriteExistingUserDisk", overwriteExistingUserDisk); TracingAdapter.Enter(invocationId, this, "CopyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/"; if (this.Client.RdfeNamespace != null) { url = url + Uri.EscapeDataString(this.Client.RdfeNamespace); } url = url + "/accounts/desktops/"; url = url + Uri.EscapeDataString(srcCollectionName); url = url + "/CopyUserDiskAsync"; List<string> queryParameters = new List<string>(); queryParameters.Add("user=" + Uri.EscapeDataString(userUpn)); queryParameters.Add("dstCollectionName=" + Uri.EscapeDataString(dstCollectionName)); queryParameters.Add("overwrite=" + Uri.EscapeDataString(overwriteExistingUserDisk.ToString().ToLower())); queryParameters.Add("api-version=2014-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json; charset=utf-8"); httpRequest.Headers.Add("x-ms-version", "2014-08-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> /// Deletes the given user disk. /// </summary> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='userUpn'> /// Required. The user upn. /// </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 collectionName, string userUpn, CancellationToken cancellationToken) { // Validate if (collectionName == null) { throw new ArgumentNullException("collectionName"); } if (userUpn == null) { throw new ArgumentNullException("userUpn"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("collectionName", collectionName); tracingParameters.Add("userUpn", userUpn); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/"; if (this.Client.RdfeNamespace != null) { url = url + Uri.EscapeDataString(this.Client.RdfeNamespace); } url = url + "/desktops/"; url = url + Uri.EscapeDataString(collectionName); url = url + "/user/"; url = url + Uri.EscapeDataString(userUpn); url = url + "/DeleteUserDiskAsync"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json; charset=utf-8"); httpRequest.Headers.Add("x-ms-version", "2014-08-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(); } } } } }
// e2a8473c-43d2-4d2c-80a8-bc3ea46e53a0 #pragma warning disable 219 using System; using Neutrino.Unity3D; namespace Neutrino { public class Effect_Water_Stream : NeutrinoRenderer { public class Model : EffectModel { public class Emitter_DefaultEmitter : EmitterModel { public class ParticleImpl : Particle { public float _lifetime; public _math.vec3 _Position; public _math.vec3 _Velocity; public float _Angle; public float _Tex__index; public float _Rot__speed; public override _math.vec2 origin() { return _math.vec2_(0.5F,0.5F); } public override float angle() { return _Angle; } public override _math.quat rotation() { return _math.quat_(1, 0, 0, 0); } public float size1_; public override float size1() { return size1_; } public override _math.vec2 size2() { return _math.vec2_(0, 0); } public override _math.vec3 color() { return _math.vec3_(1F,1F,1F); } public float alpha_; public override float alpha() { return alpha_; } public override float gridIndex() { return _Tex__index; } public override AttachedEmitter[] attachedEmitters() { return null; } } public class EmitterData { } public class GeneratorImpl : GeneratorPeriodic.Impl { public float burst() { return 1F; } public float? fixedTime() { return null; } public float? fixedShots() { return null; } public float startPhase() { return 1F; } public float rate() { return 25F; } } _math.vec2 [][,] _path = { new _math.vec2[,] {{_math.vec2_(400F,-40F)},{_math.vec2_(401F,36F)},{_math.vec2_(401F,36F)}} }; float [][][] _plot = { new float[][] { new float[]{ 1F,2F,2F }} }; float [][][] _plota = { new float[][] { new float[]{ 1F,0F,0F }} }; public class ConstructorImpl : ConstructorQuads.Impl { public ConstructorQuads.RotationType rotationType() { return ConstructorQuads.RotationType.Faced; } public ConstructorQuads.SizeType sizeType() { return ConstructorQuads.SizeType.Quad; } public ConstructorQuads.TexMapType texMapType() { return ConstructorQuads.TexMapType.Grid; } public _math.vec2 gridSize() { return _math.vec2_(2, 2); } public ushort renderStyleIndex() { return 0; } } public override void updateEmitter(Emitter emitter) { EmitterData emitterData = (EmitterData)emitter.data(); GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator(); GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl(); } public override void initParticle(Emitter emitter, Particle particle) { ParticleImpl particleImpl = (ParticleImpl)particle; float dt = 0; EmitterData emitterData = (EmitterData)emitter.data(); GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator(); GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl(); particleImpl._lifetime = 0F; _math.vec3 value_ = _math.vec3_(0F, 0F, 0F); particleImpl._Position = _math.applyv3quat_(value_, emitter.rotation()); particleImpl._Position = _math.addv3_(particleImpl._Position, emitter.position()); float rnd_ = 0F + emitter.random()() * (1F - 0F); float _path_in = _math.clamp_(rnd_, 0, 1); _math.PathRes _path_srch = _math.pathRes(0,(_path_in-0F)*1F); _math.vec2 _path_pos; _math.pathLerp1(out _path_pos, this._path[_path_srch.s], _path_srch.i); _math.vec3 conv3d_ = _math.vec3_(_path_pos.x, _path_pos.y, 0F); particleImpl._Velocity = _math.applyv3quat_(conv3d_, emitter.rotation()); particleImpl._Velocity = _math.addv3_(particleImpl._Velocity, emitter.velocity()); float rnd_a = 0F + emitter.random()() * (360F - 0F); particleImpl._Angle = rnd_a; float rnd_b = 0F + emitter.random()() * (4F - 0F); particleImpl._Tex__index = rnd_b; float rnd_c = -180F + emitter.random()() * (180F - -180F); particleImpl._Rot__speed = rnd_c; particle.position_ = particleImpl._Position; } public override void initBurstParticle(Emitter emitter, Particle particle) { ParticleImpl particleImpl = (ParticleImpl)particle; float dt = 0; EmitterData emitterData = (EmitterData)emitter.data(); GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator(); GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl(); particleImpl._lifetime = 0F; _math.vec3 value_ = _math.vec3_(0F, 0F, 0F); particleImpl._Position = _math.applyv3quat_(value_, emitter.rotation()); particleImpl._Position = _math.addv3_(particleImpl._Position, emitter.position()); float rnd_ = 0F + emitter.random()() * (1F - 0F); float _path_in = _math.clamp_(rnd_, 0, 1); _math.PathRes _path_srch = _math.pathRes(0,(_path_in-0F)*1F); _math.vec2 _path_pos; _math.pathLerp1(out _path_pos, this._path[_path_srch.s], _path_srch.i); _math.vec3 conv3d_ = _math.vec3_(_path_pos.x, _path_pos.y, 0F); particleImpl._Velocity = _math.applyv3quat_(conv3d_, emitter.rotation()); particleImpl._Velocity = _math.addv3_(particleImpl._Velocity, emitter.velocity()); float rnd_a = 0F + emitter.random()() * (360F - 0F); particleImpl._Angle = rnd_a; float rnd_b = 0F + emitter.random()() * (4F - 0F); particleImpl._Tex__index = rnd_b; float rnd_c = -180F + emitter.random()() * (180F - -180F); particleImpl._Rot__speed = rnd_c; particle.position_ = particleImpl._Position; } public override void updateParticle(Emitter emitter, Particle particle, float dt) { ParticleImpl particleImpl = (ParticleImpl)particle; EmitterData emitterData = (EmitterData)emitter.data(); GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator(); GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl(); particleImpl._lifetime += dt; _math.vec3 value_ = _math.vec3_(0F, -300F, 0F); _math.vec3 fmove_fs = value_; _math.vec3 fmove_vs = _math.vec3_(0F,0F,0F); float fmove_dtl = dt; _math.vec3 fmove_v = particleImpl._Velocity; _math.vec3 fmove_p = particleImpl._Position; while (fmove_dtl > 0.0001F) { float fmove_dtp = fmove_dtl; _math.vec3 fmove_fsd = fmove_fs; _math.vec3 fmove_rw = _math.subv3_(fmove_vs, fmove_v); float fmove_rwl = _math.lengthv3sq_(fmove_rw); if (fmove_rwl > 0.0001F) { fmove_rwl = (float)Math.Sqrt(fmove_rwl); _math.vec3 fmove_rwn = _math.divv3scalar_(fmove_rw, fmove_rwl); float fmove_df = 0.01F * 1F * fmove_rwl; if (fmove_df * fmove_dtp > 0.2F) fmove_dtp = 0.2F / fmove_df; _math.addv3(out fmove_fsd, fmove_fsd, _math.mulv3scalar_(fmove_rwn, fmove_rwl * fmove_df)); } _math.addv3(out fmove_v, fmove_v, _math.mulv3scalar_(fmove_fsd, fmove_dtp)); _math.addv3(out fmove_p, fmove_p, _math.mulv3scalar_(fmove_v, fmove_dtp)); fmove_dtl -= fmove_dtp; } particleImpl._Position = fmove_p; particleImpl._Velocity = fmove_v; float move_ = particleImpl._Angle + particleImpl._Rot__speed * dt; particleImpl._Angle = move_; particle.position_ = particleImpl._Position; float value_a = 2F; if (particleImpl._lifetime > value_a) { particle.dead_ = true; } float value_b = 30F; float _plot_out; float _plot_in0=(particleImpl._lifetime<0F?0F:(particleImpl._lifetime>1F?1F:particleImpl._lifetime)); _math.PathRes _plot_srch0 = _math.pathRes(0,(_plot_in0-0F)*1F); _math.funcLerp(out _plot_out, this._plot[0][_plot_srch0.s],_plot_srch0.i); float expr_ = (value_b * _plot_out); float expr_a = (particleImpl._lifetime / value_a); float _plota_out; float _plota_in0=(expr_a<0F?0F:(expr_a>1F?1F:expr_a)); _math.PathRes _plota_srch0 = _math.pathRes(0,(_plota_in0-0F)*1F); _math.funcLerp(out _plota_out, this._plota[0][_plota_srch0.s],_plota_srch0.i); particleImpl.size1_ = expr_; particleImpl.alpha_ = _plota_out; } public Emitter_DefaultEmitter() { generatorCreator_ = (Emitter emitter) => { return new GeneratorPeriodic(emitter, new GeneratorImpl()); }; constructorCreator_ = (Emitter emitter) => { return new ConstructorQuads(emitter, new ConstructorImpl()); }; name_ = "DefaultEmitter"; maxNumParticles_ = 100; sorting_ = Emitter.Sorting.OldToYoung; particleCreator_ = (Effect effect) => { return new ParticleImpl(); }; emitterDataCreator_ = () => { return new EmitterData(); }; } } public Model() { textures_ = new string[] { "water2x3_white.png" }; materials_ = new RenderMaterial[] { RenderMaterial.Normal }; renderStyles_ = new RenderStyle[] { new RenderStyle(0,new uint[] {0}) }; frameTime_ = 0.0333333F; presimulateTime_ = 0F; maxNumRenderCalls_ = 100; maxNumParticles_ = 100; emitterModels_ = new EmitterModel[]{ new Emitter_DefaultEmitter() }; activeEmitterModels_ = new uint[] { 0 }; randomGeneratorCreator_ = () => { return _math.rand_; }; } } static Model modelInstance_ = null; public override EffectModel createModel() { if (modelInstance_ == null) modelInstance_ = new Model(); return modelInstance_; } } } #pragma warning restore 219
// // 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.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.DataLake.Analytics; using Microsoft.Azure.Management.DataLake.Analytics.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataLake.Analytics { /// <summary> /// Creates an Azure Data Lake Analytics account management client. /// </summary> public partial class DataLakeAnalyticsManagementClient : ServiceClient<DataLakeAnalyticsManagementClient>, IDataLakeAnalyticsManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private string _userAgentSuffix; /// <summary> /// Gets or sets the additional UserAgent text to be added to the user /// agent header. This is used to further differentiate where requests /// are coming from internally. /// </summary> public string UserAgentSuffix { get { return this._userAgentSuffix; } set { this._userAgentSuffix = value; } } private IDataLakeAnalyticsAccountOperations _dataLakeAnalyticsAccount; /// <summary> /// Operations for managing Data Lake Analytics accounts /// </summary> public virtual IDataLakeAnalyticsAccountOperations DataLakeAnalyticsAccount { get { return this._dataLakeAnalyticsAccount; } } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsManagementClient /// class. /// </summary> public DataLakeAnalyticsManagementClient() : base() { this._dataLakeAnalyticsAccount = new DataLakeAnalyticsAccountOperations(this); this._userAgentSuffix = ""; this._apiVersion = "2015-10-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public DataLakeAnalyticsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public DataLakeAnalyticsManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public DataLakeAnalyticsManagementClient(HttpClient httpClient) : base(httpClient) { this._dataLakeAnalyticsAccount = new DataLakeAnalyticsAccountOperations(this); this._userAgentSuffix = ""; this._apiVersion = "2015-10-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public DataLakeAnalyticsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public DataLakeAnalyticsManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// DataLakeAnalyticsManagementClient instance /// </summary> /// <param name='client'> /// Instance of DataLakeAnalyticsManagementClient to clone to /// </param> protected override void Clone(ServiceClient<DataLakeAnalyticsManagementClient> client) { base.Clone(client); if (client is DataLakeAnalyticsManagementClient) { DataLakeAnalyticsManagementClient clonedClient = ((DataLakeAnalyticsManagementClient)client); clonedClient._userAgentSuffix = this._userAgentSuffix; clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// Parse enum values for type DataLakeAnalyticsAccountState. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static DataLakeAnalyticsAccountState ParseDataLakeAnalyticsAccountState(string value) { if ("active".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountState.Active; } if ("suspended".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountState.Suspended; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type DataLakeAnalyticsAccountState to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string DataLakeAnalyticsAccountStateToString(DataLakeAnalyticsAccountState value) { if (value == DataLakeAnalyticsAccountState.Active) { return "active"; } if (value == DataLakeAnalyticsAccountState.Suspended) { return "suspended"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type DataLakeAnalyticsAccountStatus. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static DataLakeAnalyticsAccountStatus ParseDataLakeAnalyticsAccountStatus(string value) { if ("Failed".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountStatus.Failed; } if ("Creating".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountStatus.Creating; } if ("Running".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountStatus.Running; } if ("Succeeded".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountStatus.Succeeded; } if ("Patching".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountStatus.Patching; } if ("Suspending".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountStatus.Suspending; } if ("Resuming".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountStatus.Resuming; } if ("Deleting".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountStatus.Deleting; } if ("Deleted".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeAnalyticsAccountStatus.Deleted; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type DataLakeAnalyticsAccountStatus to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string DataLakeAnalyticsAccountStatusToString(DataLakeAnalyticsAccountStatus value) { if (value == DataLakeAnalyticsAccountStatus.Failed) { return "Failed"; } if (value == DataLakeAnalyticsAccountStatus.Creating) { return "Creating"; } if (value == DataLakeAnalyticsAccountStatus.Running) { return "Running"; } if (value == DataLakeAnalyticsAccountStatus.Succeeded) { return "Succeeded"; } if (value == DataLakeAnalyticsAccountStatus.Patching) { return "Patching"; } if (value == DataLakeAnalyticsAccountStatus.Suspending) { return "Suspending"; } if (value == DataLakeAnalyticsAccountStatus.Resuming) { return "Resuming"; } if (value == DataLakeAnalyticsAccountStatus.Deleting) { return "Deleting"; } if (value == DataLakeAnalyticsAccountStatus.Deleted) { return "Deleted"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='azureAsyncOperation'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<AzureAsyncOperationResponse> GetLongRunningOperationStatusAsync(string azureAsyncOperation, CancellationToken cancellationToken) { // Validate if (azureAsyncOperation == null) { throw new ArgumentNullException("azureAsyncOperation"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("azureAsyncOperation", azureAsyncOperation); TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + azureAsyncOperation; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { 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 AzureAsyncOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AzureAsyncOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true)); result.Status = statusInstance; } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { Error errorInstance = new Error(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = errorValue["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JToken detailsArray = errorValue["details"]; if (detailsArray != null && detailsArray.Type != JTokenType.Null) { foreach (JToken detailsValue in ((JArray)detailsArray)) { ErrorDetails errorDetailsInstance = new ErrorDetails(); errorInstance.Details.Add(errorDetailsInstance); JToken codeValue2 = detailsValue["code"]; if (codeValue2 != null && codeValue2.Type != JTokenType.Null) { string codeInstance2 = ((string)codeValue2); errorDetailsInstance.Code = codeInstance2; } JToken messageValue2 = detailsValue["message"]; if (messageValue2 != null && messageValue2.Type != JTokenType.Null) { string messageInstance2 = ((string)messageValue2); errorDetailsInstance.Message = messageInstance2; } JToken targetValue2 = detailsValue["target"]; if (targetValue2 != null && targetValue2.Type != JTokenType.Null) { string targetInstance2 = ((string)targetValue2); errorDetailsInstance.Target = targetInstance2; } } } JToken innerErrorValue = errorValue["innerError"]; if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null) { InnerError innerErrorInstance = new InnerError(); errorInstance.InnerError = innerErrorInstance; JToken traceValue = innerErrorValue["trace"]; if (traceValue != null && traceValue.Type != JTokenType.Null) { string traceInstance = ((string)traceValue); innerErrorInstance.Trace = traceInstance; } JToken contextValue = innerErrorValue["context"]; if (contextValue != null && contextValue.Type != JTokenType.Null) { string contextInstance = ((string)contextValue); innerErrorInstance.Context = contextInstance; } } } } } 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) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using Microsoft.Win32; namespace OpenLiveWriter.CoreServices.Settings { public class RegistrySettingsPersister : ISettingsPersister { private RegistryKey rootNode; private string keyName; /// <param name="rootNode">One of the root-level nodes (HKLM, HKCU, etc.)</param> /// <param name="keyName">A relative path from the rootNode to the key for this instance</param> public RegistrySettingsPersister(RegistryKey rootNode, string keyName) { // set members this.rootNode = rootNode; this.keyName = keyName; } #region ISettingsPersister Members public string[] GetNames() { using (RegistryKey key = GetKey(false)) { if (key == null) return null; else return key.GetValueNames(); } } public object Get(string name, Type desiredType, object defaultValue) { object savedValue = null; try { // first try to get it from storage savedValue = Get(name, desiredType); } catch (Exception e) { // Since this could get called frequently, try to only log once if (!haveLoggedFailedRead) { //Debug.Fail("The setting " + name + " could not be retrieved: " + e.ToString()); Trace.WriteLine("The setting " + name + " could not be retrieved: " + e.ToString()); haveLoggedFailedRead = true; } } if (savedValue != null) { // value was successfully retrieved return savedValue; } else { // we want to use the default value and make sure it's persisted if (defaultValue != null) { try { Set(name, defaultValue); } catch { // Since this could get called frequently, try to only log once if (!haveLoggedFailedDefault) { //Debug.Fail("Wasn't able to persist a default value for " + name); Trace.WriteLine("Wasn't able to persist a default value for " + name); haveLoggedFailedDefault = true; } } } // all code paths that do not result in successful retrieval should end up here return defaultValue; } } private bool haveLoggedFailedRead = false; private bool haveLoggedFailedDefault = false; private bool haveLoggedFailedGetKey = false; /// <summary> /// Low-level get (returns null if the value doesn't exist). /// </summary> /// <param name="name">name</param> /// <returns>value (null if not present)</returns> public object Get(string name) { using (RegistryKey key = GetKey(false)) { object obj = key.GetValue(name); // HACK: Roundtripping of serializable objects is broken if this isn't included. // For example, this code would assert: // byte[] inBytes = new byte[] {1,2,3,4,5}; // Set("foo", inBytes); // Set("foo", Get("foo")); // byte[] outBytes = Get("foo", typeof(byte[])); // Trace.Assert(ArrayHelper.Compare(inBytes, outBytes)); if (obj is byte[]) obj = RegistryCodec.SerializableCodec.Deserialize((byte[])obj); return obj; } } /// <summary> /// This used to be public, for symmetry with <c>Set</c>; but it's a bad /// idea to use this method because there is no fallback position if an exception /// occurs when retrieving from the persisted state. The overloaded version /// of this that takes a default value is much safer. /// </summary> protected object Get(string name, Type desiredType) { using (RegistryKey key = GetKey(false)) { if (key == null) return null; object registryData = key.GetValue(name); if (registryData != null) return RegistryCodec.Instance.Decode(registryData, desiredType); else return null; } } public void Set(string name, object val) { // If the value is null, remove the key. Otherwise, set it. if (val == null) Unset(name); else { using (RegistryKey key = GetKey(true)) { if (key != null) { object registryData = RegistryCodec.Instance.Encode(val); key.SetValue(name, registryData); } } } } public void Unset(string name) { using (RegistryKey key = GetKey(true)) { if (key != null) key.DeleteValue(name, false); } } public void UnsetSubSettingsTree(string name) { using (RegistryKey key = GetKey(true)) { if (key != null) key.DeleteSubKeyTree(name); } } public IDisposable BatchUpdate() { return null; } /// <summary> /// Determine whether the specified sub-settings exists /// </summary> /// <param name="subSettingsName">name of sub-settings to check for</param> /// <returns>true if it has them, otherwise false</returns> public bool HasSubSettings(string subSettingsName) { using (RegistryKey key = GetKey(false)) { if (key == null) { return false; } using (RegistryKey subSettingsKey = key.OpenSubKey(subSettingsName)) { return subSettingsKey != null; } } } /// <summary> /// Get a subsetting object that is rooted in the current ISettingsPersister /// </summary> /// <param name="subKeyName">name of subkey</param> /// <returns>settings persister</returns> public ISettingsPersister GetSubSettings(string subSettingsName) { return new RegistrySettingsPersister(this.rootNode, keyName + "\\" + subSettingsName); } /// <summary> /// Enumerate the available sub-settings /// </summary> /// <returns></returns> public string[] GetSubSettings() { using (RegistryKey key = GetKey(false)) { if (key == null) return null; else return key.GetSubKeyNames(); } } /// <summary> /// Dispose the settings persister /// </summary> public void Dispose() { rootNode.Close(); } #endregion /// <summary> /// Gets the base key associated with this instance. /// </summary> protected virtual RegistryKey GetKey(bool writable) { try { if (writable) { return rootNode.CreateSubKey(keyName); } else { // CreateSubKey returns the subkey in read-write mode. We want to // do the creation but return in read-only mode RegistryKey key = rootNode.OpenSubKey(keyName, false); if (key != null) { // key already exists return key; } else { // key does not exist; create it, close it, open it rootNode.CreateSubKey(keyName).Close(); return rootNode.OpenSubKey(keyName, false); } } } catch (Exception) { // Since this could get called frequently, try to only log once if (!haveLoggedFailedGetKey) { if (keyName != null && keyName.IndexOf("XDefMan", StringComparison.OrdinalIgnoreCase) >= 0) Trace.WriteLine("Wasn't able to get key for " + keyName); haveLoggedFailedGetKey = true; } return null; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: A1100Response.txt #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace DolphinServer.ProtoEntity { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class A1100Response { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_A1100Response__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1100Response, global::DolphinServer.ProtoEntity.A1100Response.Builder> internal__static_A1100Response__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static A1100Response() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFBMTEwMFJlc3BvbnNlLnR4dCJoCg1BMTEwMFJlc3BvbnNlEhEKCUVycm9y", "SW5mbxgBIAEoCRIRCglFcnJvckNvZGUYAiABKAUSCwoDVWlkGAMgASgJEg8K", "B01lc3NhZ2UYBCABKAkSEwoLTWVzc2FnZVR5cGUYBSABKAlCHKoCGURvbHBo", "aW5TZXJ2ZXIuUHJvdG9FbnRpdHk=")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_A1100Response__Descriptor = Descriptor.MessageTypes[0]; internal__static_A1100Response__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1100Response, global::DolphinServer.ProtoEntity.A1100Response.Builder>(internal__static_A1100Response__Descriptor, new string[] { "ErrorInfo", "ErrorCode", "Uid", "Message", "MessageType", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class A1100Response : pb::GeneratedMessage<A1100Response, A1100Response.Builder> { private A1100Response() { } private static readonly A1100Response defaultInstance = new A1100Response().MakeReadOnly(); private static readonly string[] _a1100ResponseFieldNames = new string[] { "ErrorCode", "ErrorInfo", "Message", "MessageType", "Uid" }; private static readonly uint[] _a1100ResponseFieldTags = new uint[] { 16, 10, 34, 42, 26 }; public static A1100Response DefaultInstance { get { return defaultInstance; } } public override A1100Response DefaultInstanceForType { get { return DefaultInstance; } } protected override A1100Response ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::DolphinServer.ProtoEntity.Proto.A1100Response.internal__static_A1100Response__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<A1100Response, A1100Response.Builder> InternalFieldAccessors { get { return global::DolphinServer.ProtoEntity.Proto.A1100Response.internal__static_A1100Response__FieldAccessorTable; } } public const int ErrorInfoFieldNumber = 1; private bool hasErrorInfo; private string errorInfo_ = ""; public bool HasErrorInfo { get { return hasErrorInfo; } } public string ErrorInfo { get { return errorInfo_; } } public const int ErrorCodeFieldNumber = 2; private bool hasErrorCode; private int errorCode_; public bool HasErrorCode { get { return hasErrorCode; } } public int ErrorCode { get { return errorCode_; } } public const int UidFieldNumber = 3; private bool hasUid; private string uid_ = ""; public bool HasUid { get { return hasUid; } } public string Uid { get { return uid_; } } public const int MessageFieldNumber = 4; private bool hasMessage; private string message_ = ""; public bool HasMessage { get { return hasMessage; } } public string Message { get { return message_; } } public const int MessageTypeFieldNumber = 5; private bool hasMessageType; private string messageType_ = ""; public bool HasMessageType { get { return hasMessageType; } } public string MessageType { get { return messageType_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _a1100ResponseFieldNames; if (hasErrorInfo) { output.WriteString(1, field_names[1], ErrorInfo); } if (hasErrorCode) { output.WriteInt32(2, field_names[0], ErrorCode); } if (hasUid) { output.WriteString(3, field_names[4], Uid); } if (hasMessage) { output.WriteString(4, field_names[2], Message); } if (hasMessageType) { output.WriteString(5, field_names[3], MessageType); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasErrorInfo) { size += pb::CodedOutputStream.ComputeStringSize(1, ErrorInfo); } if (hasErrorCode) { size += pb::CodedOutputStream.ComputeInt32Size(2, ErrorCode); } if (hasUid) { size += pb::CodedOutputStream.ComputeStringSize(3, Uid); } if (hasMessage) { size += pb::CodedOutputStream.ComputeStringSize(4, Message); } if (hasMessageType) { size += pb::CodedOutputStream.ComputeStringSize(5, MessageType); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static A1100Response ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1100Response ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1100Response ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1100Response ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1100Response ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1100Response ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static A1100Response ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static A1100Response ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static A1100Response ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1100Response ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private A1100Response MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(A1100Response prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<A1100Response, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(A1100Response cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private A1100Response result; private A1100Response PrepareBuilder() { if (resultIsReadOnly) { A1100Response original = result; result = new A1100Response(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override A1100Response MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::DolphinServer.ProtoEntity.A1100Response.Descriptor; } } public override A1100Response DefaultInstanceForType { get { return global::DolphinServer.ProtoEntity.A1100Response.DefaultInstance; } } public override A1100Response BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is A1100Response) { return MergeFrom((A1100Response) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(A1100Response other) { if (other == global::DolphinServer.ProtoEntity.A1100Response.DefaultInstance) return this; PrepareBuilder(); if (other.HasErrorInfo) { ErrorInfo = other.ErrorInfo; } if (other.HasErrorCode) { ErrorCode = other.ErrorCode; } if (other.HasUid) { Uid = other.Uid; } if (other.HasMessage) { Message = other.Message; } if (other.HasMessageType) { MessageType = other.MessageType; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_a1100ResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _a1100ResponseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasErrorInfo = input.ReadString(ref result.errorInfo_); break; } case 16: { result.hasErrorCode = input.ReadInt32(ref result.errorCode_); break; } case 26: { result.hasUid = input.ReadString(ref result.uid_); break; } case 34: { result.hasMessage = input.ReadString(ref result.message_); break; } case 42: { result.hasMessageType = input.ReadString(ref result.messageType_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasErrorInfo { get { return result.hasErrorInfo; } } public string ErrorInfo { get { return result.ErrorInfo; } set { SetErrorInfo(value); } } public Builder SetErrorInfo(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasErrorInfo = true; result.errorInfo_ = value; return this; } public Builder ClearErrorInfo() { PrepareBuilder(); result.hasErrorInfo = false; result.errorInfo_ = ""; return this; } public bool HasErrorCode { get { return result.hasErrorCode; } } public int ErrorCode { get { return result.ErrorCode; } set { SetErrorCode(value); } } public Builder SetErrorCode(int value) { PrepareBuilder(); result.hasErrorCode = true; result.errorCode_ = value; return this; } public Builder ClearErrorCode() { PrepareBuilder(); result.hasErrorCode = false; result.errorCode_ = 0; return this; } public bool HasUid { get { return result.hasUid; } } public string Uid { get { return result.Uid; } set { SetUid(value); } } public Builder SetUid(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasUid = true; result.uid_ = value; return this; } public Builder ClearUid() { PrepareBuilder(); result.hasUid = false; result.uid_ = ""; return this; } public bool HasMessage { get { return result.hasMessage; } } public string Message { get { return result.Message; } set { SetMessage(value); } } public Builder SetMessage(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasMessage = true; result.message_ = value; return this; } public Builder ClearMessage() { PrepareBuilder(); result.hasMessage = false; result.message_ = ""; return this; } public bool HasMessageType { get { return result.hasMessageType; } } public string MessageType { get { return result.MessageType; } set { SetMessageType(value); } } public Builder SetMessageType(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasMessageType = true; result.messageType_ = value; return this; } public Builder ClearMessageType() { PrepareBuilder(); result.hasMessageType = false; result.messageType_ = ""; return this; } } static A1100Response() { object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1100Response.Descriptor, null); } } #endregion } #endregion Designer generated code
using ClosedXML.Excel.Caching; using ClosedXML.Excel.CalcEngine; using ClosedXML.Excel.Drawings; using ClosedXML.Excel.Ranges.Index; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using static ClosedXML.Excel.XLProtectionAlgorithm; namespace ClosedXML.Excel { internal class XLWorksheet : XLRangeBase, IXLWorksheet { #region Fields private readonly Dictionary<Int32, Int32> _columnOutlineCount = new Dictionary<Int32, Int32>(); private readonly Dictionary<Int32, Int32> _rowOutlineCount = new Dictionary<Int32, Int32>(); private readonly XLRangeFactory _rangeFactory; private readonly XLRangeRepository _rangeRepository; private readonly List<IXLRangeIndex> _rangeIndices; internal Int32 ZOrder = 1; private String _name; internal Int32 _position; private Double _rowHeight; private Boolean _tabActive; private XLSheetProtection _protection; internal Boolean EventTrackingEnabled; /// <summary> /// Fake address to be used everywhere the invalid address is needed. /// </summary> internal readonly XLAddress InvalidAddress; #endregion Fields #region Constructor public XLWorksheet(String sheetName, XLWorkbook workbook) : base( new XLRangeAddress( new XLAddress(null, XLHelper.MinRowNumber, XLHelper.MinColumnNumber, false, false), new XLAddress(null, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber, false, false)), (workbook.Style as XLStyle).Value) { EventTrackingEnabled = workbook.EventTracking == XLEventTracking.Enabled; Workbook = workbook; InvalidAddress = new XLAddress(this, 0, 0, false, false); var firstAddress = new XLAddress(this, RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.FirstAddress.FixedRow, RangeAddress.FirstAddress.FixedColumn); var lastAddress = new XLAddress(this, RangeAddress.LastAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber, RangeAddress.LastAddress.FixedRow, RangeAddress.LastAddress.FixedColumn); RangeAddress = new XLRangeAddress(firstAddress, lastAddress); _rangeFactory = new XLRangeFactory(this); _rangeRepository = new XLRangeRepository(workbook, _rangeFactory.Create); _rangeIndices = new List<IXLRangeIndex>(); Pictures = new XLPictures(this); NamedRanges = new XLNamedRanges(this); SheetView = new XLSheetView(this); Tables = new XLTables(); Hyperlinks = new XLHyperlinks(); DataValidations = new XLDataValidations(this); PivotTables = new XLPivotTables(this); Protection = new XLSheetProtection(DefaultProtectionAlgorithm); AutoFilter = new XLAutoFilter(); ConditionalFormats = new XLConditionalFormats(); SparklineGroups = new XLSparklineGroups(this); Internals = new XLWorksheetInternals(new XLCellsCollection(), new XLColumnsCollection(), new XLRowsCollection(), new XLRanges()); PageSetup = new XLPageSetup((XLPageSetup)workbook.PageOptions, this); Outline = new XLOutline(workbook.Outline); _columnWidth = workbook.ColumnWidth; _rowHeight = workbook.RowHeight; RowHeightChanged = Math.Abs(workbook.RowHeight - XLWorkbook.DefaultRowHeight) > XLHelper.Epsilon; Name = sheetName; Charts = new XLCharts(); ShowFormulas = workbook.ShowFormulas; ShowGridLines = workbook.ShowGridLines; ShowOutlineSymbols = workbook.ShowOutlineSymbols; ShowRowColHeaders = workbook.ShowRowColHeaders; ShowRuler = workbook.ShowRuler; ShowWhiteSpace = workbook.ShowWhiteSpace; ShowZeros = workbook.ShowZeros; RightToLeft = workbook.RightToLeft; TabColor = XLColor.NoColor; SelectedRanges = new XLRanges(); Author = workbook.Author; } #endregion Constructor public override XLRangeType RangeType { get { return XLRangeType.Worksheet; } } public string LegacyDrawingId; public Boolean LegacyDrawingIsNew; private Double _columnWidth; public XLWorksheetInternals Internals { get; private set; } public XLRangeFactory RangeFactory { get { return _rangeFactory; } } public override IEnumerable<IXLStyle> Styles { get { yield return GetStyle(); foreach (XLCell c in Internals.CellsCollection.GetCells()) yield return c.Style; } } protected override IEnumerable<XLStylizedBase> Children { get { var columnsUsed = Internals.ColumnsCollection.Keys .Union(Internals.CellsCollection.ColumnsUsed.Keys) .Distinct() .OrderBy(c => c) .ToList(); foreach (var col in columnsUsed) yield return Column(col); var rowsUsed = Internals.RowsCollection.Keys .Union(Internals.CellsCollection.RowsUsed.Keys) .Distinct() .OrderBy(r => r) .ToList(); foreach (var row in rowsUsed) yield return Row(row); } } internal Boolean RowHeightChanged { get; set; } internal Boolean ColumnWidthChanged { get; set; } public Int32 SheetId { get; set; } internal String RelId { get; set; } public XLDataValidations DataValidations { get; private set; } public IXLCharts Charts { get; private set; } public XLSheetProtection Protection { get => _protection; set { _protection = value.Clone().CastTo<XLSheetProtection>(); } } public XLAutoFilter AutoFilter { get; private set; } public bool IsDeleted { get; private set; } #region IXLWorksheet Members public XLWorkbook Workbook { get; private set; } public Double ColumnWidth { get { return _columnWidth; } set { ColumnWidthChanged = true; _columnWidth = value; } } public Double RowHeight { get { return _rowHeight; } set { RowHeightChanged = true; _rowHeight = value; } } public String Name { get { return _name; } set { if (_name == value) return; XLHelper.ValidateSheetName(value); Workbook.WorksheetsInternal.Rename(_name, value); _name = value; } } public Int32 Position { get { return _position; } set { if (value > Workbook.WorksheetsInternal.Count + Workbook.UnsupportedSheets.Count + 1) throw new ArgumentOutOfRangeException(nameof(value), "Index must be equal or less than the number of worksheets + 1."); if (value < _position) { Workbook.WorksheetsInternal .Where<XLWorksheet>(w => w.Position >= value && w.Position < _position) .ForEach(w => w._position += 1); } if (value > _position) { Workbook.WorksheetsInternal .Where<XLWorksheet>(w => w.Position <= value && w.Position > _position) .ForEach(w => (w)._position -= 1); } _position = value; } } public IXLPageSetup PageSetup { get; private set; } public IXLOutline Outline { get; private set; } IXLRow IXLWorksheet.FirstRowUsed() { return FirstRowUsed(); } [Obsolete("Use the overload with XLCellsUsedOptions")] IXLRow IXLWorksheet.FirstRowUsed(Boolean includeFormats) { return FirstRowUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents); } IXLRow IXLWorksheet.FirstRowUsed(XLCellsUsedOptions options) { return FirstRowUsed(options); } IXLRow IXLWorksheet.LastRowUsed() { return LastRowUsed(); } [Obsolete("Use the overload with XLCellsUsedOptions")] IXLRow IXLWorksheet.LastRowUsed(Boolean includeFormats) { return LastRowUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents); } IXLRow IXLWorksheet.LastRowUsed(XLCellsUsedOptions options) { return LastRowUsed(options); } IXLColumn IXLWorksheet.LastColumn() { return LastColumn(); } IXLColumn IXLWorksheet.FirstColumn() { return FirstColumn(); } IXLRow IXLWorksheet.FirstRow() { return FirstRow(); } IXLRow IXLWorksheet.LastRow() { return LastRow(); } IXLColumn IXLWorksheet.FirstColumnUsed() { return FirstColumnUsed(); } [Obsolete("Use the overload with XLCellsUsedOptions")] IXLColumn IXLWorksheet.FirstColumnUsed(Boolean includeFormats) { return FirstColumnUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents); } IXLColumn IXLWorksheet.FirstColumnUsed(XLCellsUsedOptions options) { return FirstColumnUsed(options); } IXLColumn IXLWorksheet.LastColumnUsed() { return LastColumnUsed(); } [Obsolete("Use the overload with XLCellsUsedOptions")] IXLColumn IXLWorksheet.LastColumnUsed(Boolean includeFormats) { return LastColumnUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents); } IXLColumn IXLWorksheet.LastColumnUsed(XLCellsUsedOptions options) { return LastColumnUsed(options); } public IXLColumns Columns() { var columnMap = new HashSet<Int32>(); columnMap.UnionWith(Internals.CellsCollection.ColumnsUsed.Keys); columnMap.UnionWith(Internals.ColumnsCollection.Keys); var retVal = new XLColumns(this, StyleValue, columnMap.Select(Column)); return retVal; } public IXLColumns Columns(String columns) { var retVal = new XLColumns(null, StyleValue); var columnPairs = columns.Split(','); foreach (string tPair in columnPairs.Select(pair => pair.Trim())) { String firstColumn; String lastColumn; if (tPair.Contains(':') || tPair.Contains('-')) { var columnRange = XLHelper.SplitRange(tPair); firstColumn = columnRange[0]; lastColumn = columnRange[1]; } else { firstColumn = tPair; lastColumn = tPair; } if (Int32.TryParse(firstColumn, out int tmp)) { foreach (IXLColumn col in Columns(Int32.Parse(firstColumn), Int32.Parse(lastColumn))) retVal.Add((XLColumn)col); } else { foreach (IXLColumn col in Columns(firstColumn, lastColumn)) retVal.Add((XLColumn)col); } } return retVal; } public IXLColumns Columns(String firstColumn, String lastColumn) { return Columns(XLHelper.GetColumnNumberFromLetter(firstColumn), XLHelper.GetColumnNumberFromLetter(lastColumn)); } public IXLColumns Columns(Int32 firstColumn, Int32 lastColumn) { var retVal = new XLColumns(null, StyleValue); for (int co = firstColumn; co <= lastColumn; co++) retVal.Add(Column(co)); return retVal; } public IXLRows Rows() { var rowMap = new HashSet<Int32>(); rowMap.UnionWith(Internals.CellsCollection.RowsUsed.Keys); rowMap.UnionWith(Internals.RowsCollection.Keys); var retVal = new XLRows(this, StyleValue, rowMap.Select(Row)); return retVal; } public IXLRows Rows(String rows) { var retVal = new XLRows(null, StyleValue); var rowPairs = rows.Split(','); foreach (string tPair in rowPairs.Select(pair => pair.Trim())) { String firstRow; String lastRow; if (tPair.Contains(':') || tPair.Contains('-')) { var rowRange = XLHelper.SplitRange(tPair); firstRow = rowRange[0]; lastRow = rowRange[1]; } else { firstRow = tPair; lastRow = tPair; } Rows(Int32.Parse(firstRow), Int32.Parse(lastRow)) .ForEach(row => retVal.Add((XLRow)row)); } return retVal; } public IXLRows Rows(Int32 firstRow, Int32 lastRow) { var retVal = new XLRows(null, StyleValue); for (int ro = firstRow; ro <= lastRow; ro++) retVal.Add(Row(ro)); return retVal; } IXLRow IXLWorksheet.Row(Int32 row) { return Row(row); } IXLColumn IXLWorksheet.Column(Int32 column) { return Column(column); } IXLColumn IXLWorksheet.Column(String column) { return Column(column); } IXLCell IXLWorksheet.Cell(int row, int column) { return Cell(row, column); } IXLCell IXLWorksheet.Cell(string cellAddressInRange) { return Cell(cellAddressInRange); } IXLCell IXLWorksheet.Cell(int row, string column) { return Cell(row, column); } IXLCell IXLWorksheet.Cell(IXLAddress cellAddressInRange) { return Cell(cellAddressInRange); } IXLRange IXLWorksheet.Range(IXLRangeAddress rangeAddress) { return Range(rangeAddress); } IXLRange IXLWorksheet.Range(string rangeAddress) { return Range(rangeAddress); } IXLRange IXLWorksheet.Range(IXLCell firstCell, IXLCell lastCell) { return Range(firstCell, lastCell); } IXLRange IXLWorksheet.Range(string firstCellAddress, string lastCellAddress) { return Range(firstCellAddress, lastCellAddress); } IXLRange IXLWorksheet.Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress) { return Range(firstCellAddress, lastCellAddress); } IXLRange IXLWorksheet.Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn) { return Range(firstCellRow, firstCellColumn, lastCellRow, lastCellColumn); } public IXLWorksheet CollapseRows() { Enumerable.Range(1, 8).ForEach(i => CollapseRows(i)); return this; } public IXLWorksheet CollapseColumns() { Enumerable.Range(1, 8).ForEach(i => CollapseColumns(i)); return this; } public IXLWorksheet ExpandRows() { Enumerable.Range(1, 8).ForEach(i => ExpandRows(i)); return this; } public IXLWorksheet ExpandColumns() { Enumerable.Range(1, 8).ForEach(i => ExpandColumns(i)); return this; } public IXLWorksheet CollapseRows(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Collapse()); return this; } public IXLWorksheet CollapseColumns(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Collapse()); return this; } public IXLWorksheet ExpandRows(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Expand()); return this; } public IXLWorksheet ExpandColumns(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Expand()); return this; } public void Delete() { IsDeleted = true; (Workbook.NamedRanges as XLNamedRanges).OnWorksheetDeleted(Name); Workbook.WorksheetsInternal.Delete(Name); } public IXLNamedRanges NamedRanges { get; private set; } public IXLNamedRange NamedRange(String rangeName) { return NamedRanges.NamedRange(rangeName); } IXLSheetView IXLWorksheet.SheetView { get => SheetView; } public XLSheetView SheetView { get; private set; } public IXLTables Tables { get; private set; } public IXLTable Table(Int32 index) { return Tables.Table(index); } public IXLTable Table(String name) { return Tables.Table(name); } public IXLWorksheet CopyTo(String newSheetName) { return CopyTo(Workbook, newSheetName, Workbook.WorksheetsInternal.Count + 1); } public IXLWorksheet CopyTo(String newSheetName, Int32 position) { return CopyTo(Workbook, newSheetName, position); } public IXLWorksheet CopyTo(XLWorkbook workbook) { return CopyTo(workbook, Name, workbook.WorksheetsInternal.Count + 1); } public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName) { return CopyTo(workbook, newSheetName, workbook.WorksheetsInternal.Count + 1); } public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName, Int32 position) { if (this.IsDeleted) throw new InvalidOperationException($"`{this.Name}` has been deleted and cannot be copied."); var targetSheet = (XLWorksheet)workbook.WorksheetsInternal.Add(newSheetName, position); Internals.ColumnsCollection.ForEach(kp => kp.Value.CopyTo(targetSheet.Column(kp.Key))); Internals.RowsCollection.ForEach(kp => kp.Value.CopyTo(targetSheet.Row(kp.Key))); Internals.CellsCollection.GetCells().ForEach(c => targetSheet.Cell(c.Address).CopyFrom(c, XLCellCopyOptions.Values | XLCellCopyOptions.Styles)); DataValidations.ForEach(dv => targetSheet.DataValidations.Add(new XLDataValidation(dv, this))); targetSheet.Visibility = Visibility; targetSheet.ColumnWidth = ColumnWidth; targetSheet.ColumnWidthChanged = ColumnWidthChanged; targetSheet.RowHeight = RowHeight; targetSheet.RowHeightChanged = RowHeightChanged; targetSheet.InnerStyle = InnerStyle; targetSheet.PageSetup = new XLPageSetup((XLPageSetup)PageSetup, targetSheet); (targetSheet.PageSetup.Header as XLHeaderFooter).Changed = true; (targetSheet.PageSetup.Footer as XLHeaderFooter).Changed = true; targetSheet.Outline = new XLOutline(Outline); targetSheet.SheetView = new XLSheetView(targetSheet, SheetView); targetSheet.SelectedRanges.RemoveAll(); Pictures.ForEach(picture => picture.CopyTo(targetSheet)); NamedRanges.ForEach(nr => nr.CopyTo(targetSheet)); Tables.Cast<XLTable>().ForEach(t => t.CopyTo(targetSheet, false)); PivotTables.ForEach(pt => pt.CopyTo(targetSheet.Cell(pt.TargetCell.Address.CastTo<XLAddress>().WithoutWorksheet()))); ConditionalFormats.ForEach(cf => cf.CopyTo(targetSheet)); SparklineGroups.CopyTo(targetSheet); MergedRanges.ForEach(mr => targetSheet.Range(((XLRangeAddress)mr.RangeAddress).WithoutWorksheet()).Merge()); SelectedRanges.ForEach(sr => targetSheet.SelectedRanges.Add(targetSheet.Range(((XLRangeAddress)sr.RangeAddress).WithoutWorksheet()))); if (AutoFilter.IsEnabled) { var range = targetSheet.Range(((XLRangeAddress)AutoFilter.Range.RangeAddress).WithoutWorksheet()); range.SetAutoFilter(); } return targetSheet; } public new IXLHyperlinks Hyperlinks { get; private set; } IXLDataValidations IXLWorksheet.DataValidations { get { return DataValidations; } } private XLWorksheetVisibility _visibility; public XLWorksheetVisibility Visibility { get { return _visibility; } set { if (value != XLWorksheetVisibility.Visible) TabSelected = false; _visibility = value; } } public IXLWorksheet Hide() { Visibility = XLWorksheetVisibility.Hidden; return this; } public IXLWorksheet Unhide() { Visibility = XLWorksheetVisibility.Visible; return this; } IXLSheetProtection IXLProtectable<IXLSheetProtection, XLSheetProtectionElements>.Protection { get => Protection; set => Protection = value as XLSheetProtection; } public IXLSheetProtection Protect() { return Protection.Protect(); } public IXLSheetProtection Protect(String password, Algorithm algorithm = DefaultProtectionAlgorithm) { return Protection.Protect(password, algorithm, XLSheetProtectionElements.SelectEverything); } public IXLSheetProtection Protect(String password, Algorithm algorithm, XLSheetProtectionElements allowedElements) { return Protection.Protect(password, algorithm, allowedElements); } IXLElementProtection IXLProtectable.Protect() { return Protect(); } IXLElementProtection IXLProtectable.Protect(String password, Algorithm algorithm) { return Protect(password, algorithm); } public IXLSheetProtection Unprotect() { return Protection.Unprotect(); } public IXLSheetProtection Unprotect(String password) { return Protection.Unprotect(password); } IXLElementProtection IXLProtectable.Unprotect() { return Unprotect(); } IXLElementProtection IXLProtectable.Unprotect(String password) { return Unprotect(password); } public new IXLRange Sort() { return GetRangeForSort().Sort(); } public new IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return GetRangeForSort().Sort(columnsToSortBy, sortOrder, matchCase, ignoreBlanks); } public new IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return GetRangeForSort().Sort(columnToSortBy, sortOrder, matchCase, ignoreBlanks); } public new IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return GetRangeForSort().SortLeftToRight(sortOrder, matchCase, ignoreBlanks); } public Boolean ShowFormulas { get; set; } public Boolean ShowGridLines { get; set; } public Boolean ShowOutlineSymbols { get; set; } public Boolean ShowRowColHeaders { get; set; } public Boolean ShowRuler { get; set; } public Boolean ShowWhiteSpace { get; set; } public Boolean ShowZeros { get; set; } public IXLWorksheet SetShowFormulas() { ShowFormulas = true; return this; } public IXLWorksheet SetShowFormulas(Boolean value) { ShowFormulas = value; return this; } public IXLWorksheet SetShowGridLines() { ShowGridLines = true; return this; } public IXLWorksheet SetShowGridLines(Boolean value) { ShowGridLines = value; return this; } public IXLWorksheet SetShowOutlineSymbols() { ShowOutlineSymbols = true; return this; } public IXLWorksheet SetShowOutlineSymbols(Boolean value) { ShowOutlineSymbols = value; return this; } public IXLWorksheet SetShowRowColHeaders() { ShowRowColHeaders = true; return this; } public IXLWorksheet SetShowRowColHeaders(Boolean value) { ShowRowColHeaders = value; return this; } public IXLWorksheet SetShowRuler() { ShowRuler = true; return this; } public IXLWorksheet SetShowRuler(Boolean value) { ShowRuler = value; return this; } public IXLWorksheet SetShowWhiteSpace() { ShowWhiteSpace = true; return this; } public IXLWorksheet SetShowWhiteSpace(Boolean value) { ShowWhiteSpace = value; return this; } public IXLWorksheet SetShowZeros() { ShowZeros = true; return this; } public IXLWorksheet SetShowZeros(Boolean value) { ShowZeros = value; return this; } public XLColor TabColor { get; set; } public IXLWorksheet SetTabColor(XLColor color) { TabColor = color; return this; } public Boolean TabSelected { get; set; } public Boolean TabActive { get { return _tabActive; } set { if (value && !_tabActive) { foreach (XLWorksheet ws in Worksheet.Workbook.WorksheetsInternal) ws._tabActive = false; } _tabActive = value; } } public IXLWorksheet SetTabSelected() { TabSelected = true; return this; } public IXLWorksheet SetTabSelected(Boolean value) { TabSelected = value; return this; } public IXLWorksheet SetTabActive() { TabActive = true; return this; } public IXLWorksheet SetTabActive(Boolean value) { TabActive = value; return this; } IXLPivotTable IXLWorksheet.PivotTable(String name) { return PivotTable(name); } public IXLPivotTables PivotTables { get; private set; } public Boolean RightToLeft { get; set; } public IXLWorksheet SetRightToLeft() { RightToLeft = true; return this; } public IXLWorksheet SetRightToLeft(Boolean value) { RightToLeft = value; return this; } public override IXLRanges Ranges(String ranges) { var retVal = new XLRanges(); foreach (string rangeAddressStr in ranges.Split(',').Select(s => s.Trim())) { if (rangeAddressStr.StartsWith("#REF!")) { continue; } else if (XLHelper.IsValidRangeAddress(rangeAddressStr)) { retVal.Add(Range(new XLRangeAddress(Worksheet, rangeAddressStr))); } else if (NamedRanges.TryGetValue(rangeAddressStr, out IXLNamedRange worksheetNamedRange)) { worksheetNamedRange.Ranges.ForEach(retVal.Add); } else if (Workbook.NamedRanges.TryGetValue(rangeAddressStr, out IXLNamedRange workbookNamedRange) && workbookNamedRange.Ranges.First().Worksheet == this) { workbookNamedRange.Ranges.ForEach(retVal.Add); } } return retVal; } IXLAutoFilter IXLWorksheet.AutoFilter { get { return AutoFilter; } } [Obsolete("Use the overload with XLCellsUsedOptions")] public IXLRows RowsUsed(Boolean includeFormats, Func<IXLRow, Boolean> predicate = null) { return RowsUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents, predicate); } public IXLRows RowsUsed(XLCellsUsedOptions options = XLCellsUsedOptions.AllContents, Func<IXLRow, Boolean> predicate = null) { var rows = new XLRows(Worksheet, StyleValue); var rowsUsed = new HashSet<Int32>(); Internals.RowsCollection.Keys.ForEach(r => rowsUsed.Add(r)); Internals.CellsCollection.RowsUsed.Keys.ForEach(r => rowsUsed.Add(r)); foreach (var rowNum in rowsUsed) { var row = Row(rowNum); if (!row.IsEmpty(options) && (predicate == null || predicate(row))) rows.Add(row); } return rows; } public IXLRows RowsUsed(Func<IXLRow, Boolean> predicate = null) { return RowsUsed(XLCellsUsedOptions.AllContents, predicate); } [Obsolete("Use the overload with XLCellsUsedOptions")] public IXLColumns ColumnsUsed(Boolean includeFormats, Func<IXLColumn, Boolean> predicate = null) { return ColumnsUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents, predicate); } public IXLColumns ColumnsUsed(XLCellsUsedOptions options = XLCellsUsedOptions.AllContents, Func<IXLColumn, Boolean> predicate = null) { var columns = new XLColumns(Worksheet, StyleValue); var columnsUsed = new HashSet<Int32>(); Internals.ColumnsCollection.Keys.ForEach(r => columnsUsed.Add(r)); Internals.CellsCollection.ColumnsUsed.Keys.ForEach(r => columnsUsed.Add(r)); foreach (var columnNum in columnsUsed) { var column = Column(columnNum); if (!column.IsEmpty(options) && (predicate == null || predicate(column))) columns.Add(column); } return columns; } public IXLColumns ColumnsUsed(Func<IXLColumn, Boolean> predicate = null) { return ColumnsUsed(XLCellsUsedOptions.AllContents, predicate); } internal void RegisterRangeIndex(IXLRangeIndex rangeIndex) { _rangeIndices.Add(rangeIndex); } internal void Cleanup() { Internals.Dispose(); Pictures.ForEach(p => p.Dispose()); _rangeRepository.Clear(); _rangeIndices.Clear(); } #endregion IXLWorksheet Members #region Outlines public void IncrementColumnOutline(Int32 level) { if (level <= 0) return; if (_columnOutlineCount.TryGetValue(level, out Int32 value)) _columnOutlineCount[level] = value + 1; else _columnOutlineCount.Add(level, 1); } public void DecrementColumnOutline(Int32 level) { if (level <= 0) return; if (_columnOutlineCount.TryGetValue(level, out Int32 value)) { if (value > 0) _columnOutlineCount[level] = value - 1; } else _columnOutlineCount.Add(level, 0); } public Int32 GetMaxColumnOutline() { var list = _columnOutlineCount.Where(kp => kp.Value > 0).ToList(); return list.Count == 0 ? 0 : list.Max(kp => kp.Key); } public void IncrementRowOutline(Int32 level) { if (level <= 0) return; if (_rowOutlineCount.TryGetValue(level, out Int32 value)) _rowOutlineCount[level] = value + 1; else _rowOutlineCount.Add(level, 0); } public void DecrementRowOutline(Int32 level) { if (level <= 0) return; if (_rowOutlineCount.TryGetValue(level, out Int32 value)) { if (value > 0) _rowOutlineCount[level] = level - 1; } else _rowOutlineCount.Add(level, 0); } public Int32 GetMaxRowOutline() { return _rowOutlineCount.Count == 0 ? 0 : _rowOutlineCount.Where(kp => kp.Value > 0).Max(kp => kp.Key); } #endregion Outlines public XLRow FirstRowUsed() { return FirstRowUsed(XLCellsUsedOptions.AllContents); } public XLRow FirstRowUsed(XLCellsUsedOptions options) { var rngRow = AsRange().FirstRowUsed(options); return rngRow != null ? Row(rngRow.RangeAddress.FirstAddress.RowNumber) : null; } public XLRow LastRowUsed() { return LastRowUsed(XLCellsUsedOptions.AllContents); } public XLRow LastRowUsed(XLCellsUsedOptions options) { var rngRow = AsRange().LastRowUsed(options); return rngRow != null ? Row(rngRow.RangeAddress.LastAddress.RowNumber) : null; } public XLColumn LastColumn() { return Column(XLHelper.MaxColumnNumber); } public XLColumn FirstColumn() { return Column(1); } public XLRow FirstRow() { return Row(1); } public XLRow LastRow() { return Row(XLHelper.MaxRowNumber); } public XLColumn FirstColumnUsed() { return FirstColumnUsed(XLCellsUsedOptions.AllContents); } public XLColumn FirstColumnUsed(XLCellsUsedOptions options) { var rngColumn = AsRange().FirstColumnUsed(options); return rngColumn != null ? Column(rngColumn.RangeAddress.FirstAddress.ColumnNumber) : null; } public XLColumn LastColumnUsed() { return LastColumnUsed(XLCellsUsedOptions.AllContents); } public XLColumn LastColumnUsed(XLCellsUsedOptions options) { var rngColumn = AsRange().LastColumnUsed(options); return rngColumn != null ? Column(rngColumn.RangeAddress.LastAddress.ColumnNumber) : null; } public XLRow Row(Int32 row) { return Row(row, true); } public XLColumn Column(Int32 columnNumber) { if (columnNumber <= 0 || columnNumber > XLHelper.MaxColumnNumber) throw new ArgumentOutOfRangeException(nameof(columnNumber), $"Column number must be between 1 and {XLHelper.MaxColumnNumber}"); if (Internals.ColumnsCollection.TryGetValue(columnNumber, out XLColumn column)) return column; else { // This is a new column so we're going to reference all // cells in this column to preserve their formatting Internals.RowsCollection.Keys.ForEach(r => Cell(r, columnNumber)); column = RangeFactory.CreateColumn(columnNumber); Internals.ColumnsCollection.Add(columnNumber, column); } return column; } public IXLColumn Column(String column) { return Column(XLHelper.GetColumnNumberFromLetter(column)); } public override XLRange AsRange() { return Range(1, 1, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber); } internal override void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted) { if (!range.IsEntireColumn()) { var model = new XLRangeAddress( range.RangeAddress.FirstAddress, new XLAddress(range.RangeAddress.LastAddress.RowNumber, XLHelper.MaxColumnNumber, false, false)); var rangesToSplit = Worksheet.MergedRanges .GetIntersectedRanges(model) .Where(r => r.RangeAddress.FirstAddress.RowNumber < range.RangeAddress.FirstAddress.RowNumber || r.RangeAddress.LastAddress.RowNumber > range.RangeAddress.LastAddress.RowNumber) .ToList(); foreach (var rangeToSplit in rangesToSplit) { Worksheet.MergedRanges.Remove(rangeToSplit); } } Workbook.Worksheets.ForEach(ws => MoveNamedRangesColumns(range, columnsShifted, ws.NamedRanges)); MoveNamedRangesColumns(range, columnsShifted, Workbook.NamedRanges); ShiftConditionalFormattingColumns(range, columnsShifted); ShiftDataValidationColumns(range, columnsShifted); ShiftPageBreaksColumns(range, columnsShifted); RemoveInvalidSparklines(); } private void ShiftPageBreaksColumns(XLRange range, int columnsShifted) { for (var i = 0; i < PageSetup.ColumnBreaks.Count; i++) { int br = PageSetup.ColumnBreaks[i]; if (range.RangeAddress.FirstAddress.ColumnNumber <= br) { PageSetup.ColumnBreaks[i] = br + columnsShifted; } } } private void ShiftConditionalFormattingColumns(XLRange range, int columnsShifted) { if (!ConditionalFormats.Any()) return; Int32 firstCol = range.RangeAddress.FirstAddress.ColumnNumber; if (firstCol == 1) return; int colNum = columnsShifted > 0 ? firstCol - 1 : firstCol; var model = Column(colNum).AsRange(); foreach (var cf in ConditionalFormats.ToList()) { var cfRanges = cf.Ranges.ToList(); cf.Ranges.RemoveAll(); foreach (var cfRange in cfRanges) { var cfAddress = cfRange.RangeAddress; IXLRange newRange; if (cfRange.Intersects(model)) { newRange = Range(cfAddress.FirstAddress.RowNumber, cfAddress.FirstAddress.ColumnNumber, cfAddress.LastAddress.RowNumber, Math.Min(XLHelper.MaxColumnNumber, cfAddress.LastAddress.ColumnNumber + columnsShifted)); } else if (cfAddress.FirstAddress.ColumnNumber >= firstCol) { newRange = Range(cfAddress.FirstAddress.RowNumber, Math.Max(cfAddress.FirstAddress.ColumnNumber + columnsShifted, firstCol), cfAddress.LastAddress.RowNumber, Math.Min(XLHelper.MaxColumnNumber, cfAddress.LastAddress.ColumnNumber + columnsShifted)); } else newRange = cfRange; if (newRange.RangeAddress.IsValid && newRange.RangeAddress.FirstAddress.ColumnNumber <= newRange.RangeAddress.LastAddress.ColumnNumber) cf.Ranges.Add(newRange); } if (!cf.Ranges.Any()) ConditionalFormats.Remove(f => f == cf); } } private void ShiftDataValidationColumns(XLRange range, int columnsShifted) { if (!DataValidations.Any()) return; Int32 firstCol = range.RangeAddress.FirstAddress.ColumnNumber; if (firstCol == 1) return; int colNum = columnsShifted > 0 ? firstCol - 1 : firstCol; var model = Column(colNum).AsRange(); foreach (var dv in DataValidations.ToList()) { var dvRanges = dv.Ranges.ToList(); dv.ClearRanges(); foreach (var dvRange in dvRanges) { var dvAddress = dvRange.RangeAddress; IXLRange newRange; if (dvRange.Intersects(model)) { newRange = Range(dvAddress.FirstAddress.RowNumber, dvAddress.FirstAddress.ColumnNumber, dvAddress.LastAddress.RowNumber, Math.Min(XLHelper.MaxColumnNumber, dvAddress.LastAddress.ColumnNumber + columnsShifted)); } else if (dvAddress.FirstAddress.ColumnNumber >= firstCol) { newRange = Range(dvAddress.FirstAddress.RowNumber, Math.Max(dvAddress.FirstAddress.ColumnNumber + columnsShifted, firstCol), dvAddress.LastAddress.RowNumber, Math.Min(XLHelper.MaxColumnNumber, dvAddress.LastAddress.ColumnNumber + columnsShifted)); } else newRange = dvRange; if (newRange.RangeAddress.IsValid && newRange.RangeAddress.FirstAddress.ColumnNumber <= newRange.RangeAddress.LastAddress.ColumnNumber) dv.AddRange(newRange); } if (!dv.Ranges.Any()) DataValidations.Delete(v => v == dv); } } internal override void WorksheetRangeShiftedRows(XLRange range, int rowsShifted) { if (!range.IsEntireRow()) { var model = new XLRangeAddress( range.RangeAddress.FirstAddress, new XLAddress(XLHelper.MaxRowNumber, range.RangeAddress.LastAddress.ColumnNumber, false, false)); var rangesToSplit = Worksheet.MergedRanges .GetIntersectedRanges(model) .Where(r => r.RangeAddress.FirstAddress.ColumnNumber < range.RangeAddress.FirstAddress.ColumnNumber || r.RangeAddress.LastAddress.ColumnNumber > range.RangeAddress.LastAddress.ColumnNumber) .ToList(); foreach (var rangeToSplit in rangesToSplit) { Worksheet.MergedRanges.Remove(rangeToSplit); } } Workbook.Worksheets.ForEach(ws => MoveNamedRangesRows(range, rowsShifted, ws.NamedRanges)); MoveNamedRangesRows(range, rowsShifted, Workbook.NamedRanges); ShiftConditionalFormattingRows(range, rowsShifted); ShiftDataValidationRows(range, rowsShifted); RemoveInvalidSparklines(); ShiftPageBreaksRows(range, rowsShifted); } private void ShiftPageBreaksRows(XLRange range, int rowsShifted) { for (var i = 0; i < PageSetup.RowBreaks.Count; i++) { int br = PageSetup.RowBreaks[i]; if (range.RangeAddress.FirstAddress.RowNumber <= br) { PageSetup.RowBreaks[i] = br + rowsShifted; } } } private void ShiftConditionalFormattingRows(XLRange range, int rowsShifted) { if (!ConditionalFormats.Any()) return; Int32 firstRow = range.RangeAddress.FirstAddress.RowNumber; if (firstRow == 1) return; int rowNum = rowsShifted > 0 ? firstRow - 1 : firstRow; var model = Row(rowNum).AsRange(); foreach (var cf in ConditionalFormats.ToList()) { var cfRanges = cf.Ranges.ToList(); cf.Ranges.RemoveAll(); foreach (var cfRange in cfRanges) { var cfAddress = cfRange.RangeAddress; IXLRange newRange; if (cfRange.Intersects(model)) { newRange = Range(cfAddress.FirstAddress.RowNumber, cfAddress.FirstAddress.ColumnNumber, Math.Min(XLHelper.MaxRowNumber, cfAddress.LastAddress.RowNumber + rowsShifted), cfAddress.LastAddress.ColumnNumber); } else if (cfAddress.FirstAddress.RowNumber >= firstRow) { newRange = Range(Math.Max(cfAddress.FirstAddress.RowNumber + rowsShifted, firstRow), cfAddress.FirstAddress.ColumnNumber, Math.Min(XLHelper.MaxRowNumber, cfAddress.LastAddress.RowNumber + rowsShifted), cfAddress.LastAddress.ColumnNumber); } else newRange = cfRange; if (newRange.RangeAddress.IsValid && newRange.RangeAddress.FirstAddress.RowNumber <= newRange.RangeAddress.LastAddress.RowNumber) cf.Ranges.Add(newRange); } if (!cf.Ranges.Any()) ConditionalFormats.Remove(f => f == cf); } } private void ShiftDataValidationRows(XLRange range, int rowsShifted) { if (!DataValidations.Any()) return; Int32 firstRow = range.RangeAddress.FirstAddress.RowNumber; if (firstRow == 1) return; int rowNum = rowsShifted > 0 ? firstRow - 1 : firstRow; var model = Row(rowNum).AsRange(); foreach (var dv in DataValidations.ToList()) { var dvRanges = dv.Ranges.ToList(); dv.ClearRanges(); foreach (var dvRange in dvRanges) { var dvAddress = dvRange.RangeAddress; IXLRange newRange; if (dvRange.Intersects(model)) { newRange = Range(dvAddress.FirstAddress.RowNumber, dvAddress.FirstAddress.ColumnNumber, Math.Min(XLHelper.MaxRowNumber, dvAddress.LastAddress.RowNumber + rowsShifted), dvAddress.LastAddress.ColumnNumber); } else if (dvAddress.FirstAddress.RowNumber >= firstRow) { newRange = Range(Math.Max(dvAddress.FirstAddress.RowNumber + rowsShifted, firstRow), dvAddress.FirstAddress.ColumnNumber, Math.Min(XLHelper.MaxRowNumber, dvAddress.LastAddress.RowNumber + rowsShifted), dvAddress.LastAddress.ColumnNumber); } else newRange = dvRange; if (newRange.RangeAddress.IsValid && newRange.RangeAddress.FirstAddress.RowNumber <= newRange.RangeAddress.LastAddress.RowNumber) dv.AddRange(newRange); } if (!dv.Ranges.Any()) DataValidations.Delete(v => v == dv); } } private void RemoveInvalidSparklines() { var invalidSparklines = SparklineGroups.SelectMany(g => g) .Where(sl => !((XLAddress)sl.Location.Address).IsValid) .ToList(); foreach (var sparkline in invalidSparklines) { Worksheet.SparklineGroups.Remove(sparkline.Location); } } private void MoveNamedRangesRows(XLRange range, int rowsShifted, IXLNamedRanges namedRanges) { foreach (XLNamedRange nr in namedRanges) { var newRangeList = nr.RangeList.Select(r => XLCell.ShiftFormulaRows(r, this, range, rowsShifted)).Where( newReference => newReference.Length > 0).ToList(); nr.RangeList = newRangeList; } } private void MoveNamedRangesColumns(XLRange range, int columnsShifted, IXLNamedRanges namedRanges) { foreach (XLNamedRange nr in namedRanges) { var newRangeList = nr.RangeList.Select(r => XLCell.ShiftFormulaColumns(r, this, range, columnsShifted)).Where( newReference => newReference.Length > 0).ToList(); nr.RangeList = newRangeList; } } public void NotifyRangeShiftedRows(XLRange range, Int32 rowsShifted) { try { SuspendEvents(); var rangesToShift = _rangeRepository .Where(r => r.RangeAddress.IsValid) .OrderBy(r => r.RangeAddress.FirstAddress.RowNumber * -Math.Sign(rowsShifted)) .ToList(); WorksheetRangeShiftedRows(range, rowsShifted); foreach (var storedRange in rangesToShift) { if (storedRange.IsEntireColumn()) continue; if (ReferenceEquals(range, storedRange)) continue; storedRange.WorksheetRangeShiftedRows(range, rowsShifted); } range.WorksheetRangeShiftedRows(range, rowsShifted); } finally { ResumeEvents(); } } public void NotifyRangeShiftedColumns(XLRange range, Int32 columnsShifted) { try { SuspendEvents(); var rangesToShift = _rangeRepository .Where(r => r.RangeAddress.IsValid) .OrderBy(r => r.RangeAddress.FirstAddress.ColumnNumber * -Math.Sign(columnsShifted)) .ToList(); WorksheetRangeShiftedColumns(range, columnsShifted); foreach (var storedRange in rangesToShift) { if (storedRange.IsEntireRow()) continue; if (ReferenceEquals(range, storedRange)) continue; storedRange.WorksheetRangeShiftedColumns(range, columnsShifted); } range.WorksheetRangeShiftedColumns(range, columnsShifted); } finally { ResumeEvents(); } } public XLRow Row(Int32 rowNumber, Boolean pingCells) { if (rowNumber <= 0 || rowNumber > XLHelper.MaxRowNumber) throw new ArgumentOutOfRangeException(nameof(rowNumber), $"Row number must be between 1 and {XLHelper.MaxRowNumber}"); if (Internals.RowsCollection.TryGetValue(rowNumber, out XLRow row)) return row; else { if (pingCells) { // This is a new row so we're going to reference all // cells in columns of this row to preserve their formatting Internals.ColumnsCollection.Keys.ForEach(c => Cell(rowNumber, c)); } row = RangeFactory.CreateRow(rowNumber); Internals.RowsCollection.Add(rowNumber, row); } return row; } public IXLTable Table(XLRange range, Boolean addToTables, Boolean setAutofilter = true) { return Table(range, GetNewTableName("Table"), addToTables, setAutofilter); } public IXLTable Table(XLRange range, String name, Boolean addToTables, Boolean setAutofilter = true) { CheckRangeNotOverlappingOtherEntities(range); XLRangeAddress rangeAddress; if (range.Rows().Count() == 1) { rangeAddress = new XLRangeAddress(range.FirstCell().Address, range.LastCell().CellBelow().Address); range.InsertRowsBelow(1); } else rangeAddress = range.RangeAddress; var rangeKey = new XLRangeKey(XLRangeType.Table, rangeAddress); var table = (XLTable)_rangeRepository.GetOrCreate(ref rangeKey); if (table.Name != name) table.Name = name; if (addToTables && !Tables.Contains(table)) { Tables.Add(table); } if (setAutofilter && !table.ShowAutoFilter) table.InitializeAutoFilter(); return table; } private void CheckRangeNotOverlappingOtherEntities(XLRange range) { // Check that the range doesn't overlap with any existing tables var firstOverlappingTable = Tables.FirstOrDefault(t => t.RangeUsed().Intersects(range)); if (firstOverlappingTable != null) throw new InvalidOperationException($"The range {range.RangeAddress.ToStringRelative(includeSheet: true)} is already part of table '{firstOverlappingTable.Name}'"); // Check that the range doesn't overlap with any filters if (AutoFilter.IsEnabled && this.AutoFilter.Range.Intersects(range)) throw new InvalidOperationException($"The range {range.RangeAddress.ToStringRelative(includeSheet: true)} overlaps with the worksheet's autofilter."); } private string GetNewTableName(string baseName) { var existingTableNames = new HashSet<String>( this.Workbook.Worksheets .SelectMany(ws => ws.Tables) .Select(t => t.Name), StringComparer.OrdinalIgnoreCase); var i = 1; string tableName; do { tableName = baseName + i.ToString(); i++; } while (existingTableNames.Contains(tableName)); return tableName; } private IXLRange GetRangeForSort() { var range = RangeUsed(); SortColumns.ForEach(e => range.SortColumns.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase)); SortRows.ForEach(e => range.SortRows.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase)); return range; } public XLPivotTable PivotTable(String name) { return (XLPivotTable)PivotTables.PivotTable(name); } public override IXLCells Cells() { return Cells(true, XLCellsUsedOptions.All); } public override IXLCells Cells(Boolean usedCellsOnly) { if (usedCellsOnly) return Cells(true, XLCellsUsedOptions.AllContents); else return Range((this as IXLRangeBase).FirstCellUsed(XLCellsUsedOptions.All), (this as IXLRangeBase).LastCellUsed(XLCellsUsedOptions.All)) .Cells(false, XLCellsUsedOptions.All); } public override XLCell Cell(String cellAddressInRange) { var cell = base.Cell(cellAddressInRange); if (cell != null) return cell; if (Workbook.NamedRanges.TryGetValue(cellAddressInRange, out IXLNamedRange workbookNamedRange)) { if (!workbookNamedRange.Ranges.Any()) return null; return workbookNamedRange.Ranges.FirstOrDefault().FirstCell().CastTo<XLCell>(); } return null; } public override XLRange Range(String rangeAddressStr) { if (XLHelper.IsValidRangeAddress(rangeAddressStr)) return Range(new XLRangeAddress(Worksheet, rangeAddressStr)); if (rangeAddressStr.Contains("[")) return Table(rangeAddressStr.Substring(0, rangeAddressStr.IndexOf("["))) as XLRange; if (NamedRanges.TryGetValue(rangeAddressStr, out IXLNamedRange worksheetNamedRange)) return worksheetNamedRange.Ranges.First().CastTo<XLRange>(); if (Workbook.NamedRanges.TryGetValue(rangeAddressStr, out IXLNamedRange workbookNamedRange)) { if (!workbookNamedRange.Ranges.Any()) return null; return workbookNamedRange.Ranges.First().CastTo<XLRange>(); } return null; } public IXLRanges MergedRanges { get { return Internals.MergedRanges; } } public IXLConditionalFormats ConditionalFormats { get; private set; } public IXLSparklineGroups SparklineGroups { get; private set; } private Boolean _eventTracking; public void SuspendEvents() { _eventTracking = EventTrackingEnabled; EventTrackingEnabled = false; } public void ResumeEvents() { EventTrackingEnabled = _eventTracking; } private IXLRanges _selectedRanges; public IXLRanges SelectedRanges { get { _selectedRanges?.RemoveAll(r => !r.RangeAddress.IsValid); return _selectedRanges; } internal set { _selectedRanges = value; } } public IXLCell ActiveCell { get; set; } private XLCalcEngine _calcEngine; internal XLCalcEngine CalcEngine { get { return _calcEngine ?? (_calcEngine = new XLCalcEngine(this)); } } public Object Evaluate(String expression) { return CalcEngine.Evaluate(expression); } /// <summary> /// Force recalculation of all cell formulas. /// </summary> public void RecalculateAllFormulas() { CellsUsed().Cast<XLCell>().ForEach(cell => cell.Evaluate(true)); } public String Author { get; set; } public override string ToString() { return this.Name; } public IXLPictures Pictures { get; private set; } public Boolean IsPasswordProtected => Protection.IsPasswordProtected; public bool IsProtected => Protection.IsProtected; public IXLPicture Picture(string pictureName) { return Pictures.Picture(pictureName); } public IXLPicture AddPicture(Stream stream) { return Pictures.Add(stream); } public IXLPicture AddPicture(Stream stream, string name) { return Pictures.Add(stream, name); } internal IXLPicture AddPicture(Stream stream, string name, int Id) { return (Pictures as XLPictures).Add(stream, name, Id); } public IXLPicture AddPicture(Stream stream, XLPictureFormat format) { return Pictures.Add(stream, format); } public IXLPicture AddPicture(Stream stream, XLPictureFormat format, string name) { return Pictures.Add(stream, format, name); } public IXLPicture AddPicture(Bitmap bitmap) { return Pictures.Add(bitmap); } public IXLPicture AddPicture(Bitmap bitmap, string name) { return Pictures.Add(bitmap, name); } public IXLPicture AddPicture(string imageFile) { return Pictures.Add(imageFile); } public IXLPicture AddPicture(string imageFile, string name) { return Pictures.Add(imageFile, name); } public override Boolean IsEntireRow() { return true; } public override Boolean IsEntireColumn() { return true; } internal void SetValue<T>(T value, int ro, int co) where T : class { if (value == null) this.Cell(ro, co).SetValue(String.Empty, setTableHeader: true, checkMergedRanges: false); else if (value is IConvertible) this.Cell(ro, co).SetValue((T)Convert.ChangeType(value, typeof(T)), setTableHeader: true, checkMergedRanges: false); else this.Cell(ro, co).SetValue(value, setTableHeader: true, checkMergedRanges: false); } /// <summary> /// Get a cell value not initializing it if it has not been initialized yet. /// </summary> /// <param name="ro">Row number</param> /// <param name="co">Column number</param> /// <returns>Current value of the specified cell. Empty string for non-initialized cells.</returns> internal object GetCellValue(int ro, int co) { if (Internals.CellsCollection.MaxRowUsed < ro || Internals.CellsCollection.MaxColumnUsed < co || !Internals.CellsCollection.Contains(ro, co)) return string.Empty; var cell = Worksheet.Internals.CellsCollection.GetCell(ro, co); if (cell.IsEvaluating) return string.Empty; return cell.Value; } public XLRange GetOrCreateRange(XLRangeParameters xlRangeParameters) { var rangeKey = new XLRangeKey(XLRangeType.Range, xlRangeParameters.RangeAddress); var range = _rangeRepository.GetOrCreate(ref rangeKey); if (xlRangeParameters.DefaultStyle != null && range.StyleValue == StyleValue) range.InnerStyle = xlRangeParameters.DefaultStyle; return range as XLRange; } /// <summary> /// Get a range row from the shared repository or create a new one. /// </summary> /// <param name="address">Address of range row.</param> /// <param name="defaultStyle">Style to apply. If null the worksheet's style is applied.</param> /// <returns>Range row with the specified address.</returns> public XLRangeRow RangeRow(XLRangeAddress address, IXLStyle defaultStyle = null) { var rangeKey = new XLRangeKey(XLRangeType.RangeRow, address); var rangeRow = (XLRangeRow)_rangeRepository.GetOrCreate(ref rangeKey); if (defaultStyle != null && rangeRow.StyleValue == StyleValue) rangeRow.InnerStyle = defaultStyle; return rangeRow; } /// <summary> /// Get a range column from the shared repository or create a new one. /// </summary> /// <param name="address">Address of range column.</param> /// <param name="defaultStyle">Style to apply. If null the worksheet's style is applied.</param> /// <returns>Range column with the specified address.</returns> public XLRangeColumn RangeColumn(XLRangeAddress address, IXLStyle defaultStyle = null) { var rangeKey = new XLRangeKey(XLRangeType.RangeColumn, address); var rangeColumn = (XLRangeColumn)_rangeRepository.GetOrCreate(ref rangeKey); if (defaultStyle != null && rangeColumn.StyleValue == StyleValue) rangeColumn.InnerStyle = defaultStyle; return rangeColumn; } protected override void OnRangeAddressChanged(XLRangeAddress oldAddress, XLRangeAddress newAddress) { } public void RellocateRange(XLRangeType rangeType, XLRangeAddress oldAddress, XLRangeAddress newAddress) { if (_rangeRepository == null) return; var oldKey = new XLRangeKey(rangeType, oldAddress); var newKey = new XLRangeKey(rangeType, newAddress); var range = _rangeRepository.Replace(ref oldKey, ref newKey); foreach (var rangeIndex in _rangeIndices) { if (!rangeIndex.MatchesType(rangeType)) continue; if (rangeIndex.Remove(oldAddress) && newAddress.IsValid && range != null) { rangeIndex.Add(range); } } } internal void DeleteColumn(int columnNumber) { Internals.ColumnsCollection.Remove(columnNumber); var columnsToMove = new List<Int32>(Internals.ColumnsCollection.Where(c => c.Key > columnNumber).Select(c => c.Key).OrderBy(c => c)); foreach (int column in columnsToMove) { Internals.ColumnsCollection.Add(column - 1, Internals.ColumnsCollection[column]); Internals.ColumnsCollection.Remove(column); Internals.ColumnsCollection[column - 1].SetColumnNumber(column - 1); } } internal void DeleteRow(int rowNumber) { Internals.RowsCollection.Remove(rowNumber); var rowsToMove = new List<Int32>(Internals.RowsCollection.Where(c => c.Key > rowNumber).Select(c => c.Key).OrderBy(r => r)); foreach (int row in rowsToMove) { Internals.RowsCollection.Add(row - 1, Worksheet.Internals.RowsCollection[row]); Internals.RowsCollection.Remove(row); Internals.RowsCollection[row - 1].SetRowNumber(row - 1); } } internal void DeleteRange(XLRangeAddress rangeAddress) { var rangeKey = new XLRangeKey(XLRangeType.Range, rangeAddress); _rangeRepository.Remove(ref rangeKey); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure.KeyVault.Internal; namespace Microsoft.Azure.KeyVault.Internal { internal partial class KeyVaultInternalClient : ServiceClient<KeyVaultInternalClient>, IKeyVaultInternalClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private KeyVaultCredential _credentials; /// <summary> /// Gets or sets the credential /// </summary> public KeyVaultCredential Credentials { get { return this._credentials; } set { this._credentials = value; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IKeyOperations _keys; /// <summary> /// Cryptographic and management operations for keys in a vault /// </summary> public virtual IKeyOperations Keys { get { return this._keys; } } private ISecretOperations _secrets; /// <summary> /// Operations for secrets in a vault /// </summary> public virtual ISecretOperations Secrets { get { return this._secrets; } } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> public KeyVaultInternalClient() : base() { this._keys = new KeyOperations(this); this._secrets = new SecretOperations(this); this._apiVersion = "2015-06-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='credentials'> /// Required. Gets or sets the credential /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public KeyVaultInternalClient(KeyVaultCredential credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='credentials'> /// Required. Gets or sets the credential /// </param> public KeyVaultInternalClient(KeyVaultCredential credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = null; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public KeyVaultInternalClient(HttpClient httpClient) : base(httpClient) { this._keys = new KeyOperations(this); this._secrets = new SecretOperations(this); this._apiVersion = "2015-06-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='credentials'> /// Required. Gets or sets the credential /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public KeyVaultInternalClient(KeyVaultCredential credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='credentials'> /// Required. Gets or sets the credential /// </param> /// <param name='httpClient'> /// The Http client /// </param> public KeyVaultInternalClient(KeyVaultCredential credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = null; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// KeyVaultInternalClient instance /// </summary> /// <param name='client'> /// Instance of KeyVaultInternalClient to clone to /// </param> protected override void Clone(ServiceClient<KeyVaultInternalClient> client) { base.Clone(client); if (client is KeyVaultInternalClient) { KeyVaultInternalClient clonedClient = ((KeyVaultInternalClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
/** * (C) Copyright IBM Corp. 2019, 2021. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 */ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.Assistant.V2.Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using UnityEngine.Networking; namespace IBM.Watson.Assistant.V2 { public partial class AssistantService : BaseService { private const string defaultServiceName = "assistant"; private const string defaultServiceUrl = "https://api.us-south.assistant.watson.cloud.ibm.com"; #region Version private string version; /// <summary> /// Gets and sets the version of the service. /// Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is /// `2021-06-14`. /// </summary> public string Version { get { return version; } set { version = value; } } #endregion #region DisableSslVerification private bool disableSslVerification = false; /// <summary> /// Gets and sets the option to disable ssl verification /// </summary> public bool DisableSslVerification { get { return disableSslVerification; } set { disableSslVerification = value; } } #endregion /// <summary> /// AssistantService constructor. /// </summary> /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. /// The current version is `2021-06-14`.</param> public AssistantService(string version) : this(version, defaultServiceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(defaultServiceName)) {} /// <summary> /// AssistantService constructor. /// </summary> /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. /// The current version is `2021-06-14`.</param> /// <param name="authenticator">The service authenticator.</param> public AssistantService(string version, Authenticator authenticator) : this(version, defaultServiceName, authenticator) {} /// <summary> /// AssistantService constructor. /// </summary> /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. /// The current version is `2021-06-14`.</param> /// <param name="serviceName">The service name to be used when configuring the client instance</param> public AssistantService(string version, string serviceName) : this(version, serviceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceName)) {} /// <summary> /// AssistantService constructor. /// </summary> /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. /// The current version is `2021-06-14`.</param> /// <param name="serviceName">The service name to be used when configuring the client instance</param> /// <param name="authenticator">The service authenticator.</param> public AssistantService(string version, string serviceName, Authenticator authenticator) : base(authenticator, serviceName) { Authenticator = authenticator; if (string.IsNullOrEmpty(version)) { throw new ArgumentNullException("`version` is required"); } else { Version = version; } if (string.IsNullOrEmpty(GetServiceUrl())) { SetServiceUrl(defaultServiceUrl); } } /// <summary> /// Create a session. /// /// Create a new session. A session is used to send user input to a skill and receive responses. It also /// maintains the state of the conversation. A session persists until it is deleted, or until it times out /// because of inactivity. (For more information, see the /// [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings). /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="assistantId">Unique identifier of the assistant. To find the assistant ID in the Watson /// Assistant user interface, open the assistant settings and click **API Details**. For information about /// creating assistants, see the /// [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). /// /// **Note:** Currently, the v2 API does not support creating assistants.</param> /// <returns><see cref="SessionResponse" />SessionResponse</returns> public bool CreateSession(Callback<SessionResponse> callback, string assistantId) { if (callback == null) throw new ArgumentNullException("`callback` is required for `CreateSession`"); if (string.IsNullOrEmpty(assistantId)) throw new ArgumentNullException("`assistantId` is required for `CreateSession`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); RequestObject<SessionResponse> req = new RequestObject<SessionResponse> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("conversation", "V2", "CreateSession")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.OnResponse = OnCreateSessionResponse; Connector.URL = GetServiceUrl() + string.Format("/v2/assistants/{0}/sessions", assistantId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnCreateSessionResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<SessionResponse> response = new DetailedResponse<SessionResponse>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<SessionResponse>(json); response.Response = json; } catch (Exception e) { Log.Error("AssistantService.OnCreateSessionResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<SessionResponse>)req).Callback != null) ((RequestObject<SessionResponse>)req).Callback(response, resp.Error); } /// <summary> /// Delete session. /// /// Deletes a session explicitly before it times out. (For more information about the session inactivity /// timeout, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings)). /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="assistantId">Unique identifier of the assistant. To find the assistant ID in the Watson /// Assistant user interface, open the assistant settings and click **API Details**. For information about /// creating assistants, see the /// [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). /// /// **Note:** Currently, the v2 API does not support creating assistants.</param> /// <param name="sessionId">Unique identifier of the session.</param> /// <returns><see cref="object" />object</returns> public bool DeleteSession(Callback<object> callback, string assistantId, string sessionId) { if (callback == null) throw new ArgumentNullException("`callback` is required for `DeleteSession`"); if (string.IsNullOrEmpty(assistantId)) throw new ArgumentNullException("`assistantId` is required for `DeleteSession`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (string.IsNullOrEmpty(sessionId)) throw new ArgumentNullException("`sessionId` is required for `DeleteSession`"); RequestObject<object> req = new RequestObject<object> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbDELETE, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("conversation", "V2", "DeleteSession")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.OnResponse = OnDeleteSessionResponse; Connector.URL = GetServiceUrl() + string.Format("/v2/assistants/{0}/sessions/{1}", assistantId, sessionId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnDeleteSessionResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<object> response = new DetailedResponse<object>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<object>(json); response.Response = json; } catch (Exception e) { Log.Error("AssistantService.OnDeleteSessionResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<object>)req).Callback != null) ((RequestObject<object>)req).Callback(response, resp.Error); } /// <summary> /// Send user input to assistant (stateful). /// /// Send user input to an assistant and receive a response, with conversation state (including context data) /// stored by Watson Assistant for the duration of the session. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="assistantId">Unique identifier of the assistant. To find the assistant ID in the Watson /// Assistant user interface, open the assistant settings and click **API Details**. For information about /// creating assistants, see the /// [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). /// /// **Note:** Currently, the v2 API does not support creating assistants.</param> /// <param name="sessionId">Unique identifier of the session.</param> /// <param name="input">An input object that includes the input text. (optional)</param> /// <param name="context">Context data for the conversation. You can use this property to set or modify context /// variables, which can also be accessed by dialog nodes. The context is stored by the assistant on a /// per-session basis. /// /// **Note:** The total size of the context data stored for a stateful session cannot exceed 100KB. /// (optional)</param> /// <param name="userId">A string value that identifies the user who is interacting with the assistant. The /// client must provide a unique identifier for each individual end user who accesses the application. For /// user-based plans, this user ID is used to identify unique users for billing purposes. This string cannot /// contain carriage return, newline, or tab characters. If no value is specified in the input, **user_id** is /// automatically set to the value of **context.global.session_id**. /// /// **Note:** This property is the same as the **user_id** property in the global system context. If **user_id** /// is specified in both locations, the value specified at the root is used. (optional)</param> /// <returns><see cref="MessageResponse" />MessageResponse</returns> public bool Message(Callback<MessageResponse> callback, string assistantId, string sessionId, MessageInput input = null, MessageContext context = null, string userId = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `Message`"); if (string.IsNullOrEmpty(assistantId)) throw new ArgumentNullException("`assistantId` is required for `Message`"); if (string.IsNullOrEmpty(sessionId)) throw new ArgumentNullException("`sessionId` is required for `Message`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); RequestObject<MessageResponse> req = new RequestObject<MessageResponse> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("conversation", "V2", "Message")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.Headers["Content-Type"] = "application/json"; req.Headers["Accept"] = "application/json"; JObject bodyObject = new JObject(); if (input != null) bodyObject["input"] = JToken.FromObject(input); if (context != null) bodyObject["context"] = JToken.FromObject(context); if (!string.IsNullOrEmpty(userId)) bodyObject["user_id"] = userId; req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); req.OnResponse = OnMessageResponse; Connector.URL = GetServiceUrl() + string.Format("/v2/assistants/{0}/sessions/{1}/message", assistantId, sessionId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnMessageResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<MessageResponse> response = new DetailedResponse<MessageResponse>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<MessageResponse>(json); response.Response = json; } catch (Exception e) { Log.Error("AssistantService.OnMessageResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<MessageResponse>)req).Callback != null) ((RequestObject<MessageResponse>)req).Callback(response, resp.Error); } /// <summary> /// Send user input to assistant (stateless). /// /// Send user input to an assistant and receive a response, with conversation state (including context data) /// managed by your application. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="assistantId">Unique identifier of the assistant. To find the assistant ID in the Watson /// Assistant user interface, open the assistant settings and click **API Details**. For information about /// creating assistants, see the /// [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). /// /// **Note:** Currently, the v2 API does not support creating assistants.</param> /// <param name="input">An input object that includes the input text. (optional)</param> /// <param name="context">Context data for the conversation. You can use this property to set or modify context /// variables, which can also be accessed by dialog nodes. The context is not stored by the assistant. To /// maintain session state, include the context from the previous response. /// /// **Note:** The total size of the context data for a stateless session cannot exceed 250KB. (optional)</param> /// <param name="userId">A string value that identifies the user who is interacting with the assistant. The /// client must provide a unique identifier for each individual end user who accesses the application. For /// user-based plans, this user ID is used to identify unique users for billing purposes. This string cannot /// contain carriage return, newline, or tab characters. If no value is specified in the input, **user_id** is /// automatically set to the value of **context.global.session_id**. /// /// **Note:** This property is the same as the **user_id** property in the global system context. If **user_id** /// is specified in both locations in a message request, the value specified at the root is used. /// (optional)</param> /// <returns><see cref="MessageResponseStateless" />MessageResponseStateless</returns> public bool MessageStateless(Callback<MessageResponseStateless> callback, string assistantId, MessageInputStateless input = null, MessageContextStateless context = null, string userId = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `MessageStateless`"); if (string.IsNullOrEmpty(assistantId)) throw new ArgumentNullException("`assistantId` is required for `MessageStateless`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); RequestObject<MessageResponseStateless> req = new RequestObject<MessageResponseStateless> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("conversation", "V2", "MessageStateless")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.Headers["Content-Type"] = "application/json"; req.Headers["Accept"] = "application/json"; JObject bodyObject = new JObject(); if (input != null) bodyObject["input"] = JToken.FromObject(input); if (context != null) bodyObject["context"] = JToken.FromObject(context); if (!string.IsNullOrEmpty(userId)) bodyObject["user_id"] = userId; req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); req.OnResponse = OnMessageStatelessResponse; Connector.URL = GetServiceUrl() + string.Format("/v2/assistants/{0}/message", assistantId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnMessageStatelessResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<MessageResponseStateless> response = new DetailedResponse<MessageResponseStateless>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<MessageResponseStateless>(json); response.Response = json; } catch (Exception e) { Log.Error("AssistantService.OnMessageStatelessResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<MessageResponseStateless>)req).Callback != null) ((RequestObject<MessageResponseStateless>)req).Callback(response, resp.Error); } /// <summary> /// Identify intents and entities in multiple user utterances. /// /// Send multiple user inputs to a dialog skill in a single request and receive information about the intents /// and entities recognized in each input. This method is useful for testing and comparing the performance of /// different skills or skill versions. /// /// This method is available only with Enterprise with Data Isolation plans. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="skillId">Unique identifier of the skill. To find the skill ID in the Watson Assistant user /// interface, open the skill settings and click **API Details**.</param> /// <param name="input">An array of input utterances to classify. (optional)</param> /// <returns><see cref="BulkClassifyResponse" />BulkClassifyResponse</returns> public bool BulkClassify(Callback<BulkClassifyResponse> callback, string skillId, List<BulkClassifyUtterance> input = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `BulkClassify`"); if (string.IsNullOrEmpty(skillId)) throw new ArgumentNullException("`skillId` is required for `BulkClassify`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); RequestObject<BulkClassifyResponse> req = new RequestObject<BulkClassifyResponse> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("conversation", "V2", "BulkClassify")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.Headers["Content-Type"] = "application/json"; req.Headers["Accept"] = "application/json"; JObject bodyObject = new JObject(); if (input != null && input.Count > 0) bodyObject["input"] = JToken.FromObject(input); req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); req.OnResponse = OnBulkClassifyResponse; Connector.URL = GetServiceUrl() + string.Format("/v2/skills/{0}/workspace/bulk_classify", skillId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnBulkClassifyResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<BulkClassifyResponse> response = new DetailedResponse<BulkClassifyResponse>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<BulkClassifyResponse>(json); response.Response = json; } catch (Exception e) { Log.Error("AssistantService.OnBulkClassifyResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<BulkClassifyResponse>)req).Callback != null) ((RequestObject<BulkClassifyResponse>)req).Callback(response, resp.Error); } /// <summary> /// List log events for an assistant. /// /// List the events from the log of an assistant. /// /// This method requires Manager access, and is available only with Enterprise plans. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="assistantId">Unique identifier of the assistant. To find the assistant ID in the Watson /// Assistant user interface, open the assistant settings and click **API Details**. For information about /// creating assistants, see the /// [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). /// /// **Note:** Currently, the v2 API does not support creating assistants.</param> /// <param name="sort">How to sort the returned log events. You can sort by **request_timestamp**. To reverse /// the sort order, prefix the parameter value with a minus sign (`-`). (optional)</param> /// <param name="filter">A cacheable parameter that limits the results to those matching the specified filter. /// For more information, see the /// [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-filter-reference#filter-reference). /// (optional)</param> /// <param name="pageLimit">The number of records to return in each page of results. (optional)</param> /// <param name="cursor">A token identifying the page of results to retrieve. (optional)</param> /// <returns><see cref="LogCollection" />LogCollection</returns> public bool ListLogs(Callback<LogCollection> callback, string assistantId, string sort = null, string filter = null, long? pageLimit = null, string cursor = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListLogs`"); if (string.IsNullOrEmpty(assistantId)) throw new ArgumentNullException("`assistantId` is required for `ListLogs`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); RequestObject<LogCollection> req = new RequestObject<LogCollection> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbGET, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("conversation", "V2", "ListLogs")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } if (!string.IsNullOrEmpty(sort)) { req.Parameters["sort"] = sort; } if (!string.IsNullOrEmpty(filter)) { req.Parameters["filter"] = filter; } if (pageLimit != null) { req.Parameters["page_limit"] = pageLimit; } if (!string.IsNullOrEmpty(cursor)) { req.Parameters["cursor"] = cursor; } req.OnResponse = OnListLogsResponse; Connector.URL = GetServiceUrl() + string.Format("/v2/assistants/{0}/logs", assistantId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnListLogsResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<LogCollection> response = new DetailedResponse<LogCollection>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<LogCollection>(json); response.Response = json; } catch (Exception e) { Log.Error("AssistantService.OnListLogsResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<LogCollection>)req).Callback != null) ((RequestObject<LogCollection>)req).Callback(response, resp.Error); } /// <summary> /// Delete labeled data. /// /// Deletes all data associated with a specified customer ID. The method has no effect if no data is associated /// with the customer ID. /// /// You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes /// data. For more information about personal data and customer IDs, see [Information /// security](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security). /// /// **Note:** This operation is intended only for deleting data associated with a single specific customer, not /// for deleting data associated with multiple customers or for any other purpose. For more information, see /// [Labeling and deleting data in Watson /// Assistant](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security-gdpr-wa). /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="customerId">The customer ID for which all data is to be deleted.</param> /// <returns><see cref="object" />object</returns> public bool DeleteUserData(Callback<object> callback, string customerId) { if (callback == null) throw new ArgumentNullException("`callback` is required for `DeleteUserData`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (string.IsNullOrEmpty(customerId)) throw new ArgumentNullException("`customerId` is required for `DeleteUserData`"); RequestObject<object> req = new RequestObject<object> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbDELETE, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("conversation", "V2", "DeleteUserData")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } if (!string.IsNullOrEmpty(customerId)) { req.Parameters["customer_id"] = customerId; } req.OnResponse = OnDeleteUserDataResponse; Connector.URL = GetServiceUrl() + "/v2/user_data"; Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnDeleteUserDataResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<object> response = new DetailedResponse<object>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<object>(json); response.Response = json; } catch (Exception e) { Log.Error("AssistantService.OnDeleteUserDataResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<object>)req).Callback != null) ((RequestObject<object>)req).Callback(response, resp.Error); } } }
using System; namespace ClosedXML.Excel { using System.Linq; internal class XLTableRange : XLRange, IXLTableRange { private readonly XLTable _table; private readonly XLRange _range; public XLTableRange(XLRange range, XLTable table) : base(new XLRangeParameters(range.RangeAddress, range.Style)) { _table = table; _range = range; } IXLTableRow IXLTableRange.FirstRow(Func<IXLTableRow, Boolean> predicate) { return FirstRow(predicate); } public XLTableRow FirstRow(Func<IXLTableRow, Boolean> predicate = null) { if (predicate == null) return new XLTableRow(this, (_range.FirstRow())); Int32 rowCount = _range.RowCount(); for (Int32 ro = 1; ro <= rowCount; ro++) { var row = new XLTableRow(this, (_range.Row(ro))); if (predicate(row)) return row; } return null; } IXLTableRow IXLTableRange.FirstRowUsed(Func<IXLTableRow, Boolean> predicate) { return FirstRowUsed(false, predicate); } public XLTableRow FirstRowUsed(Func<IXLTableRow, Boolean> predicate = null) { return FirstRowUsed(false, predicate); } IXLTableRow IXLTableRange.FirstRowUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate) { return FirstRowUsed(includeFormats, predicate); } public XLTableRow FirstRowUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate = null) { if (predicate == null) return new XLTableRow(this, (_range.FirstRowUsed(includeFormats))); Int32 rowCount = _range.RowCount(); for (Int32 ro = 1; ro <= rowCount; ro++) { var row = new XLTableRow(this, (_range.Row(ro))); if (!row.IsEmpty(includeFormats) && predicate(row)) return row; } return null; } IXLTableRow IXLTableRange.LastRow(Func<IXLTableRow, Boolean> predicate) { return LastRow(predicate); } public XLTableRow LastRow(Func<IXLTableRow, Boolean> predicate = null) { if (predicate == null) return new XLTableRow(this, (_range.LastRow())); Int32 rowCount = _range.RowCount(); for (Int32 ro = rowCount; ro >= 1; ro--) { var row = new XLTableRow(this, (_range.Row(ro))); if (predicate(row)) return row; } return null; } IXLTableRow IXLTableRange.LastRowUsed(Func<IXLTableRow, Boolean> predicate) { return LastRowUsed(false, predicate); } public XLTableRow LastRowUsed(Func<IXLTableRow, Boolean> predicate = null) { return LastRowUsed(false, predicate); } IXLTableRow IXLTableRange.LastRowUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate) { return LastRowUsed(includeFormats, predicate); } public XLTableRow LastRowUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate = null) { if (predicate == null) return new XLTableRow(this, (_range.LastRowUsed(includeFormats))); Int32 rowCount = _range.RowCount(); for (Int32 ro = rowCount; ro >= 1; ro--) { var row = new XLTableRow(this, (_range.Row(ro))); if (!row.IsEmpty(includeFormats) && predicate(row)) return row; } return null; } IXLTableRow IXLTableRange.Row(int row) { return Row(row); } public new XLTableRow Row(int row) { if (row <= 0 || row > XLHelper.MaxRowNumber) { throw new IndexOutOfRangeException(String.Format("Row number must be between 1 and {0}", XLHelper.MaxRowNumber)); } return new XLTableRow(this, base.Row(row)); } public IXLTableRows Rows(Func<IXLTableRow, Boolean> predicate = null) { var retVal = new XLTableRows(Worksheet.Style); Int32 rowCount = _range.RowCount(); for (int r = 1; r <= rowCount; r++) { var row = Row(r); if (predicate == null || predicate(row)) retVal.Add(row); } return retVal; } public new IXLTableRows Rows(int firstRow, int lastRow) { var retVal = new XLTableRows(Worksheet.Style); for (int ro = firstRow; ro <= lastRow; ro++) retVal.Add(Row(ro)); return retVal; } public new IXLTableRows Rows(string rows) { var retVal = new XLTableRows(Worksheet.Style); var rowPairs = rows.Split(','); foreach (string tPair in rowPairs.Select(pair => pair.Trim())) { String firstRow; String lastRow; if (tPair.Contains(':') || tPair.Contains('-')) { var rowRange = XLHelper.SplitRange(tPair); firstRow = rowRange[0]; lastRow = rowRange[1]; } else { firstRow = tPair; lastRow = tPair; } foreach (IXLTableRow row in Rows(Int32.Parse(firstRow), Int32.Parse(lastRow))) retVal.Add(row); } return retVal; } IXLTableRows IXLTableRange.RowsUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate) { return RowsUsed(includeFormats, predicate); } public IXLTableRows RowsUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate = null) { var rows = new XLTableRows(Worksheet.Style); Int32 rowCount = RowCount(); for (Int32 ro = 1; ro <= rowCount; ro++) { var row = Row(ro); if (!row.IsEmpty(includeFormats) && (predicate == null || predicate(row))) rows.Add(row); } return rows; } IXLTableRows IXLTableRange.RowsUsed(Func<IXLTableRow, Boolean> predicate) { return RowsUsed(predicate); } public IXLTableRows RowsUsed(Func<IXLTableRow, Boolean> predicate = null) { return RowsUsed(false, predicate); } IXLTable IXLTableRange.Table { get { return _table; } } public XLTable Table { get { return _table; } } public new IXLTableRows InsertRowsAbove(int numberOfRows) { return XLHelper.InsertRowsWithoutEvents(base.InsertRowsAbove, this, numberOfRows, !Table.ShowTotalsRow ); } public new IXLTableRows InsertRowsBelow(int numberOfRows) { return XLHelper.InsertRowsWithoutEvents(base.InsertRowsBelow, this, numberOfRows, !Table.ShowTotalsRow); } public new IXLRangeColumn Column(String column) { if (XLHelper.IsValidColumn(column)) { Int32 coNum = XLHelper.GetColumnNumberFromLetter(column); return coNum > ColumnCount() ? Column(_table.GetFieldIndex(column) + 1) : Column(coNum); } return Column(_table.GetFieldIndex(column) + 1); } } }
//------------------------------------------------------------------------------ // <copyright file="Compiler.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.IO; using System; using System.Text; using System.ComponentModel; using System.CodeDom.Compiler; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Security.Principal; using System.Security.Policy; using System.Threading; using System.Xml.Serialization.Configuration; using System.Globalization; using System.Runtime.Versioning; using System.Runtime.CompilerServices; internal class Compiler { bool debugEnabled = DiagnosticsSwitches.KeepTempFiles.Enabled; Hashtable imports = new Hashtable(); StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); [ResourceExposure(ResourceScope.Machine)] protected string[] Imports { get { string[] array = new string[imports.Values.Count]; imports.Values.CopyTo(array, 0); return array; } } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] [ResourceExposure(ResourceScope.None)] internal void AddImport(Type type, Hashtable types) { if (type == null) return; if (TypeScope.IsKnownType(type)) return; if (types[type] != null) return; types[type] = type; Type baseType = type.BaseType; if (baseType != null) AddImport(baseType, types); Type declaringType = type.DeclaringType; if (declaringType != null) AddImport(declaringType, types); foreach (Type intf in type.GetInterfaces()) AddImport(intf, types); ConstructorInfo[] ctors = type.GetConstructors(); for (int i = 0; i < ctors.Length; i++) { ParameterInfo[] parms = ctors[i].GetParameters(); for (int j = 0; j < parms.Length; j++) { AddImport(parms[j].ParameterType, types); } } if (type.IsGenericType) { Type[] arguments = type.GetGenericArguments(); for (int i = 0; i < arguments.Length; i++) { AddImport(arguments[i], types); } } TempAssembly.FileIOPermission.Assert(); Module module = type.Module; Assembly assembly = module.Assembly; if (DynamicAssemblies.IsTypeDynamic(type)) { DynamicAssemblies.Add(assembly); return; } object[] typeForwardedFromAttribute = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false); if (typeForwardedFromAttribute.Length > 0) { TypeForwardedFromAttribute originalAssemblyInfo = typeForwardedFromAttribute[0] as TypeForwardedFromAttribute; Assembly originalAssembly = Assembly.Load(originalAssemblyInfo.AssemblyFullName); imports[originalAssembly] = originalAssembly.Location; } imports[assembly] = assembly.Location; } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] [ResourceExposure(ResourceScope.None)] internal void AddImport(Assembly assembly) { TempAssembly.FileIOPermission.Assert(); imports[assembly] = assembly.Location; } internal TextWriter Source { get { return writer; } } internal void Close() { } [ResourceConsumption(ResourceScope.Machine)] [ResourceExposure(ResourceScope.Machine)] internal static string GetTempAssemblyPath(string baseDir, Assembly assembly, string defaultNamespace) { if (assembly.IsDynamic) { throw new InvalidOperationException(Res.GetString(Res.XmlPregenAssemblyDynamic)); } PermissionSet perms = new PermissionSet(PermissionState.None); perms.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); perms.Assert(); try { if (baseDir != null && baseDir.Length > 0) { // check that the dirsctory exists if (!Directory.Exists(baseDir)) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlPregenMissingDirectory, baseDir)); } } else { baseDir = Path.GetTempPath(); // check that the dirsctory exists if (!Directory.Exists(baseDir)) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlPregenMissingTempDirectory)); } } #if MONO baseDir = Path.Combine (baseDir, GetTempAssemblyName(assembly.GetName(), defaultNamespace)); #else if (baseDir.EndsWith("\\", StringComparison.Ordinal)) baseDir += GetTempAssemblyName(assembly.GetName(), defaultNamespace); else baseDir += "\\" + GetTempAssemblyName(assembly.GetName(), defaultNamespace); #endif } finally { CodeAccessPermission.RevertAssert(); } return baseDir + ".dll"; } internal static string GetTempAssemblyName(AssemblyName parent, string ns) { return parent.Name + ".XmlSerializers" + (ns == null || ns.Length == 0 ? "" : "." + ns.GetHashCode()); } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] [ResourceExposure(ResourceScope.None)] internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) { CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters parameters = xmlParameters.CodeDomParameters; parameters.ReferencedAssemblies.AddRange(Imports); if (debugEnabled) { parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = true; parameters.TempFiles.KeepFiles = true; } PermissionSet perms = new PermissionSet(PermissionState.None); if (xmlParameters.IsNeedTempDirAccess) { perms.AddPermission(TempAssembly.FileIOPermission); } perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence)); perms.Assert(); if (parent != null && (parameters.OutputAssembly == null || parameters.OutputAssembly.Length ==0)) { string assemblyName = AssemblyNameFromOptions(parameters.CompilerOptions); if (assemblyName == null) assemblyName = GetTempAssemblyPath(parameters.TempFiles.TempDir, parent, ns); // parameters.OutputAssembly = assemblyName; } if (parameters.CompilerOptions == null || parameters.CompilerOptions.Length == 0) parameters.CompilerOptions = "/nostdlib"; else parameters.CompilerOptions += " /nostdlib"; parameters.CompilerOptions += " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION"; #pragma warning disable 618 parameters.Evidence = evidence; #pragma warning restore 618 CompilerResults results = null; Assembly assembly = null; try { results = codeProvider.CompileAssemblyFromSource(parameters, writer.ToString()); // check the output for errors or a certain level-1 warning (1595) if (results.Errors.Count > 0) { StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); stringWriter.WriteLine(Res.GetString(Res.XmlCompilerError, results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture))); bool foundOne = false; foreach (CompilerError e in results.Errors) { // clear filename. This makes ToString() print just error number and message. e.FileName = ""; if (!e.IsWarning || e.ErrorNumber == "CS1595") { foundOne = true; stringWriter.WriteLine(e.ToString()); } } if (foundOne) { throw new InvalidOperationException(stringWriter.ToString()); } } assembly = results.CompiledAssembly; } catch (UnauthorizedAccessException) { // try to get the user token string user = GetCurrentUser(); if (user == null || user.Length == 0) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlSerializerAccessDenied)); } else { throw new UnauthorizedAccessException(Res.GetString(Res.XmlIdentityAccessDenied, user)); } } catch (FileLoadException fle) { throw new InvalidOperationException(Res.GetString(Res.XmlSerializerCompileFailed), fle); } finally { CodeAccessPermission.RevertAssert(); } // somehow we got here without generating an assembly if (assembly == null) throw new InvalidOperationException(Res.GetString(Res.XmlInternalError)); return assembly; } static string AssemblyNameFromOptions(string options) { if (options == null || options.Length == 0) return null; string outName = null; string[] flags = options.ToLower(CultureInfo.InvariantCulture).Split(null); for (int i = 0; i < flags.Length; i++) { string val = flags[i].Trim(); if (val.StartsWith("/out:", StringComparison.Ordinal)) { outName = val.Substring(5); } } return outName; } internal static string GetCurrentUser() { #if !FEATURE_PAL try { WindowsIdentity id = WindowsIdentity.GetCurrent(); if (id != null && id.Name != null) return id.Name; } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } } #endif // !FEATURE_PAL return ""; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //#define PERFORMANCE_TESTING using System; using Xunit; using System.Drawing.Graphics; using System.IO; using System.Diagnostics; using System.Reflection; using System.Threading.Tasks; public partial class GraphicsUnitTests { /* Functionality test Constants */ static string SquareCatLogicalName = "SquareCatJpeg"; static string BlackCatLogicalName = "BlackCatPng"; static string SoccerCatLogicalName = "SoccerCatJpeg"; static string CuteCatLogicalName = "CuteCatPng"; /* Performance Tests Constants */ #if PERFORMANCE_TESTING static StreamWriter streamwriter; static Stopwatch stopwatchSingleThread = new Stopwatch(); static Stopwatch stopwatchMultiThread = new Stopwatch(); /* Performance Tests Variables */ static string jpegCatPath = ""; static string jpegDogPath = ""; static string pngCatPath = ""; static string pngDogPath = ""; #endif /*----------------------Functionality Unit Tests------------------------------------*/ private static void ValidateImagePng(Image img, string embeddedLogicalName) { Stream toCompare = typeof(GraphicsUnitTests).GetTypeInfo().Assembly.GetManifestResourceStream(embeddedLogicalName); Image comparison = Png.Load(toCompare); Assert.Equal(comparison.HeightInPixels, img.HeightInPixels); Assert.Equal(comparison.WidthInPixels, img.WidthInPixels); Assert.Equal(comparison.TrueColor, img.TrueColor); } private static void ValidateImageJpeg(Image img, string embeddedLogicalName) { Stream toCompare = typeof(GraphicsUnitTests).GetTypeInfo().Assembly.GetManifestResourceStream(embeddedLogicalName); Image comparison = Jpg.Load(toCompare); Assert.Equal(comparison.HeightInPixels, img.HeightInPixels); Assert.Equal(comparison.WidthInPixels, img.WidthInPixels); Assert.Equal(comparison.TrueColor, img.TrueColor); } private static void ValidateCreatedImage(Image img, int widthToCompare, int heightToCompare) { Assert.Equal(widthToCompare, img.WidthInPixels); Assert.Equal(heightToCompare, img.HeightInPixels); } private static string ChooseExtension(string filepath) { if (filepath.Contains("Jpeg")) return ".jpg"; else return ".png"; } private static string SaveEmbeddedResourceToFile(string logicalName) { //get a temp file path string toReturn = Path.GetTempFileName(); toReturn = Path.ChangeExtension(toReturn, ChooseExtension(logicalName)); //get stream of embedded resoruce Stream embeddedResourceStream = typeof(GraphicsUnitTests).GetTypeInfo().Assembly.GetManifestResourceStream(logicalName); //write stream to temp file path using (FileStream fileStream = new FileStream(toReturn, FileMode.OpenOrCreate)) { embeddedResourceStream.Seek(0, SeekOrigin.Begin); embeddedResourceStream.CopyTo(fileStream); } //return where the resource is saved return toReturn; } /* Tests Create Method */ [Fact] public static void WhenCreatingAnEmptyImageThenValidateAnImage() { Image emptyTenSquare = Image.Create(10, 10); ValidateCreatedImage(emptyTenSquare, 10, 10); } [Fact] public void WhenCreatingABlankImageWithNegativeHeightThenThrowException() { Assert.Throws<InvalidOperationException>(() => Image.Create(1, -1)); } [Fact] public void WhenCreatingABlankImageWithNegativeWidthThenThrowException() { Assert.Throws<InvalidOperationException>(() => Image.Create(-1, 1)); } [Fact] public void WhenCreatingABlankImageWithNegativeSizesThenThrowException() { Assert.Throws<InvalidOperationException>(() => Image.Create(-1, -1)); } [Fact] public void WhenCreatingABlankImageWithZeroHeightThenThrowException() { Assert.Throws<InvalidOperationException>(() => Image.Create(1, 0)); } [Fact] public void WhenCreatingABlankImageWithZeroWidthThenThrowException() { Assert.Throws<InvalidOperationException>(() => Image.Create(0, 1)); } [Fact] public void WhenCreatingABlankImageWithZeroParametersThenThrowException() { Assert.Throws<InvalidOperationException>(() => Image.Create(0, 0)); } /* Tests Load(filepath) method */ [Fact] public void WhenCreatingAJpegFromAValidFileGiveAValidImage() { //save embedded resource to a file string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName); //read it Image newJpeg = Jpg.Load(filepath); File.Delete(filepath); //validate it ValidateImageJpeg(newJpeg, SquareCatLogicalName); } [Fact] public void WhenCreatingAPngFromAValidFileGiveAValidImage() { //save embedded resource to a file string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); //read it Image newJpeg = Png.Load(filepath); File.Delete(filepath); //validate it ValidateImagePng(newJpeg, BlackCatLogicalName); } [Fact] public void WhenCreatingAJpegFromAMalformedPathThenThrowException() { //place holder string to demonstrate what would be the error case string temporaryPath = Path.GetTempPath(); string invalidFilepath = temporaryPath + "\\Hi.jpg"; Assert.Throws<FileNotFoundException>(() => Jpg.Load(invalidFilepath)); } [Fact] public void WhenCreatingAPngFromAMalformedPathThenThrowException() { string temporaryPath = Path.GetTempPath(); string invalidFilepath = temporaryPath + "\\Hi.png"; Assert.Throws<FileNotFoundException>(() => Png.Load(invalidFilepath)); } [Fact] public void WhenCreatingAnImageFromAnUnfoundPathThenThrowException() { string temporaryPath = Path.GetTempPath(); string invalidFilepath = temporaryPath + "\\Hi.jpg"; Assert.Throws<FileNotFoundException>(() => Jpg.Load(invalidFilepath)); } [Fact] public void WhenCreatingAnImageFromAFileTypeThatIsNotAnImageThenThrowException() { string temporaryPath = Path.GetTempPath(); string invalidFilepath = temporaryPath + "text.txt"; Assert.Throws<FileNotFoundException>(() => Jpg.Load(invalidFilepath)); } /* Tests Load(stream) mehtod*/ [Fact] public void WhenCreatingAJpegFromAValidStreamThenWriteAValidImageToFile() { string filepath = SaveEmbeddedResourceToFile(SoccerCatLogicalName); using (FileStream filestream = new FileStream(filepath, FileMode.Open)) { Image fromStream = Jpg.Load(filestream); ValidateImageJpeg(fromStream, SoccerCatLogicalName); } File.Delete(filepath); } [Fact] public void WhenCreatingAPngFromAValidStreamThenWriteAValidImageToFile() { string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName); using (FileStream filestream = new FileStream(filepath, FileMode.Open)) { Image fromStream = Png.Load(filestream); ValidateImagePng(fromStream, CuteCatLogicalName); } File.Delete(filepath); } [Fact] public void WhenCreatingAnImageFromAnInvalidStreamThenThrowException() { Stream stream = null; Assert.Throws<InvalidOperationException>(() => Png.Load(stream)); } /* Test Resize */ [Fact] public void WhenResizingEmptyImageDownThenGiveAValidatedResizedImage() { Image emptyResizeSquare = Image.Create(100, 100); emptyResizeSquare = emptyResizeSquare.Resize(10, 10); ValidateCreatedImage(emptyResizeSquare, 10, 10); } [Fact] public void WhenResizingEmptyImageUpThenGiveAValidatedResizedImage() { Image emptyResizeSquare = Image.Create(100, 100); emptyResizeSquare = emptyResizeSquare.Resize(200, 200); ValidateCreatedImage(emptyResizeSquare, 200, 200); } [Fact] public void WhenResizingJpegLoadedFromFileThenGiveAValidatedResizedImage() { //what to do? Have embedded resource stream of expected result? string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName); Image fromFileResizeSquare = Jpg.Load(filepath); fromFileResizeSquare = fromFileResizeSquare.Resize(200, 200); ValidateCreatedImage(fromFileResizeSquare, 200, 200); File.Delete(filepath); } [Fact] public void WhenResizingPngLoadedFromFileThenGiveAValidatedResizedImage() { //what to do? Have embedded resource stream of expected result? string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image fromFileResizeSquare = Png.Load(filepath); fromFileResizeSquare = fromFileResizeSquare.Resize(400, 400); ValidateCreatedImage(fromFileResizeSquare, 400, 400); File.Delete(filepath); } [Fact] public void WhenResizingJpegLoadedFromStreamThenGiveAValidatedResizedImage() { string filepath = SaveEmbeddedResourceToFile(SoccerCatLogicalName); using (FileStream filestream = new FileStream(filepath, FileMode.Open)) { Image fromStream = Jpg.Load(filestream); fromStream = fromStream.Resize(400, 400); ValidateCreatedImage(fromStream, 400, 400); } File.Delete(filepath); } [Fact] public void WhenResizingPngLoadedFromStreamThenGiveAValidatedResizedImage() { string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName); using (FileStream filestream = new FileStream(filepath, FileMode.Open)) { Image fromStream = Png.Load(filestream); fromStream = fromStream.Resize(400, 400); ValidateCreatedImage(fromStream, 400, 400); } File.Delete(filepath); } /* Testing Resize parameters */ [Fact] public void WhenResizingImageGivenNegativeHeightThenThrowException() { Image img = Image.Create(1, 1); Assert.Throws<InvalidOperationException>(() => img.Resize(-1, 1)); } [Fact] public void WhenResizingImageGivenNegativeWidthThenThrowException() { Image img = Image.Create(1, 1); Assert.Throws<InvalidOperationException>(() => img.Resize(1, -1)); } [Fact] public void WhenResizingImageGivenNegativeSizesThenThrowException() { Image img = Image.Create(1, 1); Assert.Throws<InvalidOperationException>(() => img.Resize(-1, -1)); } [Fact] public void WhenResizingImageGivenZeroHeightThenThrowException() { Image img = Image.Create(1, 1); Assert.Throws<InvalidOperationException>(() => img.Resize(0, 1)); } [Fact] public void WhenResizingImageGivenZeroWidthThenThrowException() { Image img = Image.Create(1, 1); Assert.Throws<InvalidOperationException>(() => img.Resize(1, 0)); } [Fact] public void WhenResizingImageGivenZeroSizesThenThrowException() { Image img = Image.Create(1, 1); Assert.Throws<InvalidOperationException>(() => img.Resize(0, 0)); } /*Tests CircleCrop*/ //Tests filpath //Tests jpg [Fact] public void WhenCropingAnJpgImageFromFileGiveACorrectCroppedImage() { //checking with cat image string filepath = @"C:\Users\t-roblo\Pictures\PerfTestImages\jpgcat.jpg"; Image avatarImage = Jpg.Load(filepath); Image newImage = avatarImage.CircleCrop(); Png.WriteToFile(newImage, @"C:\Users\t-roblo\Pictures\jpgcatf.png"); } //Tests png [Fact] public void WhenCropingAnPngImageFromFileGiveACorrectCroppedImage() { //checking with cat image string filepath = @"C:\Users\t-roblo\Pictures\PerfTestImages\pngcat.png"; Image avatarImage = Png.Load(filepath); Image newImage = avatarImage.CircleCrop(); Png.WriteToFile(newImage, @"C:\Users\t-roblo\Pictures\pngcatf.png"); } //Tests stream //Tests jpg [Fact] public void WhenCropingAnJpgImageFromFileStreamACorrectCroppedImage() { //checking with cat image using (FileStream filestream = new FileStream(@"C:\Users\t-roblo\Pictures\PerfTestImages\jpgcat.jpg", FileMode.Open)) { Image avatarImage = Jpg.Load(filestream); Image newImage = avatarImage.CircleCrop(); Png.WriteToFile(newImage, @"C:\Users\t-roblo\Pictures\jpgcats.png"); } } //Tests png [Fact] public void WhenCropingAnPngImageFromFileStreamACorrectCroppedImage() { //checking with cat image using (FileStream filestream = new FileStream(@"C:\Users\t-roblo\Pictures\PerfTestImages\pngcat.png", FileMode.Open)) { Image avatarImage = Png.Load(filestream); Image newImage = avatarImage.CircleCrop(); Png.WriteToFile(newImage, @"C:\Users\t-roblo\Pictures\pngcats.png"); } } /* Test WriteToFile */ [Fact] public void WhenWritingABlankCreatedJpegToAValidFileWriteToAValidFile() { Image emptyImage = Image.Create(10, 10); ValidateCreatedImage(emptyImage, 10, 10); string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".jpg"); Jpg.WriteToFile(emptyImage, tempFilePath); File.Delete(tempFilePath); } [Fact] public void WhenWritingABlankCreatedPngToAValidFileWriteToAValidFile() { Image emptyImage = Image.Create(10, 10); ValidateCreatedImage(emptyImage, 10, 10); string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png"); Png.WriteToFile(emptyImage, tempFilePath); File.Delete(tempFilePath); } [Fact] public void WhenWritingAJpegCreatedFromFileToAValidFileWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName); Image fromFile = Jpg.Load(filepath); ValidateImageJpeg(fromFile, SquareCatLogicalName); string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".jpg"); Png.WriteToFile(fromFile, tempFilePath); File.Delete(filepath); File.Delete(tempFilePath); } [Fact] public void WhenWritingAPngCreatedFromFileToAValidFileWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image fromFile = Png.Load(filepath); ValidateImagePng(fromFile, BlackCatLogicalName); string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png"); Png.WriteToFile(fromFile, tempFilePath); File.Delete(filepath); File.Delete(tempFilePath); } [Fact] public void WhenWritingAPngMadeTransparentToAValidFileWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image img = Png.Load(filepath); ValidateImagePng(img, BlackCatLogicalName); img.SetAlphaPercentage(.2); ValidateImagePng(img, BlackCatLogicalName); string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png"); Png.WriteToFile(img, tempFilePath); File.Delete(filepath); File.Delete(tempFilePath); } [Fact] public void WhenWritingATransparentResizedPngToAValidFileWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image img = Png.Load(filepath); ValidateImagePng(img, BlackCatLogicalName); img.SetAlphaPercentage(.2); img = img.Resize(400, 400); ValidateCreatedImage(img, 400, 400); string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png"); Png.WriteToFile(img, tempFilePath); File.Delete(filepath); File.Delete(tempFilePath); } [Fact] public void WhenWritingAResizedTransparentPngToAValidFileWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image img = Png.Load(filepath); ValidateImagePng(img, BlackCatLogicalName); img = img.Resize(400, 400); ValidateCreatedImage(img, 400, 400); img.SetAlphaPercentage(.2); string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png"); Png.WriteToFile(img, tempFilePath); File.Delete(filepath); File.Delete(tempFilePath); } /* Tests Writing to a Stream*/ [Fact] public void WhenWritingABlankCreatedJpegToAValidStreamWriteToAValidStream() { Image img = Image.Create(100, 100); using (MemoryStream stream = new MemoryStream()) { Jpg.WriteToStream(img, stream); stream.Position = 0; Image img2 = Jpg.Load(stream); ValidateCreatedImage(img2, 100, 100); } } [Fact] public void WhenWritingABlankCreatedPngToAValidStreamWriteToAValidStream() { Image img = Image.Create(100, 100); using (MemoryStream stream = new MemoryStream()) { Png.WriteToStream(img, stream); stream.Position = 0; Image img2 = Png.Load(stream); ValidateCreatedImage(img2, 100, 100); } } [Fact] public void WhenWritingAJpegFromFileToAValidStreamWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(SoccerCatLogicalName); Image img = Jpg.Load(filepath); using (MemoryStream stream = new MemoryStream()) { Jpg.WriteToStream(img, stream); stream.Position = 0; Image img2 = Jpg.Load(stream); ValidateImageJpeg(img2, SoccerCatLogicalName); } File.Delete(filepath); } [Fact] public void WhenWritingAPngCreatedFromFileToAValidStreamWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName); Image img = Png.Load(filepath); using (MemoryStream stream = new MemoryStream()) { Png.WriteToStream(img, stream); stream.Position = 0; Image img2 = Png.Load(stream); ValidateImagePng(img2, CuteCatLogicalName); } File.Delete(filepath); } [Fact] public void WhenWritingAResizedJpegToAValidStreamWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(SoccerCatLogicalName); Image img = Jpg.Load(filepath); using (MemoryStream stream = new MemoryStream()) { img = img.Resize(40, 40); ValidateCreatedImage(img, 40, 40); Jpg.WriteToStream(img, stream); stream.Position = 0; Image img2 = Jpg.Load(stream); ValidateCreatedImage(img, 40, 40); } File.Delete(filepath); } [Fact] public void WhenWritingAResizedPngToAValidStreamWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName); Image img = Png.Load(filepath); using (MemoryStream stream = new MemoryStream()) { img = img.Resize(40, 40); ValidateCreatedImage(img, 40, 40); Png.WriteToStream(img, stream); stream.Position = 0; Image img2 = Png.Load(stream); ValidateCreatedImage(img, 40, 40); } File.Delete(filepath); } [Fact] public void WhenWritingAPngMadeTransparentToAValidStreamWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName); Image img = Png.Load(filepath); using (MemoryStream stream = new MemoryStream()) { img.SetAlphaPercentage(.2); ValidateImagePng(img, CuteCatLogicalName); Png.WriteToStream(img, stream); stream.Position = 0; Image img2 = Png.Load(stream); ValidateImagePng(img2, CuteCatLogicalName); } File.Delete(filepath); } [Fact] public void WhenWritingATransparentResizedPngToAValidStreamWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName); Image img = Png.Load(filepath); using (MemoryStream stream = new MemoryStream()) { img.SetAlphaPercentage(.2); img = img.Resize(400, 400); ValidateCreatedImage(img, 400, 400); Png.WriteToStream(img, stream); stream.Position = 0; Image img2 = Png.Load(stream); ValidateCreatedImage(img2, 400, 400); } File.Delete(filepath); } [Fact] public void WhenWritingAResizedTransparentPngToAValidStreamWriteAValidImage() { string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName); Image img = Png.Load(filepath); ValidateImagePng(img, CuteCatLogicalName); img = img.Resize(400, 400); ValidateCreatedImage(img, 400, 400); img.SetAlphaPercentage(.2); File.Delete(filepath); } /* Test Draw */ [Fact] public void WhenDrawingTwoImagesWriteACorrectResult() { //open yellow cat image string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName); Image yellowCat = Jpg.Load(filepath); ValidateImageJpeg(yellowCat, SquareCatLogicalName); //open black cat image string filepath2 = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image blackCat = Jpg.Load(filepath2); ValidateImagePng(blackCat, BlackCatLogicalName); //draw yellowCat.Draw(blackCat, 0, 0); ValidateImageJpeg(yellowCat, SquareCatLogicalName); File.Delete(filepath); File.Delete(filepath2); } /* Test SetTransparency */ [Fact] public void WhenSettingTheTransparencyOfAnImageWriteAnImageWithChangedTransparency() { //open black cat image string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image blackCat0 = Jpg.Load(filepath); ValidateImagePng(blackCat0, BlackCatLogicalName); blackCat0.SetAlphaPercentage(0); ValidateImagePng(blackCat0, BlackCatLogicalName); Image blackCat1 = Jpg.Load(filepath); ValidateImagePng(blackCat1, BlackCatLogicalName); blackCat0.SetAlphaPercentage(0.5); ValidateImagePng(blackCat1, BlackCatLogicalName); Image blackCat2 = Jpg.Load(filepath); ValidateImagePng(blackCat2, BlackCatLogicalName); blackCat0.SetAlphaPercentage(1); ValidateImagePng(blackCat2, BlackCatLogicalName); File.Delete(filepath); } /* Test Draw and Set Transparency */ [Fact] public void WhenDrawingAnImageWithTransparencyChangedGiveACorrectWrittenFile() { //black cat load string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image blackCat = Jpg.Load(filepath); ValidateImagePng(blackCat, BlackCatLogicalName); blackCat.SetAlphaPercentage(0.5); //yellow cat load string filepath2 = SaveEmbeddedResourceToFile(SquareCatLogicalName); Image yellowCat = Jpg.Load(filepath2); ValidateImageJpeg(yellowCat, SquareCatLogicalName); yellowCat.Draw(blackCat, 0, 0); ValidateImageJpeg(yellowCat, SquareCatLogicalName); } [Fact] public static void WhenAddingAGreyScaleFilterToAJpegGiveAValidGreyScaledImage() { string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName); Image img1 = Jpg.Load(filepath); img1.ApplyMatrixMultiplier(ImageExtensions.GreyScaleMatrix); ValidateImageJpeg(img1, SquareCatLogicalName); Jpg.WriteToFile(img1, Path.GetTempPath() + "GreyscaleCat.jpg"); } [Fact] public static void WhenAddingAGreyScaleFilterToAPngGiveAValidGreyScaledImage() { string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image img1 = Png.Load(filepath); img1.ApplyMatrixMultiplier(ImageExtensions.GreyScaleMatrix); ValidateImagePng(img1, BlackCatLogicalName); Png.WriteToFile(img1, Path.GetTempPath() + "GreyscaleCat.png"); } [Fact] public static void WhenAddingASepiaFilterToAJpegGiveAValidGreyScaledImage() { string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName); Image img1 = Jpg.Load(filepath); img1.ApplyMatrixMultiplier(ImageExtensions.SepiaMatrix); ValidateImageJpeg(img1, SquareCatLogicalName); Jpg.WriteToFile(img1, Path.GetTempPath() + "SepiaCat.jpg"); } [Fact] public static void WhenAddingASepiaFilterToAPngGiveAValidGreyScaledImage() { string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName); Image img1 = Png.Load(filepath); img1.ApplyMatrixMultiplier(ImageExtensions.SepiaMatrix); ValidateImagePng(img1, CuteCatLogicalName); Png.WriteToFile(img1, Path.GetTempPath() + "SepiaCat.png"); } [Fact] public static void WhenAddingANegativeFilterToAJpegGiveAValidGreyScaledImage() { string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName); Image img1 = Jpg.Load(filepath); img1.ApplyMatrixMultiplier(ImageExtensions.NegativeMatrix); ValidateImageJpeg(img1, SquareCatLogicalName); Jpg.WriteToFile(img1, Path.GetTempPath() + "NegativeCat.jpg"); } [Fact] public static void WhenAddingANegativeFilterToAPngGiveAValidGreyScaledImage() { string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName); Image img1 = Png.Load(filepath); img1.ApplyMatrixMultiplier(ImageExtensions.NegativeMatrix); ValidateImagePng(img1, BlackCatLogicalName); Png.WriteToFile(img1, Path.GetTempPath() + "NegativeCat.png"); } /* ------------------Performance Tests-------------------------*/ #if PERFORMANCE_TESTING [Fact] public static void RunAllPerfTests() { string filepath = Path.GetTempPath() + "Trial1Results.txt"; if (File.Exists(filepath)) File.Delete(filepath); FileStream fstream = new FileStream(filepath, FileMode.OpenOrCreate); streamwriter = new StreamWriter(fstream); //set temppaths of files perf test images SetTempPathsOfPerfTestFiles(); runTests(1); runTests(10); runTests(100); runTests(1000); runTests(5000); streamwriter.Dispose(); fstream.Dispose(); //delete perf test images files DeletePerfTestFileConstants(); } public static void runTests(int numRuns) { WriteTestHeader(numRuns); //LoadFileJpg WriteCurrentTest("LoadFileJpeg", numRuns); LoadFileJpegPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "LoadFileJpeg"); //LoadFilePng WriteCurrentTest("LoadFilePng", numRuns); LoadFilePngPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "LoadFilePng"); //WriteFileJpg WriteCurrentTest("WriteFileJpeg", numRuns); WriteFileJpegPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "WriteFileJpeg"); //WriteFilePng WriteCurrentTest("WriteFilePng", numRuns); WriteFilePngPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "WriteFilePng"); //ResizeJpg WriteCurrentTest("ResizeJpeg", numRuns); ResizeJpegPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "ResizeJpeg"); //resize png WriteCurrentTest("ResizePng", numRuns); ResizePngPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "ResizePng"); //ChangeAlphaJpg WriteCurrentTest("ChangeAlphaJpeg", numRuns); ChangeAlphaJpegPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "ChangeAlphaJpeg"); //ChangeAlphaPng WriteCurrentTest("ChangeAlphaPng", numRuns); ChangeAlphaPngPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "ChangeAlphaPng"); //DrawJpgOverJpg WriteCurrentTest("DrawJpegOverJpeg", numRuns); DrawJpegOverJpegPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "DrawJpegOverJpeg"); //DrawPngOverPng WriteCurrentTest("DrawPngOverPng", numRuns); DrawPngOverPngPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "DrawPngOverPng"); //DrawJpgOverPng WriteCurrentTest("DrawJpegOverPng", numRuns); DrawJpegOverPngPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "DrawJpegOverPng"); //DrawPngOverJpg WriteCurrentTest("DrawPngOverJpeg", numRuns); DrawPngOverJpegPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "DrawPngOverJpeg"); //LoadStreamJpg WriteCurrentTest("LoadStreamJpeg", numRuns); LoadStreamJpegPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "LoadStreamJpeg"); //LoadStreamPng WriteCurrentTest("LoadStreamPng", numRuns); LoadStreamPngPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "LoadStreamPng"); //WriteStreamJpg WriteCurrentTest("WriteStreamJpeg", numRuns); WriteStreamJpegPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "WriteStreamJpeg"); //WriteStreamPng WriteCurrentTest("WriteStreamPng", numRuns); WriteStreamPngPerfTest(numRuns); WriteStopWatch(stopwatchSingleThread, "WriteStreamPng"); } [Fact] public static void SetUpAllPerfTestsWithThreads() { int numOfTasks = 4; string filepath = Path.GetTempPath() + "Trial2Results.txt"; if (File.Exists(filepath)) File.Delete(filepath); //set temp paths of files perf test images SetTempPathsOfPerfTestFiles(); FileStream fstream = new FileStream(filepath, FileMode.OpenOrCreate); streamwriter = new StreamWriter(fstream); WriteTestHeader(1); RunAllPerfTestsWithThreads(numOfTasks, 1); WriteTestHeader(10); RunAllPerfTestsWithThreads(numOfTasks, 10); WriteTestHeader(100); RunAllPerfTestsWithThreads(numOfTasks, 100); WriteTestHeader(1000); RunAllPerfTestsWithThreads(numOfTasks, 1000); WriteTestHeader(5000); RunAllPerfTestsWithThreads(numOfTasks, 5000); streamwriter.Dispose(); fstream.Dispose(); //delete temp perf tests images files DeletePerfTestFileConstants(); } private static void RunAllPerfTestsWithThreads(int numOfTasks, int numRuns) { RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "LoadFileJpegPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "LoadFilePngPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "WriteFileJpegPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "WriteFilePngPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "ResizeJpegPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "ResizePngPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "ChangeAlphaJpegPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "ChangeAlphaPngPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "DrawJpegOverJpegPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "DrawPngOverPngPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "DrawJpegOverPngPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "DrawPngOverJpegPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "LoadStreamJpegPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "LoadStreamPngPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "WriteStreamJpegPerfTest"); RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "WriteStreamPngPerfTest"); } private static void RunOneFuntionWithMultipleTasks(int numOfTasks, int numRuns, string functionToRun) { WriteCurrentTest(functionToRun, numRuns); Task[] tasks = new Task[numOfTasks]; stopwatchMultiThread.Start(); for (int i = 0; i < numOfTasks; i++) { switch (functionToRun) { case "LoadFileJpegPerfTest": tasks[i] = Task.Factory.StartNew(() => LoadFileJpegPerfTest(numRuns / numOfTasks)); break; case "LoadFilePngPerfTest": tasks[i] = Task.Factory.StartNew(() => LoadFilePngPerfTest(numRuns / numOfTasks)); break; case "WriteFileJpegPerfTest": tasks[i] = Task.Factory.StartNew(() => WriteFileJpegPerfTest(numRuns / numOfTasks)); break; case "WriteFilePngPerfTest": tasks[i] = Task.Factory.StartNew(() => WriteFilePngPerfTest(numRuns / numOfTasks)); break; case "ResizeJpegPerfTest": tasks[i] = Task.Factory.StartNew(() => ResizeJpegPerfTest(numRuns / numOfTasks)); break; case "ResizePngPerfTest": tasks[i] = Task.Factory.StartNew(() => ResizePngPerfTest(numRuns / numOfTasks)); break; case "ChangeAlphaJpegPerfTest": tasks[i] = Task.Factory.StartNew(() => ChangeAlphaJpegPerfTest(numRuns / numOfTasks)); break; case "ChangeAlphaPngPerfTest": tasks[i] = Task.Factory.StartNew(() => ChangeAlphaPngPerfTest(numRuns / numOfTasks)); break; case "DrawJpegOverJpegPerfTest": tasks[i] = Task.Factory.StartNew(() => DrawJpegOverJpegPerfTest(numRuns / numOfTasks)); break; case "DrawPngOverPngPerfTest": tasks[i] = Task.Factory.StartNew(() => DrawPngOverPngPerfTest(numRuns / numOfTasks)); break; case "DrawJpegOverPngPerfTest": tasks[i] = Task.Factory.StartNew(() => DrawJpegOverPngPerfTest(numRuns / numOfTasks)); break; case "DrawPngOverJpegPerfTest": tasks[i] = Task.Factory.StartNew(() => DrawPngOverJpegPerfTest(numRuns / numOfTasks)); break; case "LoadStreamJpegPerfTest": tasks[i] = Task.Factory.StartNew(() => LoadStreamJpegPerfTest(numRuns / numOfTasks)); break; case "LoadStreamPngPerfTest": tasks[i] = Task.Factory.StartNew(() => LoadStreamPngPerfTest(numRuns / numOfTasks)); break; case "WriteStreamJpegPerfTest": tasks[i] = Task.Factory.StartNew(() => WriteStreamJpegPerfTest(numRuns / numOfTasks)); break; case "WriteStreamPngPerfTest": tasks[i] = Task.Factory.StartNew(() => WriteStreamPngPerfTest(numRuns / numOfTasks)); break; default: throw new NotSupportedException("A task was created but not given a proper task. Check the code/swithc statement."); } } Task.WaitAll(tasks); stopwatchMultiThread.Stop(); WriteStopWatch(stopwatchMultiThread, functionToRun); //delete dump dir } private static void SetTempPathsOfPerfTestFiles() { jpegDogPath = SaveEmbeddedResourceToFile("JpegDog"); jpegCatPath = SaveEmbeddedResourceToFile("JpegCat"); pngDogPath = SaveEmbeddedResourceToFile("PngDog"); pngCatPath = SaveEmbeddedResourceToFile("PngCat"); } private static void DeletePerfTestFileConstants() { File.Delete(jpegDogPath); File.Delete(jpegCatPath); File.Delete(pngDogPath); File.Delete(pngCatPath); } private static void WriteTestHeader(int numRuns) { Console.WriteLine(""); Console.WriteLine("~~~~~~~~~~~ {0} Runs ~~~~~~~~~~~", numRuns); Console.WriteLine(""); streamwriter.WriteLine(""); streamwriter.WriteLine("~~~~~~~~~~~ {0} Runs ~~~~~~~~~~~", numRuns); streamwriter.WriteLine(""); } private static void WriteCurrentTest(string currentTest, int numRuns) { Console.WriteLine(currentTest + "{0}", numRuns); streamwriter.WriteLine(currentTest + "{0}", numRuns); } private static void WriteStopWatch(Stopwatch sw, string currentTest) { TimeSpan elapsedSecs = (sw.Elapsed); Console.WriteLine(elapsedSecs); Console.WriteLine(""); streamwriter.WriteLine("Elapsed time for " + currentTest + ": " + elapsedSecs); streamwriter.WriteLine(""); sw.Reset(); } private static void LoadFileJpegPerfTest(int numRuns) { for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("LoadFileJpegTest :" + i); stopwatchSingleThread.Start(); Image img = Jpg.Load(jpegCatPath); stopwatchSingleThread.Stop(); img.ReleaseStruct(); } } private static void LoadFilePngPerfTest(int numRuns) { for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) { Console.WriteLine("LoadFilePngTest :" + i); } stopwatchSingleThread.Start(); Image img = Png.Load(pngCatPath); stopwatchSingleThread.Stop(); img.ReleaseStruct(); } } //FIX Write private static void WriteFileJpegPerfTest(int numRuns) { //string dir = Path.GetTempPath(); Image _thisjpgdog = Jpg.Load(jpegDogPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) { Console.WriteLine("WriteFileJpegTest :" + i); } stopwatchSingleThread.Start(); Jpg.WriteToFile(_thisjpgdog, Path.ChangeExtension(Path.GetTempFileName(), ".jpg")); stopwatchSingleThread.Stop(); } _thisjpgdog.ReleaseStruct(); } //fix write private static void WriteFilePngPerfTest(int numRuns) { Image _thispngdog = Png.Load(pngDogPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("WriteFilePngTest :" + i); stopwatchSingleThread.Start(); Png.WriteToFile(_thispngdog, Path.ChangeExtension(Path.GetTempFileName(), ".png")); stopwatchSingleThread.Stop(); } _thispngdog.ReleaseStruct(); } private static void ResizeJpegPerfTest(int numRuns) { Image _thisjpgcat = Jpg.Load(jpegCatPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("ResizeJpegTest :" + i); stopwatchSingleThread.Start(); Image img = _thisjpgcat.Resize(100, 100); stopwatchSingleThread.Stop(); img.ReleaseStruct(); } _thisjpgcat.ReleaseStruct(); } private static void ResizePngPerfTest(int numRuns) { Image _thispngcat = Png.Load(pngCatPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("ResizePngTest :" + i); stopwatchSingleThread.Start(); Image img = _thispngcat.Resize(100, 100); stopwatchSingleThread.Stop(); img.ReleaseStruct(); } _thispngcat.ReleaseStruct(); } private static void ChangeAlphaJpegPerfTest(int numRuns) { Image _thisjpgcat = Jpg.Load(jpegCatPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("ChangeAlphaJpegTest :" + i); stopwatchSingleThread.Start(); _thisjpgcat.SetAlphaPercentage(0.5); stopwatchSingleThread.Stop(); } _thisjpgcat.ReleaseStruct(); } private static void ChangeAlphaPngPerfTest(int numRuns) { Image _thispngcat = Png.Load(pngCatPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("ChangeAlphaPngTest :" + i); stopwatchSingleThread.Start(); _thispngcat.SetAlphaPercentage(0.5); stopwatchSingleThread.Stop(); } _thispngcat.ReleaseStruct(); } private static void DrawJpegOverJpegPerfTest(int numRuns) { Image _thisjpgcat = Jpg.Load(jpegCatPath); Image _thisjpgdog = Jpg.Load(jpegDogPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("DrawJpegOverJpegTest :" + i); stopwatchSingleThread.Start(); _thisjpgdog.Draw(_thisjpgcat, 10, 10); stopwatchSingleThread.Stop(); } _thisjpgcat.ReleaseStruct(); _thisjpgdog.ReleaseStruct(); } private static void DrawPngOverPngPerfTest(int numRuns) { Image _thispngcat = Png.Load(pngCatPath); Image _thispngdog = Png.Load(pngDogPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("DrawPngOverPngTest :" + i); stopwatchSingleThread.Start(); _thispngdog.Draw(_thispngcat, 10, 10); stopwatchSingleThread.Stop(); } _thispngcat.ReleaseStruct(); _thispngdog.ReleaseStruct(); } private static void DrawJpegOverPngPerfTest(int numRuns) { Image _thisjpgcat = Jpg.Load(jpegCatPath); Image _thispngdog = Png.Load(pngDogPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("DrawJpegOverPngTest :" + i); stopwatchSingleThread.Start(); _thispngdog.Draw(_thisjpgcat, 10, 10); stopwatchSingleThread.Stop(); } _thisjpgcat.ReleaseStruct(); _thispngdog.ReleaseStruct(); } private static void DrawPngOverJpegPerfTest(int numRuns) { Image _thisjpgdog = Jpg.Load(jpegDogPath); Image _thispngcat = Png.Load(pngCatPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("DrawPngOverJpegTest :" + i); stopwatchSingleThread.Start(); _thisjpgdog.Draw(_thispngcat, 10, 10); stopwatchSingleThread.Stop(); } _thisjpgdog.ReleaseStruct(); _thispngcat.ReleaseStruct(); } private static void LoadStreamJpegPerfTest(int numRuns) { for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("LoadStreamJpegTest :" + i); using (FileStream filestream = new FileStream(jpegCatPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { stopwatchSingleThread.Start(); Image img = Jpg.Load(filestream); stopwatchSingleThread.Stop(); img.ReleaseStruct(); //filestream.Dispose(); } } } private static void LoadStreamPngPerfTest(int numRuns) { for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("LoadStreamPngTest :" + i); //fixed stream by giving acces to multiple threads? using (FileStream filestream = new FileStream(pngCatPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { stopwatchSingleThread.Start(); Image img = Png.Load(filestream); stopwatchSingleThread.Stop(); img.ReleaseStruct(); //filestream.Dispose(); } } } private static void WriteStreamJpegPerfTest(int numRuns) { Image _thisjpgcat = Jpg.Load(jpegCatPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("WriteStreamJpegTest :" + i); using (MemoryStream stream = new MemoryStream()) { stopwatchSingleThread.Start(); Jpg.WriteToStream(_thisjpgcat, stream); stopwatchSingleThread.Stop(); } } _thisjpgcat.ReleaseStruct(); } private static void WriteStreamPngPerfTest(int numRuns) { Image _thispngcat = Jpg.Load(pngCatPath); for (int i = 0; i < numRuns; i++) { //make sure it's going if (i % 100 == 0) Console.WriteLine("WriteStreamPngTest :" + i); using (MemoryStream stream = new MemoryStream()) { stopwatchSingleThread.Start(); Png.WriteToStream(_thispngcat, stream); stopwatchSingleThread.Stop(); } } _thispngcat.ReleaseStruct(); } #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.Collections.Generic; using Xunit; namespace Microsoft.Win32.RegistryTests { public class RegistryKey_SetValueKind_str_obj_valueKind : RegistryTestsBase { public static IEnumerable<object[]> TestObjects { get { return TestData.TestObjects; } } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithUnknownValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { string valueName = "Testing_" + testIndex.ToString(); TestRegistryKey.SetValue(valueName, testValue, RegistryValueKind.Unknown); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithStringValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.String; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithExpandStringValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.ExpandString; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithMultiStringValeKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.MultiString; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } catch (ArgumentException) { Assert.IsNotType<string[]>(testValue); } } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithBinaryValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.Binary; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } catch (ArgumentException) { Assert.IsNotType<byte[]>(testValue); } } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithDWordValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.DWord; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(Convert.ToInt32(testValue).ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); Assert.True(testIndex <= 15); TestRegistryKey.DeleteValue(valueName); } catch (ArgumentException ioe) { Assert.False(testIndex <= 15, ioe.ToString()); } } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithQWordValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.QWord; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(Convert.ToInt64(testValue).ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); Assert.True(testIndex <= 25); TestRegistryKey.DeleteValue(valueName); } catch (ArgumentException ioe) { Assert.False(testIndex <= 25, ioe.ToString()); } } [Fact] public void SetValueForNonExistingKey() { const string valueName = "FooBar"; const int expectedValue1 = int.MaxValue; const long expectedValue2 = long.MinValue; const RegistryValueKind expectedValueKind1 = RegistryValueKind.DWord; const RegistryValueKind expectedValueKind2 = RegistryValueKind.QWord; Assert.True(TestRegistryKey.GetValue(valueName) == null, "Registry key already exists"); TestRegistryKey.SetValue(valueName, expectedValue1, expectedValueKind1); Assert.True(TestRegistryKey.GetValue(valueName) != null, "Registry key doesn't exists"); Assert.Equal(expectedValue1, (int)TestRegistryKey.GetValue(valueName)); Assert.Equal(expectedValueKind1, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.SetValue(valueName, expectedValue2, expectedValueKind2); Assert.Equal(expectedValue2, (long)TestRegistryKey.GetValue(valueName)); Assert.Equal(expectedValueKind2, TestRegistryKey.GetValueKind(valueName)); } public static IEnumerable<object[]> TestValueNames { get { return TestData.TestValueNames; } } [Theory] [MemberData(nameof(TestValueNames))] public void SetValueWithNameTest(string valueName) { const long expectedValue = long.MaxValue; const RegistryValueKind expectedValueKind = RegistryValueKind.QWord; TestRegistryKey.SetValue(valueName, expectedValue, expectedValueKind); Assert.Equal(expectedValue, (long)TestRegistryKey.GetValue(valueName)); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); } [Fact] public void NegativeTests() { // Should throw if key length above 255 characters but prior to V4 the limit is 16383 const int maxValueNameLength = 16383; string tooLongValueName = new string('a', maxValueNameLength + 1); Assert.Throws<ArgumentException>(() => TestRegistryKey.SetValue(tooLongValueName, ulong.MaxValue, RegistryValueKind.String)); const string valueName = "FooBar"; // Should throw if passed value is null Assert.Throws<ArgumentNullException>(() => TestRegistryKey.SetValue(valueName, null, RegistryValueKind.QWord)); // Should throw because valueKind is equal to -2 which is not an acceptable value Assert.Throws<ArgumentException>(() => TestRegistryKey.SetValue(valueName, int.MinValue, (RegistryValueKind)(-2))); // Should throw because passed array contains null string[] strArr = { "one", "two", null, "three" }; Assert.Throws<ArgumentException>(() => TestRegistryKey.SetValue(valueName, strArr, RegistryValueKind.MultiString)); // Should throw because passed array has wrong type Assert.Throws<ArgumentException>(() => TestRegistryKey.SetValue(valueName, new[] { new object() }, RegistryValueKind.MultiString)); // Should throw because passed array has wrong type object[] objTemp = { "my string", "your string", "Any once string" }; Assert.Throws<ArgumentException>(() => TestRegistryKey.SetValue(valueName, objTemp, RegistryValueKind.Unknown)); // Should throw because RegistryKey is readonly using (var rk = Registry.CurrentUser.OpenSubKey(TestRegistryKeyName, false)) { Assert.Throws<UnauthorizedAccessException>(() => rk.SetValue(valueName, int.MaxValue, RegistryValueKind.DWord)); } // Should throw if RegistryKey is closed Assert.Throws<ObjectDisposedException>(() => { TestRegistryKey.Dispose(); TestRegistryKey.SetValue(valueName, int.MinValue, RegistryValueKind.DWord); }); } } }
using System; using System.Runtime.InteropServices; using System.Text; namespace DbgEng { [ComImport, ComConversionLoss, Guid("B86FB3B1-80D4-475B-AEA3-CF06539CF63A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDebugControl7 : IDebugControl6 { #pragma warning disable CS0108 // XXX hides inherited member. This is COM default. #region IDebugControl void GetInterrupt(); void SetInterrupt( [In] uint Flags); uint GetInterruptTimeout(); void SetInterruptTimeout( [In] uint Seconds); void GetLogFile( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint FileSize, [Out] out int Append); void OpenLogFile( [In, MarshalAs(UnmanagedType.LPStr)] string File, [In] int Append); void CloseLogFile(); uint GetLogMask(); void SetLogMask( [In] uint Mask); void Input( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint InputSize); void ReturnInput( [In, MarshalAs(UnmanagedType.LPStr)] string Buffer); void Output( [In] uint Mask, [In, MarshalAs(UnmanagedType.LPStr)] string Format, [In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] params object[] parameters); void OutputVaList( [In] uint Mask, [In, MarshalAs(UnmanagedType.LPStr)] string Format, [In] ref sbyte Args); void ControlledOutput( [In] uint OutputControl, [In] uint Mask, [In, MarshalAs(UnmanagedType.LPStr)] string Format, [In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] params object[] parameters); void ControlledOutputVaList( [In] uint OutputControl, [In] uint Mask, [In, MarshalAs(UnmanagedType.LPStr)] string Format, [In] ref sbyte Args); void OutputPrompt( [In] uint OutputControl, [In, MarshalAs(UnmanagedType.LPStr)] string Format, [In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] params object[] parameters); void OutputPromptVaList( [In] uint OutputControl, [In, MarshalAs(UnmanagedType.LPStr)] string Format, [In] ref sbyte Args); void GetPromptText( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint TextSize); void OutputCurrentState( [In] uint OutputControl, [In] uint Flags); void OutputVersionInformation( [In] uint OutputControl); ulong GetNotifyEventHandle(); void SetNotifyEventHandle( [In] ulong Handle); ulong Assemble( [In] ulong Offset, [In, MarshalAs(UnmanagedType.LPStr)] string Instr); void Disassemble( [In] ulong Offset, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint DisassemblySize, [Out] out ulong EndOffset); ulong GetDisassembleEffectiveOffset(); ulong OutputDisassembly( [In] uint OutputControl, [In] ulong Offset, [In] uint Flags); void OutputDisassemblyLines( [In] uint OutputControl, [In] uint PreviousLines, [In] uint TotalLines, [In] ulong Offset, [In] uint Flags, [Out] out uint OffsetLine, [Out] out ulong StartOffset, [Out] out ulong EndOffset, [Out] out ulong LineOffsets); ulong GetNearInstruction( [In] ulong Offset, [In] int Delta); void GetStackTrace( [In] ulong FrameOffset, [In] ulong StackOffset, [In] ulong InstructionOffset, [Out] IntPtr Frames, [In] uint FramesSize, [Out] out uint FramesFilled); ulong GetReturnOffset(); void OutputStackTrace( [In] uint OutputControl, [In] IntPtr Frames = default(IntPtr), [In] uint FramesSize = default(uint), [In] uint Flags = default(uint)); void GetDebuggeeType( [Out] out uint Class, [Out] out uint Qualifier); uint GetActualProcessorType(); uint GetExecutingProcessorType(); uint GetNumberPossibleExecutingProcessorTypes(); uint GetPossibleExecutingProcessorTypes( [In] uint Start, [In] uint Count); uint GetNumberProcessors(); void GetSystemVersion( [Out] out uint PlatformId, [Out] out uint Major, [Out] out uint Minor, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ServicePackString, [In] uint ServicePackStringSize, [Out] out uint ServicePackStringUsed, [Out] out uint ServicePackNumber, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder BuildString, [In] uint BuildStringSize, [Out] out uint BuildStringUsed); uint GetPageSize(); void IsPointer64Bit(); void ReadBugCheckData( [Out] out uint Code, [Out] out ulong Arg1, [Out] out ulong Arg2, [Out] out ulong Arg3, [Out] out ulong Arg4); uint GetNumberSupportedProcessorTypes(); uint GetSupportedProcessorTypes( [In] uint Start, [In] uint Count); void GetProcessorTypeNames( [In] uint Type, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FullNameBuffer, [In] uint FullNameBufferSize, [Out] out uint FullNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder AbbrevNameBuffer, [In] uint AbbrevNameBufferSize, [Out] out uint AbbrevNameSize); uint GetEffectiveProcessorType(); void SetEffectiveProcessorType( [In] uint Type); uint GetExecutionStatus(); void SetExecutionStatus( [In] uint Status); uint GetCodeLevel(); void SetCodeLevel( [In] uint Level); uint GetEngineOptions(); void AddEngineOptions( [In] uint Options); void RemoveEngineOptions( [In] uint Options); void SetEngineOptions( [In] uint Options); void GetSystemErrorControl( [Out] out uint OutputLevel, [Out] out uint BreakLevel); void SetSystemErrorControl( [In] uint OutputLevel, [In] uint BreakLevel); void GetTextMacro( [In] uint Slot, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint MacroSize); void SetTextMacro( [In] uint Slot, [In, MarshalAs(UnmanagedType.LPStr)] string Macro); uint GetRadix(); void SetRadix( [In] uint Radix); void Evaluate( [In, MarshalAs(UnmanagedType.LPStr)] string Expression, [In] uint DesiredType, [Out] out _DEBUG_VALUE Value, [Out] out uint RemainderIndex); _DEBUG_VALUE CoerceValue( [In] ref _DEBUG_VALUE In, [In] uint OutType); IntPtr CoerceValues( [In] uint Count, [In] IntPtr In, [In] ref uint OutTypes); void Execute( [In] uint OutputControl, [In, MarshalAs(UnmanagedType.LPStr)] string Command, [In] uint Flags); void ExecuteCommandFile( [In] uint OutputControl, [In, MarshalAs(UnmanagedType.LPStr)] string CommandFile, [In] uint Flags); uint GetNumberBreakpoints(); [return: MarshalAs(UnmanagedType.Interface)] IDebugBreakpoint GetBreakpointByIndex( [In] uint Index); [return: MarshalAs(UnmanagedType.Interface)] IDebugBreakpoint GetBreakpointById( [In] uint Id); void GetBreakpointParameters( [In] uint Count, [In] ref uint Ids, [In] uint Start = default(uint), [Out] IntPtr Params = default(IntPtr)); [return: MarshalAs(UnmanagedType.Interface)] IDebugBreakpoint AddBreakpoint( [In] uint Type, [In] uint DesiredId); void RemoveBreakpoint( [In, MarshalAs(UnmanagedType.Interface)] IDebugBreakpoint Bp); ulong AddExtension( [In, MarshalAs(UnmanagedType.LPStr)] string Path, [In] uint Flags); void RemoveExtension( [In] ulong Handle); ulong GetExtensionByPath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); void CallExtension( [In] ulong Handle, [In, MarshalAs(UnmanagedType.LPStr)] string Function, [In, MarshalAs(UnmanagedType.LPStr)] string Arguments = null); IntPtr GetExtensionFunction( [In] ulong Handle, [In, MarshalAs(UnmanagedType.LPStr)] string FuncName); _WINDBG_EXTENSION_APIS32 GetWindbgExtensionApis32(); _WINDBG_EXTENSION_APIS64 GetWindbgExtensionApis64(); void GetNumberEventFilters( [Out] out uint SpecificEvents, [Out] out uint SpecificExceptions, [Out] out uint ArbitraryExceptions); void GetEventFilterText( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint TextSize); void GetEventFilterCommand( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint CommandSize); void SetEventFilterCommand( [In] uint Index, [In, MarshalAs(UnmanagedType.LPStr)] string Command); IntPtr GetSpecificFilterParameters( [In] uint Start, [In] uint Count); void SetSpecificFilterParameters( [In] uint Start, [In] uint Count, [In] IntPtr Params); void GetSpecificFilterArgument( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint ArgumentSize); void SetSpecificFilterArgument( [In] uint Index, [In, MarshalAs(UnmanagedType.LPStr)] string Argument); void GetExceptionFilterParameters( [In] uint Count, [In] ref uint Codes, [In] uint Start = default(uint), [Out] IntPtr Params = default(IntPtr)); void SetExceptionFilterParameters( [In] uint Count, [In] IntPtr Params); void GetExceptionFilterSecondCommand( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint CommandSize); void SetExceptionFilterSecondCommand( [In] uint Index, [In, MarshalAs(UnmanagedType.LPStr)] string Command); void WaitForEvent( [In] uint Flags, [In] uint Timeout); void GetLastEventInformation( [Out] out uint Type, [Out] out uint ProcessId, [Out] out uint ThreadId, [Out] IntPtr ExtraInformation, [In] uint ExtraInformationSize, [Out] out uint ExtraInformationUsed, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Description, [In] uint DescriptionSize, [Out] out uint DescriptionUsed); #endregion #region IDebugControl2 uint GetCurrentTimeDate(); uint GetCurrentSystemUpTime(); uint GetDumpFormatFlags(); uint GetNumberTextReplacements(); void GetTextReplacement( [In, MarshalAs(UnmanagedType.LPStr)] string SrcText, [In] uint Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder SrcBuffer, [In] uint SrcBufferSize, [Out] out uint SrcSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder DstBuffer, [In] uint DstBufferSize, [Out] out uint DstSize); void SetTextReplacement( [In, MarshalAs(UnmanagedType.LPStr)] string SrcText, [In, MarshalAs(UnmanagedType.LPStr)] string DstText); void RemoveTextReplacements(); void OutputTextReplacements( [In] uint OutputControl, [In] uint Flags); #endregion #region IDebugControl3 uint GetAssemblyOptions(); void AddAssemblyOptions( [In] uint Options); void RemoveAssemblyOptions( [In] uint Options); void SetAssemblyOptions( [In] uint Options); uint GetExpressionSyntax(); void SetExpressionSyntax( [In] uint Flags); void SetExpressionSyntaxByName( [In, MarshalAs(UnmanagedType.LPStr)] string AbbrevName); uint GetNumberExpressionSyntaxes(); void GetExpressionSyntaxNames( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FullNameBuffer, [In] uint FullNameBufferSize, [Out] out uint FullNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder AbbrevNameBuffer, [In] uint AbbrevNameBufferSize, [Out] out uint AbbrevNameSize); uint GetNumberEvents(); void GetEventIndexDescription( [In] uint Index, [In] uint Which, [In, MarshalAs(UnmanagedType.LPStr)] string Buffer, [In] uint BufferSize, [Out] out uint DescSize); uint GetCurrentEventIndex(); uint SetNextEventIndex( [In] uint Relation, [In] uint Value); #endregion #region IDebugControl4 void GetLogFileWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint FileSize, [Out] out int Append); void OpenLogFileWide( [In, MarshalAs(UnmanagedType.LPWStr)] string File, [In] int Append); void InputWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint InputSize); void ReturnInputWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Buffer); void OutputWide( [In] uint Mask, [In, MarshalAs(UnmanagedType.LPWStr)] string Format, [In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] params object[] parameters); void OutputVaListWide( [In] uint Mask, [In, MarshalAs(UnmanagedType.LPWStr)] string Format, [In] ref sbyte Args); void ControlledOutputWide( [In] uint OutputControl, [In] uint Mask, [In, MarshalAs(UnmanagedType.LPWStr)] string Format, [In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] params object[] parameters); void ControlledOutputVaListWide( [In] uint OutputControl, [In] uint Mask, [In, MarshalAs(UnmanagedType.LPWStr)] string Format, [In] ref sbyte Args); void OutputPromptWide( [In] uint OutputControl, [In, MarshalAs(UnmanagedType.LPWStr)] string Format, [In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] params object[] parameters); void OutputPromptVaListWide( [In] uint OutputControl, [In, MarshalAs(UnmanagedType.LPWStr)] string Format, [In] ref sbyte Args); void GetPromptTextWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint TextSize); ulong AssembleWide( [In] ulong Offset, [In, MarshalAs(UnmanagedType.LPWStr)] string Instr); void DisassembleWide( [In] ulong Offset, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint DisassemblySize, [Out] out ulong EndOffset); void GetProcessorTypeNamesWide( [In] uint Type, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder FullNameBuffer, [In] uint FullNameBufferSize, [Out] out uint FullNameSize, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder AbbrevNameBuffer, [In] uint AbbrevNameBufferSize, [Out] out uint AbbrevNameSize); void GetTextMacroWide( [In] uint Slot, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint MacroSize); void SetTextMacroWide( [In] uint Slot, [In, MarshalAs(UnmanagedType.LPWStr)] string Macro); void EvaluateWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Expression, [In] uint DesiredType, [Out] out _DEBUG_VALUE Value, [Out] out uint RemainderIndex); void ExecuteWide( [In] uint OutputControl, [In, MarshalAs(UnmanagedType.LPWStr)] string Command, [In] uint Flags); void ExecuteCommandFileWide( [In] uint OutputControl, [In, MarshalAs(UnmanagedType.LPWStr)] string CommandFile, [In] uint Flags); [return: MarshalAs(UnmanagedType.Interface)] IDebugBreakpoint2 GetBreakpointByIndex2( [In] uint Index); [return: MarshalAs(UnmanagedType.Interface)] IDebugBreakpoint2 GetBreakpointById2( [In] uint Id); [return: MarshalAs(UnmanagedType.Interface)] IDebugBreakpoint2 AddBreakpoint2( [In] uint Type, [In] uint DesiredId); void RemoveBreakpoint2( [In, MarshalAs(UnmanagedType.Interface)] IDebugBreakpoint2 Bp); ulong AddExtensionWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path, [In] uint Flags); ulong GetExtensionByPathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); void CallExtensionWide( [In] ulong Handle, [In, MarshalAs(UnmanagedType.LPWStr)] string Function, [In, MarshalAs(UnmanagedType.LPWStr)] string Arguments = null); IntPtr GetExtensionFunctionWide( [In] ulong Handle, [In, MarshalAs(UnmanagedType.LPWStr)] string FuncName); void GetEventFilterTextWide( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint TextSize); void GetEventFilterCommandWide( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint CommandSize); void SetEventFilterCommandWide( [In] uint Index, [In, MarshalAs(UnmanagedType.LPWStr)] string Command); void GetSpecificFilterArgumentWide( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint ArgumentSize); void SetSpecificFilterArgumentWide( [In] uint Index, [In, MarshalAs(UnmanagedType.LPWStr)] string Argument); void GetExceptionFilterSecondCommandWide( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint CommandSize); void SetExceptionFilterSecondCommandWide( [In] uint Index, [In, MarshalAs(UnmanagedType.LPWStr)] string Command); void GetLastEventInformationWide( [Out] out uint Type, [Out] out uint ProcessId, [Out] out uint ThreadId, [Out] IntPtr ExtraInformation, [In] uint ExtraInformationSize, [Out] out uint ExtraInformationUsed, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Description, [In] uint DescriptionSize, [Out] out uint DescriptionUsed); void GetTextReplacementWide( [In, MarshalAs(UnmanagedType.LPWStr)] string SrcText, [In] uint Index, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder SrcBuffer, [In] uint SrcBufferSize, [Out] out uint SrcSize, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder DstBuffer, [In] uint DstBufferSize, [Out] out uint DstSize); void SetTextReplacementWide( [In, MarshalAs(UnmanagedType.LPWStr)] string SrcText, [In, MarshalAs(UnmanagedType.LPWStr)] string DstText = null); void SetExpressionSyntaxByNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string AbbrevName); void GetExpressionSyntaxNamesWide( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder FullNameBuffer, [In] uint FullNameBufferSize, [Out] out uint FullNameSize, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder AbbrevNameBuffer, [In] uint AbbrevNameBufferSize, [Out] out uint AbbrevNameSize); void GetEventIndexDescriptionWide( [In] uint Index, [In] uint Which, [In, MarshalAs(UnmanagedType.LPWStr)] string Buffer, [In] uint BufferSize, [Out] out uint DescSize); void GetLogFile2( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint FileSize, [Out] out uint Flags); void OpenLogFile2( [In, MarshalAs(UnmanagedType.LPStr)] string File, [In] uint Flags); void GetLogFile2Wide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint FileSize, [Out] out uint Flags); void OpenLogFile2Wide( [In, MarshalAs(UnmanagedType.LPWStr)] string File, [In] uint Flags); void GetSystemVersionValues( [Out] out uint PlatformId, [Out] out uint Win32Major, [Out] out uint Win32Minor, [Out] out uint KdMajor, [Out] out uint KdMinor); void GetSystemVersionString( [In] uint Which, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); void GetSystemVersionStringWide( [In] uint Which, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); void GetContextStackTrace( [In] IntPtr StartContext, [In] uint StartContextSize, [Out] IntPtr Frames, [In] uint FramesSize, [Out] IntPtr FrameContexts, [In] uint FrameContextsSize, [In] uint FrameContextsEntrySize, [Out] out uint FramesFilled); void OutputContextStackTrace( [In] uint OutputControl, [In] IntPtr Frames, [In] uint FramesSize, [In] IntPtr FrameContexts, [In] uint FrameContextsSize, [In] uint FrameContextsEntrySize, [In] uint Flags); void GetStoredEventInformation( [Out] out uint Type, [Out] out uint ProcessId, [Out] out uint ThreadId, [Out] IntPtr Context, [In] uint ContextSize, [Out] out uint ContextUsed, [Out] IntPtr ExtraInformation, [In] uint ExtraInformationSize, [Out] out uint ExtraInformationUsed); void GetManagedStatus( [Out] out uint Flags, [In] uint WhichString, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder String, [In] uint StringSize, [Out] out uint StringNeeded); void GetManagedStatusWide( [Out] out uint Flags, [In] uint WhichString, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder String, [In] uint StringSize, [Out] out uint StringNeeded); void ResetManagedStatus( [In] uint Flags); #endregion #region IDebugControl5 void GetStackTraceEx( [In] ulong FrameOffset, [In] ulong StackOffset, [In] ulong InstructionOffset, [Out] IntPtr Frames, [In] uint FramesSize, [Out] out uint FramesFilled); void OutputStackTraceEx( [In] uint OutputControl, [In] IntPtr Frames = default(IntPtr), [In] uint FramesSize = default(uint), [In] uint Flags = default(uint)); void GetContextStackTraceEx( [In] IntPtr StartContext, [In] uint StartContextSize, [Out] IntPtr Frames, [In] uint FramesSize, [Out] IntPtr FrameContexts, [In] uint FrameContextsSize, [In] uint FrameContextsEntrySize, [Out] out uint FramesFilled); void OutputContextStackTraceEx( [In] uint OutputControl, [In] IntPtr Frames, [In] uint FramesSize, [In] IntPtr FrameContexts, [In] uint FrameContextsSize, [In] uint FrameContextsEntrySize, [In] uint Flags); [return: MarshalAs(UnmanagedType.Interface)] IDebugBreakpoint3 GetBreakpointByGuid( [In] ref Guid Guid); #endregion #region IDebugControl6 uint GetExecutionStatusEx(); void GetSynchronizationStatus( [Out] out uint SendsAttempted, [Out] out uint SecondsSinceLastResponse); #endregion #pragma warning restore CS0108 // XXX hides inherited member. This is COM default. void GetDebuggeeType2( [In] uint Flags, [Out] out uint Class, [Out] out uint Qualifier); } }
using System.Text; using Lucene.Net.Util; namespace Lucene.Net.Index { using System; /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using Codec = Lucene.Net.Codecs.Codec; // javadocs using IndexingChain = Lucene.Net.Index.DocumentsWriterPerThread.IndexingChain; using IndexReaderWarmer = Lucene.Net.Index.IndexWriter.IndexReaderWarmer; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using InfoStream = Lucene.Net.Util.InfoStream; using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e; using Similarity = Lucene.Net.Search.Similarities.Similarity; /// <summary> /// Holds all the configuration used by <seealso cref="IndexWriter"/> with few setters for /// settings that can be changed on an <seealso cref="IndexWriter"/> instance "live". /// /// @since 4.0 /// </summary> public class LiveIndexWriterConfig { private readonly Analyzer analyzer; private volatile int maxBufferedDocs; private double RamBufferSizeMB; private volatile int maxBufferedDeleteTerms; private volatile int readerTermsIndexDivisor; private volatile IndexReaderWarmer mergedSegmentWarmer; private volatile int termIndexInterval; // TODO: this should be private to the codec, not settable here // modified by IndexWriterConfig /// <summary> /// <seealso cref="DelPolicy"/> controlling when commit /// points are deleted. /// </summary> protected internal volatile IndexDeletionPolicy delPolicy; /// <summary> /// <seealso cref="IndexCommit"/> that <seealso cref="IndexWriter"/> is /// opened on. /// </summary> protected internal volatile IndexCommit Commit; /// <summary> /// <seealso cref="OpenMode"/> that <seealso cref="IndexWriter"/> is opened /// with. /// </summary> protected internal OpenMode_e? openMode; /// <summary> /// <seealso cref="Similarity"/> to use when encoding norms. </summary> protected internal volatile Similarity similarity; /// <summary> /// <seealso cref="MergeScheduler"/> to use for running merges. </summary> protected internal volatile IMergeScheduler mergeScheduler; /// <summary> /// Timeout when trying to obtain the write lock on init. </summary> protected internal long writeLockTimeout; /// <summary> /// <seealso cref="IndexingChain"/> that determines how documents are /// indexed. /// </summary> protected internal volatile IndexingChain indexingChain; /// <summary> /// <seealso cref="Codec"/> used to write new segments. </summary> protected internal volatile Codec codec; /// <summary> /// <seealso cref="InfoStream"/> for debugging messages. </summary> protected internal volatile InfoStream infoStream; /// <summary> /// <seealso cref="MergePolicy"/> for selecting merges. </summary> protected internal volatile MergePolicy mergePolicy; /// <summary> /// {@code DocumentsWriterPerThreadPool} to control how /// threads are allocated to {@code DocumentsWriterPerThread}. /// </summary> protected internal volatile DocumentsWriterPerThreadPool indexerThreadPool; /// <summary> /// True if readers should be pooled. </summary> protected internal volatile bool readerPooling; /// <summary> /// <seealso cref="FlushPolicy"/> to control when segments are /// flushed. /// </summary> protected internal volatile FlushPolicy flushPolicy; /// <summary> /// Sets the hard upper bound on RAM usage for a single /// segment, after which the segment is forced to flush. /// </summary> protected internal volatile int PerThreadHardLimitMB; /// <summary> /// <seealso cref="LuceneVersion"/> that <seealso cref="IndexWriter"/> should emulate. </summary> protected internal readonly LuceneVersion MatchVersion; /// <summary> /// True if segment flushes should use compound file format </summary> protected internal volatile bool useCompoundFile = IndexWriterConfig.DEFAULT_USE_COMPOUND_FILE_SYSTEM; /// <summary> /// True if merging should check integrity of segments before merge </summary> protected internal volatile bool checkIntegrityAtMerge = IndexWriterConfig.DEFAULT_CHECK_INTEGRITY_AT_MERGE; // used by IndexWriterConfig internal LiveIndexWriterConfig(Analyzer analyzer, LuceneVersion matchVersion) { this.analyzer = analyzer; this.MatchVersion = matchVersion; RamBufferSizeMB = IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB; maxBufferedDocs = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS; maxBufferedDeleteTerms = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DELETE_TERMS; readerTermsIndexDivisor = IndexWriterConfig.DEFAULT_READER_TERMS_INDEX_DIVISOR; mergedSegmentWarmer = null; termIndexInterval = IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL; // TODO: this should be private to the codec, not settable here delPolicy = new KeepOnlyLastCommitDeletionPolicy(); Commit = null; useCompoundFile = IndexWriterConfig.DEFAULT_USE_COMPOUND_FILE_SYSTEM; openMode = OpenMode_e.CREATE_OR_APPEND; similarity = IndexSearcher.DefaultSimilarity; mergeScheduler = new ConcurrentMergeScheduler(); writeLockTimeout = IndexWriterConfig.WRITE_LOCK_TIMEOUT; indexingChain = DocumentsWriterPerThread.defaultIndexingChain; codec = Codec.Default; if (codec == null) { throw new System.NullReferenceException(); } infoStream = Util.InfoStream.Default; mergePolicy = new TieredMergePolicy(); flushPolicy = new FlushByRamOrCountsPolicy(); readerPooling = IndexWriterConfig.DEFAULT_READER_POOLING; indexerThreadPool = new ThreadAffinityDocumentsWriterThreadPool(IndexWriterConfig.DEFAULT_MAX_THREAD_STATES); PerThreadHardLimitMB = IndexWriterConfig.DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB; } /// <summary> /// Creates a new config that that handles the live <seealso cref="IndexWriter"/> /// settings. /// </summary> internal LiveIndexWriterConfig(IndexWriterConfig config) { maxBufferedDeleteTerms = config.MaxBufferedDeleteTerms; maxBufferedDocs = config.MaxBufferedDocs; mergedSegmentWarmer = config.MergedSegmentWarmer; RamBufferSizeMB = config.RAMBufferSizeMB; readerTermsIndexDivisor = config.ReaderTermsIndexDivisor; termIndexInterval = config.TermIndexInterval; MatchVersion = config.MatchVersion; analyzer = config.Analyzer; delPolicy = config.DelPolicy; Commit = config.IndexCommit; openMode = config.OpenMode; similarity = config.Similarity; mergeScheduler = config.MergeScheduler; writeLockTimeout = config.WriteLockTimeout; indexingChain = config.IndexingChain; codec = config.Codec; infoStream = config.InfoStream; mergePolicy = config.MergePolicy; indexerThreadPool = config.IndexerThreadPool; readerPooling = config.ReaderPooling; flushPolicy = config.FlushPolicy; PerThreadHardLimitMB = config.RAMPerThreadHardLimitMB; useCompoundFile = config.UseCompoundFile; checkIntegrityAtMerge = config.CheckIntegrityAtMerge; } /// <summary> /// Returns the default analyzer to use for indexing documents. </summary> public virtual Analyzer Analyzer { get { return analyzer; } } /// <summary> /// Expert: set the interval between indexed terms. Large values cause less /// memory to be used by IndexReader, but slow random-access to terms. Small /// values cause more memory to be used by an IndexReader, and speed /// random-access to terms. /// <p> /// this parameter determines the amount of computation required per query /// term, regardless of the number of documents that contain that term. In /// particular, it is the maximum number of other terms that must be scanned /// before a term is located and its frequency and position information may be /// processed. In a large index with user-entered query terms, query processing /// time is likely to be dominated not by term lookup but rather by the /// processing of frequency and positional data. In a small index or when many /// uncommon query terms are generated (e.g., by wildcard queries) term lookup /// may become a dominant cost. /// <p> /// In particular, <code>numUniqueTerms/interval</code> terms are read into /// memory by an IndexReader, and, on average, <code>interval/2</code> terms /// must be scanned for each random term access. /// /// <p> /// Takes effect immediately, but only applies to newly flushed/merged /// segments. /// /// <p> /// <b>NOTE:</b> this parameter does not apply to all PostingsFormat implementations, /// including the default one in this release. It only makes sense for term indexes /// that are implemented as a fixed gap between terms. For example, /// <seealso cref="Lucene41PostingsFormat"/> implements the term index instead based upon how /// terms share prefixes. To configure its parameters (the minimum and maximum size /// for a block), you would instead use <seealso cref="Lucene41PostingsFormat#Lucene41PostingsFormat(int, int)"/>. /// which can also be configured on a per-field basis: /// <pre class="prettyprint"> /// //customize Lucene41PostingsFormat, passing minBlockSize=50, maxBlockSize=100 /// final PostingsFormat tweakedPostings = new Lucene41PostingsFormat(50, 100); /// iwc.SetCodec(new Lucene45Codec() { /// &#64;Override /// public PostingsFormat getPostingsFormatForField(String field) { /// if (field.equals("fieldWithTonsOfTerms")) /// return tweakedPostings; /// else /// return super.getPostingsFormatForField(field); /// } /// }); /// </pre> /// Note that other implementations may have their own parameters, or no parameters at all. /// </summary> /// <seealso cref= IndexWriterConfig#DEFAULT_TERM_INDEX_INTERVAL </seealso> public virtual LiveIndexWriterConfig SetTermIndexInterval(int interval) // TODO: this should be private to the codec, not settable here { this.termIndexInterval = interval; return this; } /// <summary> /// Returns the interval between indexed terms. /// </summary> /// <seealso cref= #setTermIndexInterval(int) </seealso> public virtual int TermIndexInterval { get { return termIndexInterval; } } /// <summary> /// Determines the maximum number of delete-by-term operations that will be /// buffered before both the buffered in-memory delete terms and queries are /// applied and flushed. /// <p> /// Disabled by default (writer flushes by RAM usage). /// <p> /// NOTE: this setting won't trigger a segment flush. /// /// <p> /// Takes effect immediately, but only the next time a document is added, /// updated or deleted. Also, if you only delete-by-query, this setting has no /// effect, i.e. delete queries are buffered until the next segment is flushed. /// </summary> /// <exception cref="IllegalArgumentException"> /// if maxBufferedDeleteTerms is enabled but smaller than 1 /// </exception> /// <seealso cref= #setRAMBufferSizeMB </seealso> public virtual LiveIndexWriterConfig SetMaxBufferedDeleteTerms(int maxBufferedDeleteTerms) { if (maxBufferedDeleteTerms != IndexWriterConfig.DISABLE_AUTO_FLUSH && maxBufferedDeleteTerms < 1) { throw new System.ArgumentException("maxBufferedDeleteTerms must at least be 1 when enabled"); } this.maxBufferedDeleteTerms = maxBufferedDeleteTerms; return this; } /// <summary> /// Returns the number of buffered deleted terms that will trigger a flush of all /// buffered deletes if enabled. /// </summary> /// <seealso cref= #setMaxBufferedDeleteTerms(int) </seealso> public virtual int MaxBufferedDeleteTerms { get { return maxBufferedDeleteTerms; } } /// <summary> /// Determines the amount of RAM that may be used for buffering added documents /// and deletions before they are flushed to the Directory. Generally for /// faster indexing performance it's best to flush by RAM usage instead of /// document count and use as large a RAM buffer as you can. /// <p> /// When this is set, the writer will flush whenever buffered documents and /// deletions use this much RAM. Pass in /// <seealso cref="IndexWriterConfig#DISABLE_AUTO_FLUSH"/> to prevent triggering a flush /// due to RAM usage. Note that if flushing by document count is also enabled, /// then the flush will be triggered by whichever comes first. /// <p> /// The maximum RAM limit is inherently determined by the JVMs available /// memory. Yet, an <seealso cref="IndexWriter"/> session can consume a significantly /// larger amount of memory than the given RAM limit since this limit is just /// an indicator when to flush memory resident documents to the Directory. /// Flushes are likely happen concurrently while other threads adding documents /// to the writer. For application stability the available memory in the JVM /// should be significantly larger than the RAM buffer used for indexing. /// <p> /// <b>NOTE</b>: the account of RAM usage for pending deletions is only /// approximate. Specifically, if you delete by Query, Lucene currently has no /// way to measure the RAM usage of individual Queries so the accounting will /// under-estimate and you should compensate by either calling commit() /// periodically yourself, or by using <seealso cref="#setMaxBufferedDeleteTerms(int)"/> /// to flush and apply buffered deletes by count instead of RAM usage (for each /// buffered delete Query a constant number of bytes is used to estimate RAM /// usage). Note that enabling <seealso cref="#setMaxBufferedDeleteTerms(int)"/> will not /// trigger any segment flushes. /// <p> /// <b>NOTE</b>: It's not guaranteed that all memory resident documents are /// flushed once this limit is exceeded. Depending on the configured /// <seealso cref="FlushPolicy"/> only a subset of the buffered documents are flushed and /// therefore only parts of the RAM buffer is released. /// <p> /// /// The default value is <seealso cref="IndexWriterConfig#DEFAULT_RAM_BUFFER_SIZE_MB"/>. /// /// <p> /// Takes effect immediately, but only the next time a document is added, /// updated or deleted. /// </summary> /// <seealso cref= IndexWriterConfig#setRAMPerThreadHardLimitMB(int) /// </seealso> /// <exception cref="IllegalArgumentException"> /// if ramBufferSize is enabled but non-positive, or it disables /// ramBufferSize when maxBufferedDocs is already disabled </exception> public virtual LiveIndexWriterConfig SetRAMBufferSizeMB(double ramBufferSizeMB) { if (ramBufferSizeMB != IndexWriterConfig.DISABLE_AUTO_FLUSH && ramBufferSizeMB <= 0.0) { throw new System.ArgumentException("ramBufferSize should be > 0.0 MB when enabled"); } if (ramBufferSizeMB == IndexWriterConfig.DISABLE_AUTO_FLUSH && maxBufferedDocs == IndexWriterConfig.DISABLE_AUTO_FLUSH) { throw new System.ArgumentException("at least one of ramBufferSize and maxBufferedDocs must be enabled"); } this.RamBufferSizeMB = ramBufferSizeMB; return this; } /// <summary> /// Returns the value set by <seealso cref="#setRAMBufferSizeMB(double)"/> if enabled. </summary> public virtual double RAMBufferSizeMB { get { return RamBufferSizeMB; } } /// <summary> /// Determines the minimal number of documents required before the buffered /// in-memory documents are flushed as a new Segment. Large values generally /// give faster indexing. /// /// <p> /// When this is set, the writer will flush every maxBufferedDocs added /// documents. Pass in <seealso cref="IndexWriterConfig#DISABLE_AUTO_FLUSH"/> to prevent /// triggering a flush due to number of buffered documents. Note that if /// flushing by RAM usage is also enabled, then the flush will be triggered by /// whichever comes first. /// /// <p> /// Disabled by default (writer flushes by RAM usage). /// /// <p> /// Takes effect immediately, but only the next time a document is added, /// updated or deleted. /// </summary> /// <seealso cref= #setRAMBufferSizeMB(double) </seealso> /// <exception cref="IllegalArgumentException"> /// if maxBufferedDocs is enabled but smaller than 2, or it disables /// maxBufferedDocs when ramBufferSize is already disabled </exception> public virtual LiveIndexWriterConfig SetMaxBufferedDocs(int maxBufferedDocs) { if (maxBufferedDocs != IndexWriterConfig.DISABLE_AUTO_FLUSH && maxBufferedDocs < 2) { throw new System.ArgumentException("maxBufferedDocs must at least be 2 when enabled"); } if (maxBufferedDocs == IndexWriterConfig.DISABLE_AUTO_FLUSH && RamBufferSizeMB == IndexWriterConfig.DISABLE_AUTO_FLUSH) { throw new System.ArgumentException("at least one of ramBufferSize and maxBufferedDocs must be enabled"); } this.maxBufferedDocs = maxBufferedDocs; return this; } /// <summary> /// Returns the number of buffered added documents that will trigger a flush if /// enabled. /// </summary> /// <seealso cref= #setMaxBufferedDocs(int) </seealso> public virtual int MaxBufferedDocs { get { return maxBufferedDocs; } } /// <summary> /// Set the merged segment warmer. See <seealso cref="IndexReaderWarmer"/>. /// /// <p> /// Takes effect on the next merge. /// </summary> public virtual LiveIndexWriterConfig SetMergedSegmentWarmer(IndexReaderWarmer mergeSegmentWarmer) { this.mergedSegmentWarmer = mergeSegmentWarmer; return this; } /// <summary> /// Returns the current merged segment warmer. See <seealso cref="IndexReaderWarmer"/>. </summary> public virtual IndexReaderWarmer MergedSegmentWarmer { get { return mergedSegmentWarmer; } } /// <summary> /// Sets the termsIndexDivisor passed to any readers that IndexWriter opens, /// for example when applying deletes or creating a near-real-time reader in /// <seealso cref="DirectoryReader#open(IndexWriter, boolean)"/>. If you pass -1, the /// terms index won't be loaded by the readers. this is only useful in advanced /// situations when you will only .Next() through all terms; attempts to seek /// will hit an exception. /// /// <p> /// Takes effect immediately, but only applies to readers opened after this /// call /// <p> /// <b>NOTE:</b> divisor settings &gt; 1 do not apply to all PostingsFormat /// implementations, including the default one in this release. It only makes /// sense for terms indexes that can efficiently re-sample terms at load time. /// </summary> public virtual LiveIndexWriterConfig SetReaderTermsIndexDivisor(int divisor) { if (divisor <= 0 && divisor != -1) { throw new System.ArgumentException("divisor must be >= 1, or -1 (got " + divisor + ")"); } readerTermsIndexDivisor = divisor; return this; } /// <summary> /// Returns the {@code termInfosIndexDivisor}. /// </summary> /// <seealso cref= #setReaderTermsIndexDivisor(int) </seealso> public virtual int ReaderTermsIndexDivisor { get { return readerTermsIndexDivisor; } } /// <summary> /// Returns the <seealso cref="OpenMode"/> set by <seealso cref="IndexWriterConfig#setOpenMode(OpenMode)"/>. </summary> public virtual OpenMode_e? OpenMode { get { return openMode; } } /// <summary> /// Returns the <seealso cref="DelPolicy"/> specified in /// <seealso cref="IndexWriterConfig#setIndexDeletionPolicy(IndexDeletionPolicy)"/> or /// the default <seealso cref="KeepOnlyLastCommitDeletionPolicy"/>/ /// </summary> public virtual IndexDeletionPolicy DelPolicy { get { return delPolicy; } } /// <summary> /// Returns the <seealso cref="IndexCommit"/> as specified in /// <seealso cref="IndexWriterConfig#setIndexCommit(IndexCommit)"/> or the default, /// {@code null} which specifies to open the latest index commit point. /// </summary> public virtual IndexCommit IndexCommit { get { return Commit; } } /// <summary> /// Expert: returns the <seealso cref="Similarity"/> implementation used by this /// <seealso cref="IndexWriter"/>. /// </summary> public virtual Similarity Similarity { get { return similarity; } } /// <summary> /// Returns the <seealso cref="MergeScheduler"/> that was set by /// <seealso cref="IndexWriterConfig#setMergeScheduler(MergeScheduler)"/>. /// </summary> public virtual IMergeScheduler MergeScheduler { get { return mergeScheduler; } } /// <summary> /// Returns allowed timeout when acquiring the write lock. /// </summary> /// <seealso cref= IndexWriterConfig#setWriteLockTimeout(long) </seealso> public virtual long WriteLockTimeout { get { return writeLockTimeout; } } /// <summary> /// Returns the current <seealso cref="Codec"/>. </summary> public virtual Codec Codec { get { return codec; } } /// <summary> /// Returns the current MergePolicy in use by this writer. /// </summary> /// <seealso cref= IndexWriterConfig#setMergePolicy(MergePolicy) </seealso> public virtual MergePolicy MergePolicy { get { return mergePolicy; } } /// <summary> /// Returns the configured <seealso cref="DocumentsWriterPerThreadPool"/> instance. /// </summary> /// <seealso cref= IndexWriterConfig#setIndexerThreadPool(DocumentsWriterPerThreadPool) </seealso> /// <returns> the configured <seealso cref="DocumentsWriterPerThreadPool"/> instance. </returns> public virtual DocumentsWriterPerThreadPool IndexerThreadPool { get { return indexerThreadPool; } } /// <summary> /// Returns the max number of simultaneous threads that may be indexing /// documents at once in IndexWriter. /// </summary> public virtual int MaxThreadStates { get { try { return ((ThreadAffinityDocumentsWriterThreadPool)indexerThreadPool).MaxThreadStates; } catch (System.InvalidCastException cce) { throw new InvalidOperationException(cce.Message, cce); } } } /// <summary> /// Returns {@code true} if <seealso cref="IndexWriter"/> should pool readers even if /// <seealso cref="DirectoryReader#open(IndexWriter, boolean)"/> has not been called. /// </summary> public virtual bool ReaderPooling { get { return readerPooling; } } /// <summary> /// Returns the indexing chain set on /// <seealso cref="IndexWriterConfig#setIndexingChain(IndexingChain)"/>. /// </summary> public virtual IndexingChain IndexingChain { get { return indexingChain; } } /// <summary> /// Returns the max amount of memory each <seealso cref="DocumentsWriterPerThread"/> can /// consume until forcefully flushed. /// </summary> /// <seealso cref= IndexWriterConfig#setRAMPerThreadHardLimitMB(int) </seealso> public virtual int RAMPerThreadHardLimitMB { get { return PerThreadHardLimitMB; } } /// <seealso cref= IndexWriterConfig#setFlushPolicy(FlushPolicy) </seealso> public virtual FlushPolicy FlushPolicy { get { return flushPolicy; } } /// <summary> /// Returns <seealso cref="InfoStream"/> used for debugging. /// </summary> /// <seealso cref= IndexWriterConfig#setInfoStream(InfoStream) </seealso> public virtual InfoStream InfoStream { get { return infoStream; } set { infoStream = value; } } /// <summary> /// Sets if the <seealso cref="IndexWriter"/> should pack newly written segments in a /// compound file. Default is <code>true</code>. /// <p> /// Use <code>false</code> for batch indexing with very large ram buffer /// settings. /// </p> /// <p> /// <b>Note: To control compound file usage during segment merges see /// <seealso cref="MergePolicy#setNoCFSRatio(double)"/> and /// <seealso cref="MergePolicy#setMaxCFSSegmentSizeMB(double)"/>. this setting only /// applies to newly created segments.</b> /// </p> /// </summary> public virtual LiveIndexWriterConfig SetUseCompoundFile(bool useCompoundFile) { this.useCompoundFile = useCompoundFile; return this; } /// <summary> /// Returns <code>true</code> iff the <seealso cref="IndexWriter"/> packs /// newly written segments in a compound file. Default is <code>true</code>. /// </summary> public virtual bool UseCompoundFile { get { return useCompoundFile; } } /// <summary> /// Sets if <seealso cref="IndexWriter"/> should call <seealso cref="AtomicReader#checkIntegrity()"/> /// on existing segments before merging them into a new one. /// <p> /// Use <code>true</code> to enable this safety check, which can help /// reduce the risk of propagating index corruption from older segments /// into new ones, at the expense of slower merging. /// </p> /// </summary> public virtual LiveIndexWriterConfig SetCheckIntegrityAtMerge(bool checkIntegrityAtMerge) { this.checkIntegrityAtMerge = checkIntegrityAtMerge; return this; } /// <summary> /// Returns true if <seealso cref="AtomicReader#checkIntegrity()"/> is called before /// merging segments. /// </summary> public virtual bool CheckIntegrityAtMerge { get { return checkIntegrityAtMerge; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("matchVersion=").Append(MatchVersion).Append("\n"); sb.Append("analyzer=").Append(analyzer == null ? "null" : analyzer.GetType().Name).Append("\n"); sb.Append("ramBufferSizeMB=").Append(RAMBufferSizeMB).Append("\n"); sb.Append("maxBufferedDocs=").Append(MaxBufferedDocs).Append("\n"); sb.Append("maxBufferedDeleteTerms=").Append(MaxBufferedDeleteTerms).Append("\n"); sb.Append("mergedSegmentWarmer=").Append(MergedSegmentWarmer).Append("\n"); sb.Append("readerTermsIndexDivisor=").Append(ReaderTermsIndexDivisor).Append("\n"); sb.Append("termIndexInterval=").Append(TermIndexInterval).Append("\n"); // TODO: this should be private to the codec, not settable here sb.Append("delPolicy=").Append(DelPolicy.GetType().Name).Append("\n"); IndexCommit commit = IndexCommit; sb.Append("commit=").Append(commit == null ? "null" : commit.ToString()).Append("\n"); sb.Append("openMode=").Append(OpenMode).Append("\n"); sb.Append("similarity=").Append(Similarity.GetType().Name).Append("\n"); sb.Append("mergeScheduler=").Append(MergeScheduler).Append("\n"); sb.Append("default WRITE_LOCK_TIMEOUT=").Append(IndexWriterConfig.WRITE_LOCK_TIMEOUT).Append("\n"); sb.Append("writeLockTimeout=").Append(WriteLockTimeout).Append("\n"); sb.Append("codec=").Append(Codec).Append("\n"); sb.Append("infoStream=").Append(InfoStream.GetType().Name).Append("\n"); sb.Append("mergePolicy=").Append(MergePolicy).Append("\n"); sb.Append("indexerThreadPool=").Append(IndexerThreadPool).Append("\n"); sb.Append("readerPooling=").Append(ReaderPooling).Append("\n"); sb.Append("perThreadHardLimitMB=").Append(RAMPerThreadHardLimitMB).Append("\n"); sb.Append("useCompoundFile=").Append(UseCompoundFile).Append("\n"); sb.Append("checkIntegrityAtMerge=").Append(CheckIntegrityAtMerge).Append("\n"); return sb.ToString(); } } }
// ---------------------------------------------------------------------------------- // // Copyright 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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Internal.Common { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; public class ConsoleApplicationStandardOutputEvents : StandardOutputEvents, ICommandParserOutputEvents { static protected ConsoleColor DefaultForegroundColor { get; private set; } static protected bool SetCursorPostionSupported { get; private set;} static public bool Verbose { get; set; } protected TraceSource TraceSource { get; set; } public int NumberOfErrors { get; private set; } public int NumberOfWarnings { get; private set; } public bool HasErrors { get { return NumberOfErrors > 0; } } public bool HasWarnings { get { return NumberOfWarnings > 0; } } protected ConsoleApplicationStandardOutputEvents() { } public ConsoleApplicationStandardOutputEvents(TraceSource traceSource) { TraceSource = traceSource; } static ConsoleApplicationStandardOutputEvents() { if (Environment.GetEnvironmentVariable("_CSVERBOSE") != null) { Verbose = true; } DefaultForegroundColor = Console.ForegroundColor; try { Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop); SetCursorPostionSupported = true; } catch (Exception) { SetCursorPostionSupported = false; } } override public void LogWarning(int ecode, string fmt, params object[] args) { NumberOfWarnings++; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(fmt,args); Console.ForegroundColor = DefaultForegroundColor; if (TraceSource != null) { TraceSource.TraceEvent(TraceEventType.Warning, ecode, fmt, args); } } override public void LogError(int ecode, string fmt, params object[] args) { NumberOfErrors++; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(fmt, args); Console.ForegroundColor = DefaultForegroundColor; if (TraceSource != null) { TraceSource.TraceEvent(TraceEventType.Error, ecode, fmt, args); } } override public void LogImportantMessage(int ecode, string fmt, params object[] args) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(fmt, args); Console.ForegroundColor = DefaultForegroundColor; if (TraceSource != null) { TraceSource.TraceEvent(TraceEventType.Information, ecode, fmt, args); } } override public void LogMessage(int ecode, string fmt, params object[] args) { Console.WriteLine(fmt, args); if (TraceSource != null) { TraceSource.TraceEvent(TraceEventType.Information, ecode, fmt, args); } } override public void LogDebug(string fmt, params object[] args) { if (Verbose) { Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(fmt, args); Console.ForegroundColor = DefaultForegroundColor; } if (TraceSource != null) { TraceSource.TraceEvent(TraceEventType.Verbose, 0, fmt, args); } } override public void LogProgress(string fmt, params object[] args) { if (SetCursorPostionSupported) { int lineWidth = Console.BufferWidth; var emptyLine = new String(' ', lineWidth); Console.Write(emptyLine); Console.SetCursorPosition(0, Console.CursorTop - 1); Console.WriteLine(fmt, args); Console.SetCursorPosition(0, Console.CursorTop - 1); } else { Console.WriteLine(fmt, args); } } public void ShowBanner(string title,string version) { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo( System.Reflection.Assembly.GetExecutingAssembly().Location); if (version == null) version = versionInfo.FileVersion; LogMessage("Windows(R) Azure(TM) {0} version {1}",title, version ); LogMessage("for Microsoft(R) .NET Framework 3.5"); LogMessage(versionInfo.LegalCopyright); LogMessage(""); } public void CommandUnknown(string commandName) { LogError("Command {0} is unknown.", commandName); } public void CommandTooManyArguments(string commandName, int expected, int found, IEnumerable<string> args) { var fmtArgs = "'" + string.Join("', '",args.ToArray()) + "'"; LogError("Too many arguments for command {0} expects {1} argument(s) found {2}.\nFound: {3}", commandName, expected, found, fmtArgs); } public void CommandTooFewArguments(string commandName, int expected, int found, IEnumerable<string> args) { var fmtArgs = "'" + string.Join("', '", args.ToArray()) + "'"; LogError("Too few arguments for command {0} expects {1} argument(s) found {2}.\nFound: {3}", commandName, expected, found, fmtArgs); } public void CommandParamUnknown(string commandName, string switchName) { LogError("Named parameter \"{0}\" for command {1} is unknown.", switchName, commandName); } public void CommandMissingParam(string commandName, string switchUsage) { LogError("Named parameter \"{0}\" missing for command {1}.", switchUsage, commandName); } public void CommandMissing() { LogError("No command specified."); } public void CommandParamMissingArgument(string commandName, string switchUsage) { LogError("Parameter \"{0}\" for command {1} is required.", switchUsage, commandName); } public void CommandUsage(CommandDefinition commandDefiniton, Func<SwitchDefinition,string> switchUsage) { var indent = " "; var switchSyntax = from sw in commandDefiniton.Switches.Values orderby sw.Name where sw.Undocumented == false select switchUsage(sw); LogMessage("NAME"); LogMessage(indent + commandDefiniton.Name); LogMessage(""); if(commandDefiniton.Category != CommandCategory.None) { LogMessage("CATEGORY"); LogMessage(indent + commandDefiniton.Category); LogMessage(""); } LogMessage("SYNOPSIS"); LogMessage(indent + commandDefiniton.Description); LogMessage(""); LogMessage("SYNTAX"); LogMessage(indent + commandDefiniton.Name + " " + String.Join(" ", switchSyntax.ToArray())); LogMessage(""); } public void CommandDeprecated(CommandDefinition old, CommandDefinition newCmd) { LogWarning("The command {0} is deprecated. Please use the command {1} instead.", old.Name, newCmd.Name); } public void Format(IEnumerable<CommandDefinition> commands) { if (commands.All(cd => cd.Category == CommandCategory.None)) { var fmt = new ListOutputFormatter(this, "Name", "Synopsis"); var records = from cmddef in commands orderby cmddef.Name select fmt.MakeRecord(cmddef.Name, cmddef.Description); fmt.OutputRecords(records); } else { var fmt = new ListOutputFormatter(this, "Name", "Category", "Synopsis"); var records = from cmddef in commands orderby cmddef.Category, cmddef.Name select fmt.MakeRecord(cmddef.Name, cmddef.Category, cmddef.Description); fmt.OutputRecords(records); } } public void CommandDuplicateParam(string switchUsage) { LogWarning("Duplicate named parameter: {0}", switchUsage); } public void DebugCommandLine(string[] args) { int i = 0; foreach (var arg in args) { int argnum = i++; LogDebug("arg[{0}]=\"{1}\"", argnum, arg); string[] charCodes = arg.ToCharArray().Select(c => String.Format("{0}", (int)c)).ToArray(); LogDebug("arg[{0}]={{ {1} }}", argnum, String.Join(", ", charCodes)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedDivideNullableTests { #region Test methods [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableByte(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableFloat(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableInt(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableLong(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableSByte(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableShort(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUInt(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableULong(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUShort(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableNumberTest(bool useInterpreter) { Number?[] values = new Number?[] { null, new Number(0), new Number(1), Number.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableNumber(values[i], values[j], useInterpreter); } } } #endregion #region Helpers public static byte DivideNullableByte(byte a, byte b) { return (byte)(a / b); } public static char DivideNullableChar(char a, char b) { return (char)(a / b); } public static decimal DivideNullableDecimal(decimal a, decimal b) { return (decimal)(a / b); } public static double DivideNullableDouble(double a, double b) { return (double)(a / b); } public static float DivideNullableFloat(float a, float b) { return (float)(a / b); } public static int DivideNullableInt(int a, int b) { return (int)(a / b); } public static long DivideNullableLong(long a, long b) { return (long)(a / b); } public static sbyte DivideNullableSByte(sbyte a, sbyte b) { return unchecked((sbyte)(a / b)); } public static short DivideNullableShort(short a, short b) { return unchecked((short)(a / b)); } public static uint DivideNullableUInt(uint a, uint b) { return (uint)(a / b); } public static ulong DivideNullableULong(ulong a, ulong b) { return (ulong)(a / b); } public static ushort DivideNullableUShort(ushort a, ushort b) { return (ushort)(a / b); } #endregion #region Test verifiers private static void VerifyDivideNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Divide( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableByte"))); Func<byte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((byte?)(a / b), f()); } private static void VerifyDivideNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.Divide( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableChar"))); Func<char?> f = e.Compile(useInterpreter); if (a.HasValue && b == '\0') Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((char?)(a / b), f()); } private static void VerifyDivideNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Divide( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableDecimal"))); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Divide( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableDouble"))); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDivideNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Divide( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableFloat"))); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDivideNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Divide( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableInt"))); Func<int?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == int.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Divide( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableLong"))); Func<long?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == long.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Divide( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableSByte"))); Func<sbyte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(unchecked((sbyte?)(a / b)), f()); } private static void VerifyDivideNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Divide( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableShort"))); Func<short?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(unchecked((short?)(a / b)), f()); } private static void VerifyDivideNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Divide( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableUInt"))); Func<uint?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Divide( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableULong"))); Func<ulong?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Divide( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableUShort"))); Func<ushort?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((ushort?)(a / b), f()); } private static void VerifyDivideNullableNumber(Number? a, Number? b, bool useInterpreter) { Expression<Func<Number?>> e = Expression.Lambda<Func<Number?>>( Expression.Divide( Expression.Constant(a, typeof(Number?)), Expression.Constant(b, typeof(Number?)))); Assert.Equal(typeof(Number?), e.Body.Type); Func<Number?> f = e.Compile(useInterpreter); if (a.HasValue && b == new Number(0)) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; namespace WebApplication2 { /// <summary> /// Summary description for frmEmergencyProcedures. /// </summary> public partial class frmProfileSPC : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Load_Procedures(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand); } #endregion private void Load_Procedures() { if (!IsPostBack) { lblOrg.Text=Session["OrgName"].ToString(); loadData(); if (Session["Mode"].ToString() == "Locs") { lblContents1.Text="Location: " + Session["LocationName"].ToString(); lblContents2.Text="Task Name: " + Session["ResourceName"].ToString() + Session["TaskName"].ToString() + ": Check Types of Resource Required"; btnAdd.Text=" Cancel "; DataGrid1.Columns[3].Visible=false; DataGrid1.Columns[4].Visible=false; } else if (Session["Mode"].ToString() == "Profiles") { lblContents1.Text=Session["ProfileName"].ToString(); lblContents2.Text=Session["ProcName"].ToString() + ": Types of Contacts"; btnAdd.Width=134; DataGrid1.Columns[6].Visible=false; } } } private void loadData () { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveProfileSPC"; cmd.Connection=this.epsDbConn; if (Session["Mode"].ToString() == "Profiles") { cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Session["ProfileSPId"].ToString(); } if (Session["Mode"].ToString() == "Locs") { cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@ResourceTypeId",SqlDbType.Int); cmd.Parameters["@ResourceTypeId"].Value=Session["ResourceTypeId"].ToString(); cmd.Parameters.Add ("@ProcId",SqlDbType.Int); cmd.Parameters["@ProcId"].Value=Session["ProcId"].ToString(); } DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"ProfileSPC"); Session["ds"] = ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); if (Session["Mode"].ToString() == "Profiles") { assignValues(); } } private void assignValues() { foreach (DataGridItem i in DataGrid1.Items) { TextBox tbDesc = (TextBox)(i.Cells[3].FindControl("txtDesc")); if (i.Cells[5].Text == "&nbsp;") { tbDesc.Text=null; } else { tbDesc.Text = i.Cells[5].Text; } } } private void updateGrid() { if (Session["Mode"].ToString() == "Profiles") { foreach (DataGridItem i in DataGrid1.Items) { TextBox tbDesc = (TextBox)(i.Cells[3].FindControl("txtDesc")); SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_UpdateProfileSPC"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add("@Desc", SqlDbType.NText); cmd.Parameters ["@Desc"].Value=tbDesc.Text.ToString();//Int32.Parse(tb.Text); cmd.Parameters.Add("@Caller", SqlDbType.NVarChar); cmd.Parameters ["@Caller"].Value="frmProfileSPC"; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters ["@Id"].Value=i.Cells[0].Text.ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } else if (Session["Mode"].ToString() == "Locs") { foreach (DataGridItem i in DataGrid1.Items) { { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_AddContactTypes"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@RoleId",SqlDbType.Int); cmd.Parameters["@RoleId"].Value= i.Cells[1].Text; cmd.Parameters.Add ("@TaskId", SqlDbType.Int); cmd.Parameters["@TaskId"].Value=Session["TaskId"]; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } } protected void btnAdd_Click(object sender, System.EventArgs e) { if (Session["Mode"].ToString() == "Profiles") { updateGrid(); Session["CallerCTA"]="frmProfileSPC"; Response.Redirect (strURL + "frmContactTypesAll.aspx?"); } else { Exit(); } } protected void btnExit_Click(object sender, System.EventArgs e) { updateGrid(); Exit(); } private void Exit() { Response.Redirect (strURL + Session["CSPC"].ToString() + ".aspx?"); } private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { if (e.CommandName == "Remove") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_DeleteProfileSPC"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); loadData(); } } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * PageSpeed Insights API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/speed/docs/insights/v1/getting_started'>PageSpeed Insights API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20190129 (1489) * <tr><th>API Docs * <td><a href='https://developers.google.com/speed/docs/insights/v1/getting_started'> * https://developers.google.com/speed/docs/insights/v1/getting_started</a> * <tr><th>Discovery Name<td>pagespeedonline * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using PageSpeed Insights API can be found at * <a href='https://developers.google.com/speed/docs/insights/v1/getting_started'>https://developers.google.com/speed/docs/insights/v1/getting_started</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Pagespeedonline.v1 { /// <summary>The Pagespeedonline Service.</summary> public class PagespeedonlineService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public PagespeedonlineService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public PagespeedonlineService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { pagespeedapi = new PagespeedapiResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "pagespeedonline"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/pagespeedonline/v1/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "pagespeedonline/v1/"; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://www.googleapis.com/batch/pagespeedonline/v1"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch/pagespeedonline/v1"; } } #endif private readonly PagespeedapiResource pagespeedapi; /// <summary>Gets the Pagespeedapi resource.</summary> public virtual PagespeedapiResource Pagespeedapi { get { return pagespeedapi; } } } ///<summary>A base abstract class for Pagespeedonline requests.</summary> public abstract class PagespeedonlineBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new PagespeedonlineBaseServiceRequest instance.</summary> protected PagespeedonlineBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>An opaque string that represents a user for quota purposes. Must not exceed 40 /// characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Deprecated. Please use quotaUser instead.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Pagespeedonline parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "pagespeedapi" collection of methods.</summary> public class PagespeedapiResource { private const string Resource = "pagespeedapi"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public PagespeedapiResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Runs PageSpeed analysis on the page at the specified URL, and returns a PageSpeed score, a list of /// suggestions to make that page faster, and other information.</summary> /// <param name="url">The URL to fetch and analyze</param> public virtual RunpagespeedRequest Runpagespeed(string url) { return new RunpagespeedRequest(service, url); } /// <summary>Runs PageSpeed analysis on the page at the specified URL, and returns a PageSpeed score, a list of /// suggestions to make that page faster, and other information.</summary> public class RunpagespeedRequest : PagespeedonlineBaseServiceRequest<Google.Apis.Pagespeedonline.v1.Data.Result> { /// <summary>Constructs a new Runpagespeed request.</summary> public RunpagespeedRequest(Google.Apis.Services.IClientService service, string url) : base(service) { Url = url; InitParameters(); } /// <summary>The URL to fetch and analyze</summary> [Google.Apis.Util.RequestParameterAttribute("url", Google.Apis.Util.RequestParameterType.Query)] public virtual string Url { get; private set; } /// <summary>Indicates if third party resources should be filtered out before PageSpeed analysis.</summary> /// [default: false] [Google.Apis.Util.RequestParameterAttribute("filter_third_party_resources", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> FilterThirdPartyResources { get; set; } /// <summary>The locale used to localize formatted results</summary> [Google.Apis.Util.RequestParameterAttribute("locale", Google.Apis.Util.RequestParameterType.Query)] public virtual string Locale { get; set; } /// <summary>A PageSpeed rule to run; if none are given, all rules are run</summary> [Google.Apis.Util.RequestParameterAttribute("rule", Google.Apis.Util.RequestParameterType.Query)] public virtual Google.Apis.Util.Repeatable<string> Rule { get; set; } /// <summary>Indicates if binary data containing a screenshot should be included</summary> /// [default: false] [Google.Apis.Util.RequestParameterAttribute("screenshot", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Screenshot { get; set; } /// <summary>The analysis strategy to use</summary> [Google.Apis.Util.RequestParameterAttribute("strategy", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<StrategyEnum> Strategy { get; set; } /// <summary>The analysis strategy to use</summary> public enum StrategyEnum { /// <summary>Fetch and analyze the URL for desktop browsers</summary> [Google.Apis.Util.StringValueAttribute("desktop")] Desktop, /// <summary>Fetch and analyze the URL for mobile devices</summary> [Google.Apis.Util.StringValueAttribute("mobile")] Mobile, } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "runpagespeed"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "runPagespeed"; } } /// <summary>Initializes Runpagespeed parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "url", new Google.Apis.Discovery.Parameter { Name = "url", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = @"(?i)http(s)?://.*", }); RequestParameters.Add( "filter_third_party_resources", new Google.Apis.Discovery.Parameter { Name = "filter_third_party_resources", IsRequired = false, ParameterType = "query", DefaultValue = "false", Pattern = null, }); RequestParameters.Add( "locale", new Google.Apis.Discovery.Parameter { Name = "locale", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"[a-zA-Z]+(_[a-zA-Z]+)?", }); RequestParameters.Add( "rule", new Google.Apis.Discovery.Parameter { Name = "rule", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"[a-zA-Z]+", }); RequestParameters.Add( "screenshot", new Google.Apis.Discovery.Parameter { Name = "screenshot", IsRequired = false, ParameterType = "query", DefaultValue = "false", Pattern = null, }); RequestParameters.Add( "strategy", new Google.Apis.Discovery.Parameter { Name = "strategy", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Pagespeedonline.v1.Data { public class Result : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The captcha verify result</summary> [Newtonsoft.Json.JsonPropertyAttribute("captchaResult")] public virtual string CaptchaResult { get; set; } /// <summary>Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and /// run by the server.</summary> [Newtonsoft.Json.JsonPropertyAttribute("formattedResults")] public virtual Result.FormattedResultsData FormattedResults { get; set; } /// <summary>Canonicalized and final URL for the document, after following page redirects (if any).</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>List of rules that were specified in the request, but which the server did not know how to /// instantiate.</summary> [Newtonsoft.Json.JsonPropertyAttribute("invalidRules")] public virtual System.Collections.Generic.IList<string> InvalidRules { get; set; } /// <summary>Kind of result.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, /// etc.</summary> [Newtonsoft.Json.JsonPropertyAttribute("pageStats")] public virtual Result.PageStatsData PageStats { get; set; } /// <summary>Response code for the document. 200 indicates a normal page load. 4xx/5xx indicates an /// error.</summary> [Newtonsoft.Json.JsonPropertyAttribute("responseCode")] public virtual System.Nullable<int> ResponseCode { get; set; } /// <summary>The PageSpeed Score (0-100), which indicates how much faster a page could be. A high score /// indicates little room for improvement, while a lower score indicates more room for improvement.</summary> [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual System.Nullable<int> Score { get; set; } /// <summary>Base64-encoded screenshot of the page that was analyzed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("screenshot")] public virtual Result.ScreenshotData Screenshot { get; set; } /// <summary>Title of the page, as displayed in the browser's title bar.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The version of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual Result.VersionData Version { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and /// run by the server.</summary> public class FormattedResultsData { /// <summary>The locale of the formattedResults, e.g. "en_US".</summary> [Newtonsoft.Json.JsonPropertyAttribute("locale")] public virtual string Locale { get; set; } /// <summary>Dictionary of formatted rule results, with one entry for each PageSpeed rule instantiated and /// run by the server.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ruleResults")] public virtual System.Collections.Generic.IDictionary<string,FormattedResultsData.RuleResultsDataElement> RuleResults { get; set; } /// <summary>The enum-like identifier for this rule. For instance "EnableKeepAlive" or "AvoidCssImport". Not /// localized.</summary> public class RuleResultsDataElement { /// <summary>Localized name of the rule, intended for presentation to a user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("localizedRuleName")] public virtual string LocalizedRuleName { get; set; } /// <summary>The impact (unbounded floating point value) that implementing the suggestions for this rule /// would have on making the page faster. Impact is comparable between rules to determine which rule's /// suggestions would have a higher or lower impact on making a page faster. For instance, if enabling /// compression would save 1MB, while optimizing images would save 500kB, the enable compression rule /// would have 2x the impact of the image optimization rule, all other things being equal.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ruleImpact")] public virtual System.Nullable<double> RuleImpact { get; set; } /// <summary>List of blocks of URLs. Each block may contain a heading and a list of URLs. Each URL may /// optionally include additional details.</summary> [Newtonsoft.Json.JsonPropertyAttribute("urlBlocks")] public virtual System.Collections.Generic.IList<RuleResultsDataElement.UrlBlocksData> UrlBlocks { get; set; } public class UrlBlocksData { /// <summary>Heading to be displayed with the list of URLs.</summary> [Newtonsoft.Json.JsonPropertyAttribute("header")] public virtual UrlBlocksData.HeaderData Header { get; set; } /// <summary>List of entries that provide information about URLs in the url block. /// Optional.</summary> [Newtonsoft.Json.JsonPropertyAttribute("urls")] public virtual System.Collections.Generic.IList<UrlBlocksData.UrlsData> Urls { get; set; } /// <summary>Heading to be displayed with the list of URLs.</summary> public class HeaderData { /// <summary>List of arguments for the format string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("args")] public virtual System.Collections.Generic.IList<HeaderData.ArgsData> Args { get; set; } /// <summary>A localized format string with $N placeholders, where N is the 1-indexed argument /// number, e.g. 'Minifying the following $1 resources would save a total of $2 /// bytes'.</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } public class ArgsData { /// <summary>Type of argument. One of URL, STRING_LITERAL, INT_LITERAL, BYTES, or /// DURATION.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>Argument value, as a localized string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } } } public class UrlsData { /// <summary>List of entries that provide additional details about a single URL. /// Optional.</summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<UrlsData.DetailsData> Details { get; set; } /// <summary>A format string that gives information about the URL, and a list of arguments for /// that format string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("result")] public virtual UrlsData.ResultData Result { get; set; } public class DetailsData { /// <summary>List of arguments for the format string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("args")] public virtual System.Collections.Generic.IList<DetailsData.ArgsData> Args { get; set; } /// <summary>A localized format string with $N placeholders, where N is the 1-indexed /// argument number, e.g. 'Unnecessary metadata for this resource adds an additional $1 /// bytes to its download size'.</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } public class ArgsData { /// <summary>Type of argument. One of URL, STRING_LITERAL, INT_LITERAL, BYTES, or /// DURATION.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>Argument value, as a localized string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } } } /// <summary>A format string that gives information about the URL, and a list of arguments for /// that format string.</summary> public class ResultData { /// <summary>List of arguments for the format string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("args")] public virtual System.Collections.Generic.IList<ResultData.ArgsData> Args { get; set; } /// <summary>A localized format string with $N placeholders, where N is the 1-indexed /// argument number, e.g. 'Minifying the resource at URL $1 can save $2 bytes'.</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } public class ArgsData { /// <summary>Type of argument. One of URL, STRING_LITERAL, INT_LITERAL, BYTES, or /// DURATION.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>Argument value, as a localized string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } } } } } } } /// <summary>Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, /// etc.</summary> public class PageStatsData { /// <summary>Number of uncompressed response bytes for CSS resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("cssResponseBytes")] public virtual System.Nullable<long> CssResponseBytes { get; set; } /// <summary>Number of response bytes for flash resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("flashResponseBytes")] public virtual System.Nullable<long> FlashResponseBytes { get; set; } /// <summary>Number of uncompressed response bytes for the main HTML document and all iframes on the /// page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("htmlResponseBytes")] public virtual System.Nullable<long> HtmlResponseBytes { get; set; } /// <summary>Number of response bytes for image resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("imageResponseBytes")] public virtual System.Nullable<long> ImageResponseBytes { get; set; } /// <summary>Number of uncompressed response bytes for JS resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("javascriptResponseBytes")] public virtual System.Nullable<long> JavascriptResponseBytes { get; set; } /// <summary>Number of CSS resources referenced by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberCssResources")] public virtual System.Nullable<int> NumberCssResources { get; set; } /// <summary>Number of unique hosts referenced by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberHosts")] public virtual System.Nullable<int> NumberHosts { get; set; } /// <summary>Number of JavaScript resources referenced by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberJsResources")] public virtual System.Nullable<int> NumberJsResources { get; set; } /// <summary>Number of HTTP resources loaded by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberResources")] public virtual System.Nullable<int> NumberResources { get; set; } /// <summary>Number of static (i.e. cacheable) resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberStaticResources")] public virtual System.Nullable<int> NumberStaticResources { get; set; } /// <summary>Number of response bytes for other resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("otherResponseBytes")] public virtual System.Nullable<long> OtherResponseBytes { get; set; } /// <summary>Number of uncompressed response bytes for text resources not covered by other statistics (i.e /// non-HTML, non-script, non-CSS resources) on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("textResponseBytes")] public virtual System.Nullable<long> TextResponseBytes { get; set; } /// <summary>Total size of all request bytes sent by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("totalRequestBytes")] public virtual System.Nullable<long> TotalRequestBytes { get; set; } } /// <summary>Base64-encoded screenshot of the page that was analyzed.</summary> public class ScreenshotData { /// <summary>Image data base64 encoded.</summary> [Newtonsoft.Json.JsonPropertyAttribute("data")] public virtual string Data { get; set; } /// <summary>Height of screenshot in pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>Mime type of image data. E.g. "image/jpeg".</summary> [Newtonsoft.Json.JsonPropertyAttribute("mime_type")] public virtual string MimeType { get; set; } /// <summary>Width of screenshot in pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } } /// <summary>The version of PageSpeed used to generate these results.</summary> public class VersionData { /// <summary>The major version number of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("major")] public virtual System.Nullable<int> Major { get; set; } /// <summary>The minor version number of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("minor")] public virtual System.Nullable<int> Minor { get; set; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: operations/rpc/room_claims_svc.proto #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace HOLMS.Types.Operations.RPC { public static partial class RoomClaimsSvc { static readonly string __ServiceName = "holms.types.operations.rpc.RoomClaimsSvc"; static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest> __Marshaller_RoomClaimsSvcSearchRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchResponse> __Marshaller_RoomClaimsSvcSearchResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.ContinuousRoomClaimsSvcSearchResponse> __Marshaller_ContinuousRoomClaimsSvcSearchResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.ContinuousRoomClaimsSvcSearchResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationRequest> __Marshaller_RoomClaimsSvcGetClaimableByReservationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationResponse> __Marshaller_RoomClaimsSvcGetClaimableByReservationResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsRequest> __Marshaller_RoomClaimsSvcUpdateReservationRoomClaimsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsResponse> __Marshaller_RoomClaimsSvcUpdateReservationRoomClaimsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsRequest> __Marshaller_GetAllRoomsWithClaimsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsResponse> __Marshaller_GetAllRoomsWithClaimsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsResponse.Parser.ParseFrom); static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest, global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchResponse> __Method_Search = new grpc::Method<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest, global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchResponse>( grpc::MethodType.Unary, __ServiceName, "Search", __Marshaller_RoomClaimsSvcSearchRequest, __Marshaller_RoomClaimsSvcSearchResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest, global::HOLMS.Types.Operations.RPC.ContinuousRoomClaimsSvcSearchResponse> __Method_SearchContinuousClaims = new grpc::Method<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest, global::HOLMS.Types.Operations.RPC.ContinuousRoomClaimsSvcSearchResponse>( grpc::MethodType.Unary, __ServiceName, "SearchContinuousClaims", __Marshaller_RoomClaimsSvcSearchRequest, __Marshaller_ContinuousRoomClaimsSvcSearchResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationRequest, global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationResponse> __Method_GetClaimableByReservation = new grpc::Method<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationRequest, global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationResponse>( grpc::MethodType.Unary, __ServiceName, "GetClaimableByReservation", __Marshaller_RoomClaimsSvcGetClaimableByReservationRequest, __Marshaller_RoomClaimsSvcGetClaimableByReservationResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsRequest, global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsResponse> __Method_UpdateReservationRoomClaims = new grpc::Method<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsRequest, global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsResponse>( grpc::MethodType.Unary, __ServiceName, "UpdateReservationRoomClaims", __Marshaller_RoomClaimsSvcUpdateReservationRoomClaimsRequest, __Marshaller_RoomClaimsSvcUpdateReservationRoomClaimsResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsRequest, global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsResponse> __Method_GetAllRoomsWithClaims = new grpc::Method<global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsRequest, global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsResponse>( grpc::MethodType.Unary, __ServiceName, "GetAllRoomsWithClaims", __Marshaller_GetAllRoomsWithClaimsRequest, __Marshaller_GetAllRoomsWithClaimsResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.RoomClaimsSvcReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of RoomClaimsSvc</summary> public abstract partial class RoomClaimsSvcBase { public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchResponse> Search(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.ContinuousRoomClaimsSvcSearchResponse> SearchContinuousClaims(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationResponse> GetClaimableByReservation(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsResponse> UpdateReservationRoomClaims(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsResponse> GetAllRoomsWithClaims(global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for RoomClaimsSvc</summary> public partial class RoomClaimsSvcClient : grpc::ClientBase<RoomClaimsSvcClient> { /// <summary>Creates a new client for RoomClaimsSvc</summary> /// <param name="channel">The channel to use to make remote calls.</param> public RoomClaimsSvcClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for RoomClaimsSvc that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public RoomClaimsSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected RoomClaimsSvcClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected RoomClaimsSvcClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchResponse Search(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Search(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchResponse Search(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Search, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchResponse> SearchAsync(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SearchAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchResponse> SearchAsync(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Search, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.ContinuousRoomClaimsSvcSearchResponse SearchContinuousClaims(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SearchContinuousClaims(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.ContinuousRoomClaimsSvcSearchResponse SearchContinuousClaims(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_SearchContinuousClaims, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.ContinuousRoomClaimsSvcSearchResponse> SearchContinuousClaimsAsync(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SearchContinuousClaimsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.ContinuousRoomClaimsSvcSearchResponse> SearchContinuousClaimsAsync(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcSearchRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_SearchContinuousClaims, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationResponse GetClaimableByReservation(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetClaimableByReservation(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationResponse GetClaimableByReservation(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetClaimableByReservation, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationResponse> GetClaimableByReservationAsync(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetClaimableByReservationAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationResponse> GetClaimableByReservationAsync(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcGetClaimableByReservationRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetClaimableByReservation, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsResponse UpdateReservationRoomClaims(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateReservationRoomClaims(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsResponse UpdateReservationRoomClaims(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateReservationRoomClaims, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsResponse> UpdateReservationRoomClaimsAsync(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateReservationRoomClaimsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsResponse> UpdateReservationRoomClaimsAsync(global::HOLMS.Types.Operations.RPC.RoomClaimsSvcUpdateReservationRoomClaimsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateReservationRoomClaims, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsResponse GetAllRoomsWithClaims(global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetAllRoomsWithClaims(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsResponse GetAllRoomsWithClaims(global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetAllRoomsWithClaims, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsResponse> GetAllRoomsWithClaimsAsync(global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetAllRoomsWithClaimsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsResponse> GetAllRoomsWithClaimsAsync(global::HOLMS.Types.Operations.RPC.GetAllRoomsWithClaimsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetAllRoomsWithClaims, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override RoomClaimsSvcClient NewInstance(ClientBaseConfiguration configuration) { return new RoomClaimsSvcClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(RoomClaimsSvcBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_Search, serviceImpl.Search) .AddMethod(__Method_SearchContinuousClaims, serviceImpl.SearchContinuousClaims) .AddMethod(__Method_GetClaimableByReservation, serviceImpl.GetClaimableByReservation) .AddMethod(__Method_UpdateReservationRoomClaims, serviceImpl.UpdateReservationRoomClaims) .AddMethod(__Method_GetAllRoomsWithClaims, serviceImpl.GetAllRoomsWithClaims).Build(); } } } #endregion
using System; using System.Collections; using System.Collections.Generic; /// <summary> /// System.Array.Sort<T>(T [],System.Int32,System.Int32,System.Collections.IComparer<T>) /// </summary> public class ArraySort10 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; //Bug 385712: Won't fix //retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1:Sort a string array using generics and customized comparer"); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Tom", "Allin"}; string[] s2 = new string[6]{"Jack", "Mary", "Mike", "Allin", "Peter", "Tom"}; A a1 = new A(); Array.Sort<string>(s1, 3, 3, a1); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using customized comparer<T> "); try { // We'll add two here since we later do things like subtract two from length int length = 2 + TestLibrary.Generator.GetByte(); int[] i1 = new int[length]; int[] i2 = new int[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetByte(); i1[i] = value; i2[i] = value; } IComparer<int> b1 = new B<int>(); int startIdx = GetInt(0, length - 2); int endIdx = GetInt(startIdx, length - 1); int count = endIdx - startIdx + 1; Array.Sort<int>(i1, startIdx, count, b1); for (int i = startIdx; i < endIdx; i++) //manually quich sort { for (int j = i + 1; j <= endIdx; j++) { if (i2[i] > i2[j]) { int temp = i2[i]; i2[i] = i2[j]; i2[j] = temp; } } } for (int i = 0; i < length; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,the start index is:" + startIdx.ToString() + "the end index is:" + endIdx.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using reverse comparer<T> "); try { char[] c1 = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' }; char[] d1 = new char[10] { 'a', 'e', 'd', 'c', 'b', 'f', 'g', 'h', 'i', 'j' }; IComparer<char> b2 = new B<char>(); Array.Sort<char>(c1, 1, 4, b2); for (int i = 0; i < 10; i++) { if (c1[i] != d1[i]) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Sort customized type array using default customized comparer"); try { C<int>[] c_array = new C<int>[5]; C<int>[] c_result = new C<int>[5]; for (int i = 0; i < 5; i++) { int value = TestLibrary.Generator.GetInt32(); C<int> c1 = new C<int>(value); c_array.SetValue(c1, i); c_result.SetValue(c1, i); } //sort manually C<int> temp; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { if (c_result[i].value > c_result[i + 1].value) { temp = c_result[i]; c_result[i] = c_result[i + 1]; c_result[i + 1] = temp; } } } Array.Sort<C<int>>(c_array, 0, 5, null); for (int i = 0; i < 5; i++) { if (c_result[i].value != c_array[i].value) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array to be sorted is null reference "); try { string[] s1 = null; Array.Sort<string>(s1, 0, 2, null); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected "); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The start index is less than the minimal bound of the array"); try { string[] s1 = new string[6]{"Jack", "Mary", "Peter", "Mike", "Tom", "Allin"}; Array.Sort<string>(s1, -1, 4, null); TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException is not throw as expected "); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: Length is less than zero"); try { string[] s1 = new string[6]{"Jack", "Mary", "Peter", "Mike", "Tom", "Allin"}; Array.Sort<string>(s1, 3, -3, null); TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException is not throw as expected "); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: The start index and length do not specify a valid range in array"); try { int length = TestLibrary.Generator.GetByte(); string[] s1 = new string[length]; for (int i = 0; i < length; i++) { string value = TestLibrary.Generator.GetString(false, 0, 10); s1[i] = value; } int startIdx = GetInt(0, Byte.MaxValue); int increment = length + 1; Array.Sort<string>(s1, startIdx + increment, 0, null); TestLibrary.TestFramework.LogError("107", "The ArgumentException is not throw as expected "); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5:The implementation of comparer caused an error during the sort"); try { int[] i1 = new int[9] { 2, 34, 56, 87, 34, 23, 209, 34, 87 }; IComparer<int> d1 = new D<int>(); Array.Sort<int>(i1, 0, 9, d1); TestLibrary.TestFramework.LogError("109", "The ArgumentException is not throw as expected "); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6: Elements in array do not implement the IComparable interface"); try { E[] a1 = new E[4] { new E(), new E(), new E(), new E() }; IComparer<E> d2 = null; Array.Sort<E>(a1, 0, 4, d2); TestLibrary.TestFramework.LogError("111", "The InvalidOperationException is not throw as expected "); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArraySort10 test = new ArraySort10(); TestLibrary.TestFramework.BeginTestCase("ArraySort10"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } class A : IComparer<string> { #region IComparer<string> Members public int Compare(string x, string y) { return x.CompareTo(y); } #endregion } class B<T> : IComparer<T> where T : IComparable { #region IComparer<T> Members public int Compare(T x, T y) { if (typeof(T) == typeof(char)) { return -x.CompareTo(y); } return x.CompareTo(y); } #endregion } class C<T> : IComparable where T : IComparable { public T value; public C(T a) { this.value = a; } #region IComparable Members public int CompareTo(object obj) { return value.CompareTo(((C<T>)obj).value); } #endregion } class D<T> : IComparer<T> where T : IComparable { #region IComparer<T> Members public int Compare(T x, T y) { if (x.CompareTo(x) == 0) return -1; return 1; } #endregion } class E { public E() { } } #region Help method for geting test data private Int32 GetInt(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32() % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Responses/EncounterResponse.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Networking.Responses { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/EncounterResponse.proto</summary> public static partial class EncounterResponseReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Responses/EncounterResponse.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static EncounterResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjdQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL0VuY291bnRlclJl", "c3BvbnNlLnByb3RvEh9QT0dPUHJvdG9zLk5ldHdvcmtpbmcuUmVzcG9uc2Vz", "GjBQT0dPUHJvdG9zL0RhdGEvQ2FwdHVyZS9DYXB0dXJlUHJvYmFiaWxpdHku", "cHJvdG8aKFBPR09Qcm90b3MvTWFwL1Bva2Vtb24vV2lsZFBva2Vtb24ucHJv", "dG8itAQKEUVuY291bnRlclJlc3BvbnNlEjkKDHdpbGRfcG9rZW1vbhgBIAEo", "CzIjLlBPR09Qcm90b3MuTWFwLlBva2Vtb24uV2lsZFBva2Vtb24SUQoKYmFj", "a2dyb3VuZBgCIAEoDjI9LlBPR09Qcm90b3MuTmV0d29ya2luZy5SZXNwb25z", "ZXMuRW5jb3VudGVyUmVzcG9uc2UuQmFja2dyb3VuZBJJCgZzdGF0dXMYAyAB", "KA4yOS5QT0dPUHJvdG9zLk5ldHdvcmtpbmcuUmVzcG9uc2VzLkVuY291bnRl", "clJlc3BvbnNlLlN0YXR1cxJIChNjYXB0dXJlX3Byb2JhYmlsaXR5GAQgASgL", "MisuUE9HT1Byb3Rvcy5EYXRhLkNhcHR1cmUuQ2FwdHVyZVByb2JhYmlsaXR5", "IiIKCkJhY2tncm91bmQSCAoEUEFSSxAAEgoKBkRFU0VSVBABItcBCgZTdGF0", "dXMSEwoPRU5DT1VOVEVSX0VSUk9SEAASFQoRRU5DT1VOVEVSX1NVQ0NFU1MQ", "ARIXChNFTkNPVU5URVJfTk9UX0ZPVU5EEAISFAoQRU5DT1VOVEVSX0NMT1NF", "RBADEhoKFkVOQ09VTlRFUl9QT0tFTU9OX0ZMRUQQBBIaChZFTkNPVU5URVJf", "Tk9UX0lOX1JBTkdFEAUSHgoaRU5DT1VOVEVSX0FMUkVBRFlfSEFQUEVORUQQ", "BhIaChZQT0tFTU9OX0lOVkVOVE9SWV9GVUxMEAdiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Data.Capture.CaptureProbabilityReflection.Descriptor, global::POGOProtos.Map.Pokemon.WildPokemonReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.EncounterResponse), global::POGOProtos.Networking.Responses.EncounterResponse.Parser, new[]{ "WildPokemon", "Background", "Status", "CaptureProbability" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.EncounterResponse.Types.Background), typeof(global::POGOProtos.Networking.Responses.EncounterResponse.Types.Status) }, null) })); } #endregion } #region Messages public sealed partial class EncounterResponse : pb::IMessage<EncounterResponse> { private static readonly pb::MessageParser<EncounterResponse> _parser = new pb::MessageParser<EncounterResponse>(() => new EncounterResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<EncounterResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Responses.EncounterResponseReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EncounterResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EncounterResponse(EncounterResponse other) : this() { WildPokemon = other.wildPokemon_ != null ? other.WildPokemon.Clone() : null; background_ = other.background_; status_ = other.status_; CaptureProbability = other.captureProbability_ != null ? other.CaptureProbability.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EncounterResponse Clone() { return new EncounterResponse(this); } /// <summary>Field number for the "wild_pokemon" field.</summary> public const int WildPokemonFieldNumber = 1; private global::POGOProtos.Map.Pokemon.WildPokemon wildPokemon_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Map.Pokemon.WildPokemon WildPokemon { get { return wildPokemon_; } set { wildPokemon_ = value; } } /// <summary>Field number for the "background" field.</summary> public const int BackgroundFieldNumber = 2; private global::POGOProtos.Networking.Responses.EncounterResponse.Types.Background background_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Responses.EncounterResponse.Types.Background Background { get { return background_; } set { background_ = value; } } /// <summary>Field number for the "status" field.</summary> public const int StatusFieldNumber = 3; private global::POGOProtos.Networking.Responses.EncounterResponse.Types.Status status_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Responses.EncounterResponse.Types.Status Status { get { return status_; } set { status_ = value; } } /// <summary>Field number for the "capture_probability" field.</summary> public const int CaptureProbabilityFieldNumber = 4; private global::POGOProtos.Data.Capture.CaptureProbability captureProbability_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Data.Capture.CaptureProbability CaptureProbability { get { return captureProbability_; } set { captureProbability_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as EncounterResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(EncounterResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(WildPokemon, other.WildPokemon)) return false; if (Background != other.Background) return false; if (Status != other.Status) return false; if (!object.Equals(CaptureProbability, other.CaptureProbability)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (wildPokemon_ != null) hash ^= WildPokemon.GetHashCode(); if (Background != 0) hash ^= Background.GetHashCode(); if (Status != 0) hash ^= Status.GetHashCode(); if (captureProbability_ != null) hash ^= CaptureProbability.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (wildPokemon_ != null) { output.WriteRawTag(10); output.WriteMessage(WildPokemon); } if (Background != 0) { output.WriteRawTag(16); output.WriteEnum((int) Background); } if (Status != 0) { output.WriteRawTag(24); output.WriteEnum((int) Status); } if (captureProbability_ != null) { output.WriteRawTag(34); output.WriteMessage(CaptureProbability); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (wildPokemon_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(WildPokemon); } if (Background != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Background); } if (Status != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status); } if (captureProbability_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CaptureProbability); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(EncounterResponse other) { if (other == null) { return; } if (other.wildPokemon_ != null) { if (wildPokemon_ == null) { wildPokemon_ = new global::POGOProtos.Map.Pokemon.WildPokemon(); } WildPokemon.MergeFrom(other.WildPokemon); } if (other.Background != 0) { Background = other.Background; } if (other.Status != 0) { Status = other.Status; } if (other.captureProbability_ != null) { if (captureProbability_ == null) { captureProbability_ = new global::POGOProtos.Data.Capture.CaptureProbability(); } CaptureProbability.MergeFrom(other.CaptureProbability); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (wildPokemon_ == null) { wildPokemon_ = new global::POGOProtos.Map.Pokemon.WildPokemon(); } input.ReadMessage(wildPokemon_); break; } case 16: { background_ = (global::POGOProtos.Networking.Responses.EncounterResponse.Types.Background) input.ReadEnum(); break; } case 24: { status_ = (global::POGOProtos.Networking.Responses.EncounterResponse.Types.Status) input.ReadEnum(); break; } case 34: { if (captureProbability_ == null) { captureProbability_ = new global::POGOProtos.Data.Capture.CaptureProbability(); } input.ReadMessage(captureProbability_); break; } } } } #region Nested types /// <summary>Container for nested types declared in the EncounterResponse message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum Background { [pbr::OriginalName("PARK")] Park = 0, [pbr::OriginalName("DESERT")] Desert = 1, } public enum Status { [pbr::OriginalName("ENCOUNTER_ERROR")] EncounterError = 0, [pbr::OriginalName("ENCOUNTER_SUCCESS")] EncounterSuccess = 1, [pbr::OriginalName("ENCOUNTER_NOT_FOUND")] EncounterNotFound = 2, [pbr::OriginalName("ENCOUNTER_CLOSED")] EncounterClosed = 3, [pbr::OriginalName("ENCOUNTER_POKEMON_FLED")] EncounterPokemonFled = 4, [pbr::OriginalName("ENCOUNTER_NOT_IN_RANGE")] EncounterNotInRange = 5, [pbr::OriginalName("ENCOUNTER_ALREADY_HAPPENED")] EncounterAlreadyHappened = 6, [pbr::OriginalName("POKEMON_INVENTORY_FULL")] PokemonInventoryFull = 7, } } #endregion } #endregion } #endregion Designer generated code
//Copyright (c) 2016, Samuel Pollachini (Samuel Polacchini) //The UnityForCpp project is licensed under the terms of the MIT license using UnityEngine; using UnityEngine.Assertions; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Reflection; namespace UnityForCpp { public class UnityMessager : MonoBehaviour { //Max number of simultaneous message receiver instances bound to the UnityMessager and so able to receive messages. Min value is 16. public int maxNumberOfReceiverIds = 16; //Max size in bytes of the memory blocks used by UnityMessager. Min value is 512, 1024 or 2048 are usually good values. public int maxQueueArraysSizeInBytes = 512; //SINGLETON access point public static UnityMessager Instance { get { return _s_instance; } } //Provides an available receiver id, in such way you can bound your receiver instance (IMessageReceiver) to it using //SetReceiverObject. By requesting it from the C# code you should pass it to the C++ code so it can be used there. public int NewReceiverId() { int nextFreeId = _receiverIdsSharedArray[0]; //Position 0 holder the next free id if (nextFreeId == 0) //0 means there is no more available receive ids, THIS CAN NEVER HAPPEN, set a bigger value on the inspector { Debug.LogError("[UnityMessager] Not enough receiver ids set to your application!!"); return -1; } //The receiver id shared array controls the free ids by implementing a single linked list where a given position //has the id of the next free position. So here we are removing the "nextFreeId" from this list by setting the head //of the list (position 0) to the position indicated by the nextFreeId position. _receiverIdsSharedArray[0] = _receiverIdsSharedArray[nextFreeId]; _receiverIdsSharedArray[nextFreeId] = -1; //this indicates the id is not free, but also wasn't bound to a receiver yet. return nextFreeId; } //This method releases a receiver id setting null to the reference of the receiver instance bound to it. public void ReleaseReceiverId(int receiverId) { if (_receiverIdsSharedArray[receiverId] != -1) //this indicates the id is not in use, being in the free ids linked list. { Debug.LogWarning("[UnityMessager] Attempt to release a receiver id not being used!"); return; } _receivers[receiverId] = null; _receiverGameObjects[receiverId] = null; //reinserts the id to the front of the single linked list, remembering the position 0 is always the head of the list. _receiverIdsSharedArray[receiverId] = _receiverIdsSharedArray[0]; _receiverIdsSharedArray[0] = receiverId; } //Set a C# object as receiver (it may be any C# object, including a game object component if you want make it special, beyond the default) public void SetReceiverObject(int receiverId, IMessageReceiver receiver) { //Check this id was really delivered to you via NewReceiverId(), which may be called from C# or from C++ if (_receiverIdsSharedArray[receiverId] != -1) { Debug.LogError("[UnityMessager] Attempt to set an object to a 'free' Receiver id!. Use NewReceiverId for requesting an id before setting an object to it."); return; } _receivers[receiverId] = receiver; } //Set a game object as receiver and (optionally) specify the default receiver component //the default receiver component is the target for when SendMessage is used from C++ without any component specified public void SetReceiverObject(int receiverId, GameObject gameObject, IMessageReceiver defaultReceiverComponent = null) { //Check this id was really delivered to you via NewReceiverId(), which may be called from C# or from C++ if (_receiverIdsSharedArray[receiverId] != -1) { Debug.LogError("[UnityMessager] Attempt to set an object to a 'free' Receiver id!. Use NewReceiverId for requesting an id before setting an object to it."); return; } _receiverGameObjects[receiverId] = gameObject; _receivers[receiverId] = defaultReceiverComponent != null? defaultReceiverComponent : gameObject.GetComponent(typeof(IMessageReceiver)) as IMessageReceiver; } //If true you usually should call DeliverMessagers right way. public bool HasMessagesToDeliver { get { return _controlQueue.HasMessagesToBeDelivered; } } //Deliver ALL the received messages to the respective receivers. Handlers that call C++ code when handling messages MUST BE //SURE this C++ code will not send messages during the delivering process public void DeliverMessages() { if (!HasMessagesToDeliver) return; //This sets an end message so the delivering process doesn't continue forever and reset things on C++ side UnityMessagerDLL.UM_OnStartMessageDelivering(); try { while (_controlQueue.HasMessagesToBeDelivered) { //_currentUniqueId purpose is only to make sure there was no forbidden calls to Message::FillUnityMessagerInternalMessageInstance Assert.IsTrue(++_currentUniqueId > 0); //always true, inside an assert just to be removed on release builds //The call bellow will read the next message to our internal instance (_internalMessageInstance), so it can be sent to receivers _controlQueue.ReadNextMessageToUnityMessagerInternalInstance(); if (_internalMessageInstance.ComponentId >= 0) //is this message addressed to an specific game object component? { GameObject receiverGameObject = null; if (_internalMessageInstance.ReceiverId >= 0) //was the receiver specified by an id? receiverGameObject = _receiverGameObjects[_internalMessageInstance.ReceiverId]; else { //else we have a name to look for with GameObject.Find int objectNameLength = -_internalMessageInstance.ReceiverId; string objectName = GetParamQueue<Byte>().ReadNextAsString(objectNameLength); receiverGameObject = GameObject.Find(objectName); } if (receiverGameObject != null) //if we have found the receiver game object { //Get the component based on its type, indexed by the component id Component component = receiverGameObject.GetComponent(_componentTypes[_internalMessageInstance.ComponentId]); if (component != null) { if (_internalMessageInstance.MessageId >= 0) //if this is a message to an IMessageReceiver component { IMessageReceiver receiverComponent = component as IMessageReceiver; if (receiverComponent != null) receiverComponent.ReceiveMessage(ref _internalMessageInstance); else Debug.LogError("[UnityMessager] Message sent to an invalid receiver component!"); } else //else this message will be delivered via reflection DeliverMessageWithReflection(component, ref _internalMessageInstance); } else Debug.LogError("[UnityMessager] Message sent to an component the receiver game object doesn't have!!"); } else Debug.LogError("[UnityMessager] Message sent to an invalid or not found GameObject!!"); } else //the message is addressed to a C# object (which may also be the default receiver component of game object receiver). { IMessageReceiver receiver = _receivers[_internalMessageInstance.ReceiverId]; if (receiver != null) receiver.ReceiveMessage(ref _internalMessageInstance); else Debug.LogError("[UnityMessager] Message sent to an invalid receiver object!!"); } //If the message receiver has not read all the parameters we need to advance manually until getting to the start of the next message while (_controlQueue.NumberOfParamsBeforeNextMessage > 0) { ParamInfo paramInfo = _controlQueue.CurrentParamInfo; _messageQueues[paramInfo.QueueId].AdvanceToPos(paramInfo.ArrayLength >= 0 ? paramInfo.ArrayLength : 1); _controlQueue.AdvanceToNextParam(); } } } catch (Exception exception) { _controlQueue.OnFinishDeliveringMessages(); throw exception; } finally { //Reset Message Queues so they get ready for next usage when delivering messages again. for (int i = 0; i < _messageQueues.Length; ++i) _messageQueues[i].Reset(); } } //This method will release almost all the shared arrays (used blocks of memory having around "maxQueueArraysSizeInBytes" bytes each) //being currently used by UnityMessager. This is specially useful when your app loses focus and should free non essential stuff //If needed, the arrays released by this method will be allocated again in the future. public void ReleasePossibleQueueArrays() { UnityMessagerDLL.UM_ReleasePossibleQueueArrays(); } //IMPLEMENT this interface in order to make your class objects capable of receiving and handling messages. public interface IMessageReceiver { void ReceiveMessage(ref UnityMessager.Message msg); } //All the data from a message is delivered to your receiver instance through an instance of this struct //YOU ARE NOT ALLOWED TO MAKE COPIES OF THIS OR TRYING TO KEEP THE REFERENCE BEYOND THE "ReceiveMessage" call. public struct Message { //The receiver associated with the receiving instance handling this message, usually you won't need it public int ReceiverId { get; private set; } //The component Id for the component this message is addressed, usually you won't need it public int ComponentId { get; private set; } //Message Id is a value totally under your control, decide yourself the ids to represent your message types for a given //receiver type and use it on your ReceiveMessage method route the received message to the destination handler code. public int MessageId { get; private set; } //Total number of parameters sent together with this messager. Observe, however some of them may be already read and cannot //be read again. Check NumberOfParamsToBeRead for the parameters that still available for unpacking on the message queues. public int NumberOfParams { get; private set; } //Number of parameters on this message that were not read yet. Each time a method from Message with the "Advance" word on //its name is called, this value gets decremented, since the read parameter value cannot be read again. public int NumberOfParamsToBeRead { get { //safety to check to be sure this call is not coming from a copy of an old Message instance. if (_uniqueId < _s_currentUniqueId) return 0; return UnityMessager.Instance._controlQueue.NumberOfParamsBeforeNextMessage; } } //Returns the next param type. If the next parameter is an array the element type of this array is returned. public Type NextParamType { get { if (_paramInfo.QueueId < 0) return null; return UnityMessager.Instance._messageQueues[_paramInfo.QueueId].QueueType; } } //Use this to check if the next parameter is an array of the type given by "NextParamType" public bool IsNextParamAnArray { get { if (_paramInfo.QueueId < 0) return false; return _paramInfo.ArrayLength >= 0; } } //A parameter can be read as string if it has Byte as type and is an array. This method performs this check for you. public bool CanNextParamBeReadAsString { get { if (_paramInfo.QueueId < 0) return false; return _paramInfo.ArrayLength >= 0 && UnityMessager.Instance._messageQueues[_paramInfo.QueueId].QueueType == typeof(Byte); } } //Reads the next parameter as a single value and advance to the next parameter if any. public T ReadNextParamAndAdvance<T>() { Assert.IsTrue(CheckParamRequest(typeof(T), false)); //When assertions get compiled relevant additional checks are made T param = UnityMessager.Instance.GetParamQueue<T>(_paramInfo.QueueId).ReadNext(); Advance(); return param; } //Reads the next parameter as an ArrayParam/T[] and advance to the next parameter if any. //ArrayParam can be implicitly converted to T[], however by using it directly you may avoid the creation of a new array object, //accessing the values directly from the parameter queue. Check the ArrayParam class for more details. public ArrayParam<T> ReadNextParamAsArrayAndAdvance<T>() { Assert.IsTrue(CheckParamRequest(typeof(T), true)); //When assertions get compiled relevant additional checks are made ArrayParam<T> param = UnityMessager.Instance.GetParamQueue<T>(_paramInfo.QueueId).ReadNextAsArray(_paramInfo.ArrayLength); Advance(); return param; } //Reads the next parameter as an string and advance to the next parameter if any. public string ReadNextParamAsStringAndAdvance() { Assert.IsTrue(CheckParamRequest(typeof(Byte), true)); //When assertions get compiled relevant additional checks are made string param = UnityMessager.Instance.GetParamQueue<Byte>(_paramInfo.QueueId).ReadNextAsString(_paramInfo.ArrayLength); Advance(); return param; } //Reads the next parameter (single or array) as an object and advance to the next parameter if any. //if it is an array, the object will be a c# native array of the current parameter type (T[]) public object ReadNextParamAndAdvance() { bool isArray = IsNextParamAnArray; Assert.IsTrue(CheckParamRequest(null, isArray)); //When assertions get compiled relevant additional checks are made object param = isArray ? UnityMessager.Instance._messageQueues[_paramInfo.QueueId].ReadNextAsArrayBase(_paramInfo.ArrayLength) : UnityMessager.Instance._messageQueues[_paramInfo.QueueId].ReadNextAsObject(); Advance(); return param; } //Skip the next parameter and advance to the next parameter after that if any. public void SkipNextParamAndAdvance() { UnityMessager.Instance._controlQueue.AdvanceToNextParam(); _paramInfo = UnityMessager.Instance._controlQueue.CurrentParamInfo; } //FOR INTERNAL USAGE ONLY!! This method fills the data from the next message to be handled directly into //the internal Message instance of the UnityMessager, avoiding the need of exposing a public constructor or factory method public static void FillUnityMessagerInternalMessageInstance(int rcvId, int rtnId, int msgId, int nOfParams) { UnityMessager unityMessager = UnityMessager.Instance; //Check there was no forbidden calls made to this method Assert.IsTrue(_s_currentUniqueId < unityMessager._currentUniqueId, "[UnityMessager] NOT ALLOWED CALL TO FillUnityMessagerInternalMessageInstance, RESTART THE GAME!!"); unityMessager._internalMessageInstance.ReceiverId = rcvId; unityMessager._internalMessageInstance.ComponentId = rtnId; unityMessager._internalMessageInstance.MessageId = msgId; unityMessager._internalMessageInstance.NumberOfParams = nOfParams; //gives this message an uniqueId in such way it will not be able to request parameters anymore //after the ReceiveMessage method has advanced to the next message unityMessager._internalMessageInstance._uniqueId = ++_s_currentUniqueId; //reads the current parameter to be delivered as "NextParam" on the methods of this struct unityMessager._internalMessageInstance._paramInfo = UnityMessager.Instance._controlQueue.CurrentParamInfo; } //Advance to the next parameter (actually the one that comes after the one said as "next" on method titles private void Advance() { //Now we are advancing to the parameter the comes after the one we calling "Next Parameter" by this method name. UnityMessager.Instance._controlQueue.AdvanceToNextParam(); //so now we have it ready to the next request of -1 set to the _paramInfo.QueueId if there is no other params for this message _paramInfo = UnityMessager.Instance._controlQueue.CurrentParamInfo; } //Perform additional checks to log errors to the user when parameters are being requested in a wrong way for this message instance private bool CheckParamRequest(Type requestedType, bool wasRequestedAsArray) { if (_uniqueId < _s_currentUniqueId) { Debug.LogError("[UnityMessager] ReadNextParamAndAdvance called for an old Message which parameters were already read."); return false; } if (_paramInfo.QueueId < 0) { Debug.LogError("[UnityMessager] Attempt to read a parameter beyond the ones of available for the message!"); return false; } if (requestedType != null && UnityMessager.Instance._messageQueues[_paramInfo.QueueId].QueueType != requestedType) { Debug.LogError("[UnityMessager] Parameter of wrong type being requested!"); return false; } if ((_paramInfo.ArrayLength >= 0) != wasRequestedAsArray) { if (wasRequestedAsArray) Debug.LogError("[UnityMessager] Single parameter value requested as array!"); else Debug.LogError("[UnityMessager] Array parameter requested as single value!"); return false; } return true; } private ParamInfo _paramInfo; private ulong _uniqueId; private static ulong _s_currentUniqueId = 0; //gets increamented at each new message, providing always an unique id. }; //Use this class for receiving and handling array parameters. It usually avoids the need of creating a C# native array instance, //if you need it however, you may use "CopyTo" to fill your C# native array. public struct ArrayParam<T> { public int Length { get; private set; } public T this[int i] { get { Assert.IsTrue(i >= 0 && i < Length); return _array[_firstIdx + i]; } } public void CopyTo(T[] destArray, int destStartIdx, int thisStartIdx, int copyLength) { Assert.IsTrue(thisStartIdx >= 0 && (thisStartIdx + copyLength) <= Length); Array.Copy(_array, _firstIdx + thisStartIdx, destArray, destStartIdx, copyLength); } //better to avoid this implicit conversion on performance sensitive code. public static implicit operator T[](ArrayParam<T> array) { T[] result = new T[array.Length]; array.CopyTo(result, 0, 0, array.Length); return result; } public ArrayParam(T[] array, int firstIdx, int length) : this() { _array = array; _firstIdx = firstIdx; Length = length; } private T[] _array; private int _firstIdx; } //This is only used on debug code to make sure no invalid calls to FillUnityMessagerInternalMessageInstance are being made private ulong _currentUniqueId = 0; //Point of return for the method Message.FillUnityMessagerInternalMessageInstance. Once it is filled it is delivered to its receiver. private Message _internalMessageInstance; //shared array for controling the available receiver ids, keep them in synch between the C++ code and the C# code. private int[] _receiverIdsSharedArray = null; //message receiver instances (OR default component instances) accordingly to their receiverIds. private IMessageReceiver[] _receivers = null; //message receiver game object instances accordingly to their receiverIds private GameObject[] _receiverGameObjects = null; //component types, this is indexed by the unique internal component id for the component type private List<Type> _componentTypes = null; //Message queues arrays, where the 0 position is the control queue and the next ones are the ParamQueue instances, one per param type private MessageQueueBase[] _messageQueues = null; private ControlQueue _controlQueue = null; private const int _controlQueueId = 0; //MUST BE 0, corresponds to UM_CONTROL_QUEUE_ID on C++ private const int _maxNOfMessageQueues = 32; //corresponds to UM_MAX_N_OF_MESSAGE_QUEUES on C++, check comments for this. private static UnityMessager _s_instance = null; //singleton reference holder #if UNITY_EDITOR //Check min value requirement are met for the inspector settings for this class void OnValidate() { if (maxNumberOfReceiverIds < 16) { Debug.LogWarning("Max Number Of Receiver Ids cannot be less than 16!!"); maxNumberOfReceiverIds = 16; } if (maxQueueArraysSizeInBytes < 512) { Debug.LogWarning("Max Queue Arrays' Size In Bytes Cannot Be Less Than 512!!"); maxQueueArraysSizeInBytes = 512; } } #endif private void Awake() { if (_s_instance != null && _s_instance != this) { Destroy(this.gameObject); throw new Exception("[UnityMessager] More than one instance of UnityMessager being created!!"); } if (_s_instance == null) { _s_instance = this; DontDestroyOnLoad(this.gameObject); } int firstArrayId = UnityMessagerDLL.UM_InitUnityMessagerAndGetControlQueueId(maxNumberOfReceiverIds, maxQueueArraysSizeInBytes); _controlQueue = new ControlQueue(firstArrayId); _messageQueues = new MessageQueueBase[_maxNOfMessageQueues]; _messageQueues[0] = _controlQueue; //We create instance of MessageQueueBase so they can hold received ids for the first and current queue arrays //until the user's code requests the corresponding parameter using a generic method for the first time, what will //cause the real ParamQueue to be instanced and replace this placeholder instance we set here. for (int i = 1; i < _messageQueues.Length; ++i) _messageQueues[i] = new MessageQueueBase(i); _receivers = new IMessageReceiver[maxNumberOfReceiverIds]; //Internal MessageReceiver class, handle messages sent to the UnityMessager itself. The receiver Id 0 is known as being its receiver id by default. _receivers[0] = new MessageReceiver(); _receiverGameObjects = new GameObject[maxNumberOfReceiverIds]; _componentTypes = new List<Type>(); DeliverMessages(); //Deliver the first messages, expected to be only control messages to finish with the intialization process } private void OnDestroy() { //This will delete the singleton instance on C++ and release all the shared arrays allocated by the UnityMessager UnityMessagerDLL.UM_OnDestroy(); } //Registers a new component type being used by the C++ code as receiver component for game object receivers private void RegisterComponentType(int id, string typeName) { Assert.IsTrue(_componentTypes.Count == id);//the id is the index, it would be strange if this assertion fails Type componentType = Type.GetType(typeName); Assert.IsTrue(componentType != null, "[UnityMessager] Invalid component type being used from C++"); _componentTypes.Add(componentType); } //helper method for getting the Parameter Queue created at the first time its accessed for an specific type private ParamQueue<T> GetParamQueue<T>(int queueId = -1) { //If this is the first time we are reading a parameter of the type T we need to create the ParamQueue for it. if (ParamQueue<T>.Instance == null) { if (queueId < 0) { for (queueId = 0; queueId < _maxNOfMessageQueues; ++queueId) { if (_messageQueues[queueId].QueueType == typeof(T)) break; } if (queueId == _maxNOfMessageQueues) return null; } //We do that using the existing instance to MessageQueueBase for the respective queueId. //This base class instance has held for us the ids provided in the past for this queueId. ParamQueue<T>.CreateInstance(UnityMessager.Instance._messageQueues[queueId]); //Saves the new ParamQueue instance replacing the base class instance we don't need anymore _messageQueues[queueId] = ParamQueue<T>.Instance; } return ParamQueue<T>.Instance; } //helper method to get a message based on reflection delivered with the message parameters extracted private void DeliverMessageWithReflection(object component, ref Message message) { int methodNameLength = -message.MessageId; //messageId, when negative, is the length of the method name string string methodName = GetParamQueue<Byte>().ReadNextAsString(methodNameLength); MethodInfo methodInfo = component.GetType().GetMethod(methodName); ParameterInfo[] paramInfos = methodInfo.GetParameters(); Assert.IsTrue(message.NumberOfParams == paramInfos.Length); object[] parameters = null; if (paramInfos.Length > 0) //is there any parameter to read { parameters = new object[paramInfos.Length]; int i = -1; while (message.NumberOfParamsToBeRead > 0) parameters[++i] = paramInfos[i].ParameterType == typeof(string) ? //read a string as a string, so we don't get a byte array message.ReadNextParamAsStringAndAdvance() : message.ReadNextParamAndAdvance(); } methodInfo.Invoke(component, parameters); } //Control messages are specific to setup or control the message delivering process itself private void HandleControlMessage(int messageId, ArrayParam<int> arrayParam) { switch (messageId) { case 0: //UMM_SET_QUEUE_ARRAY = 0, used when the current array in use is close to its end, so a new one is needed { Assert.IsTrue(arrayParam.Length == 2); int queueId = arrayParam[0]; int arrayId = arrayParam[1]; _messageQueues[queueId].SetCurrentArray(arrayId); break; } case 1: //UMM_SET_QUEUE_FIRST_ARRAY = 1, first array of a given queue, we keep this info forever so we can reset queues { Assert.IsTrue(arrayParam.Length == 2); int queueId = arrayParam[0]; int arrayId = arrayParam[1]; _messageQueues[queueId].SetFirstArray(arrayId); break; } case 2: //UMM_SET_RECEIVER_IDS_ARRAY = 2, sets the id for the control array of available receiver ids { Assert.IsTrue(arrayParam.Length == 1); int arrayId = arrayParam[0]; _receiverIdsSharedArray = UnityAdapter.Instance.GetSharedArray<int>(arrayId); break; } default: Debug.LogError("[UnityMessager] Unknow message id received by UnityMessager.HandleControlMessage!"); break; } } //Internal message receiver class, to handle messages addressed to UnityMessager itself, not being control messages private class MessageReceiver : IMessageReceiver { public void ReceiveMessage(ref UnityMessager.Message msg) { switch (msg.MessageId) { case 3: //UMM_FINISH_DELIVERING_MESSAGES = 3, Send to mark the last message to be delivered (THIS ONE). UnityMessager.Instance._controlQueue.OnFinishDeliveringMessages(); break; case 4: //UMM_REGISTER_NEW_COMPONENT = 4 UnityMessager.Instance.RegisterComponentType(msg.ReadNextParamAndAdvance<int>(), msg.ReadNextParamAsStringAndAdvance()); break; default: Debug.LogError("[UnityMessager] Unknow message id received by UnityMessager.ReceiveMessage!"); break; } } } private struct ParamInfo { //Parameter queue id, -1 if it represents that there is no more parameters to be read for a given Message. public int QueueId { get; private set; } //Array length if the parameter is an array, -1 if it is a single value. public int ArrayLength { get; private set; } public ParamInfo(int queueId, int arrayLength) : this() { QueueId = queueId; ArrayLength = arrayLength; } } private class MessageQueueBase { //Corresponds to the QueueId on the C++ code and to the index of the instance on the UnityMessager._messageQueues array. public int QueueId { get; private set; } //ParamQueue<T> parameter (T) type, null if this is not a ParamQueue instance. public Type QueueType { get; private set; } //Usual contructor public MessageQueueBase(int queueId) { QueueId = queueId; QueueType = null; } //Special constructor used by ParamQueue on its constructing process, check this for more comments public MessageQueueBase(MessageQueueBase instanceToCopy) { QueueId = instanceToCopy.QueueId; QueueType = instanceToCopy.QueueType; _firstArrayBase = instanceToCopy._firstArrayBase; _currentArrayBase = instanceToCopy._currentArrayBase; _currentArrayPos = instanceToCopy._currentArrayPos; } //Sets the id of the first array for this queue. Having this info we can reset the queue to its first id after delivering all the messages public void SetFirstArray(int arrayId) { _firstArrayBase = UnityAdapter.Instance.GetSharedArray(arrayId); _currentArrayBase = _firstArrayBase; QueueType = _firstArrayBase.GetType().GetElementType(); } //Just updates the current array id on this base class method. Derived classes should update their array references also. public virtual void SetCurrentArray(int arrayId) { _currentArrayBase = UnityAdapter.Instance.GetSharedArray(arrayId); _currentArrayPos = 0; } //Resets the Message queue so it starts from its beginning at the next Message delivering process public virtual void Reset() { _currentArrayBase = _firstArrayBase; _currentArrayPos = 0; } //Advance the desired number of items on this queue without actually reading the held values. //Useful for when the message receiver has returned without reading all the method parameters. public void AdvanceToPos(int nOfItemsToSkip) { _currentArrayPos += nOfItemsToSkip; } //Read the next value on the queue as a single param value public object ReadNextAsObject() { return _currentArrayBase.GetValue(_currentArrayPos++); } //Read the next value on the queue as an array value public Array ReadNextAsArrayBase(int length) { var array = Array.CreateInstance(QueueType, length); Array.Copy(_currentArrayBase, _currentArrayPos, array, 0, length); _currentArrayPos += length; return array; } protected int _currentArrayPos = 0; protected Array _firstArrayBase = null; protected Array _currentArrayBase = null; } private abstract class MessageQueue<T>: MessageQueueBase { public MessageQueue(int queueId, int firstArrayId) : base(queueId) { SetFirstArray(firstArrayId); _firstArray = _currentArray = _firstArrayBase as T[]; } //complements the base class version by actually keeping references to the first and current queue arrays public MessageQueue(MessageQueueBase baseInst) : base(baseInst) { _firstArray = _firstArrayBase as T[]; _currentArray = _firstArrayBase == _currentArrayBase ? _firstArray : _currentArrayBase as T[]; } //complements the base class version by actually updating the current array reference public override void SetCurrentArray(int arrayId) { base.SetCurrentArray(arrayId); _currentArray = _currentArrayBase as T[]; } //complements the base class version by actually updating the current array reference public override void Reset() { base.Reset(); _currentArray = _firstArray; } protected T[] _firstArray = null; protected T[] _currentArray = null; } private class ControlQueue: MessageQueue<int> { public ControlQueue(int firstArrayid): base(UnityMessager._controlQueueId, firstArrayid) { CurrentParamInfo = new ParamInfo(-1, 0); } public bool HasMessagesToBeDelivered { get { return _firstArray[0] != _emptyCode; } } //This includes the current parameter, for which info is already read to the CurrentParamInfo property public int NumberOfParamsBeforeNextMessage { get; private set; } //This advances the control queue over the next message, creating the Message instance to be handled and preparing for //reading the parameters (actually the first parameter info is already read here by default). public void ReadNextMessageToUnityMessagerInternalInstance() { Assert.IsTrue(NumberOfParamsBeforeNextMessage == 0); DeliverControlMessagesIfAny(); //very important since queue arrays may be changed by these messages int receiverId = _currentArray[_currentArrayPos + 0]; int messageId = _currentArray[_currentArrayPos + 1]; NumberOfParamsBeforeNextMessage = _currentArray[_currentArrayPos + 2]; int componentId = -1; if (NumberOfParamsBeforeNextMessage >= 0) //normal C# object receiver _currentArrayPos += 3; else { //A negative number of parameters indicates this message is addressed to a component from a game object receiver //observe control messages are an exception to this rule, we know they are control messages because receiverId == 0 componentId = _currentArray[_currentArrayPos + 3]; _currentArrayPos += 4; NumberOfParamsBeforeNextMessage = - NumberOfParamsBeforeNextMessage - 1; } ReadCurrentParam(); Message.FillUnityMessagerInternalMessageInstance(receiverId, componentId, messageId, NumberOfParamsBeforeNextMessage); } //The current parameter info is actually considered to be the "next parameter info" by the Message struct public ParamInfo CurrentParamInfo { get; private set; } public void AdvanceToNextParam() { --NumberOfParamsBeforeNextMessage; ReadCurrentParam(); } //So HasMessagesToBeDelivered returns false and ends the message delivering loop public void OnFinishDeliveringMessages() { _firstArray[0] = _emptyCode; } //Reads the current parameter info to the CurrentParamInfo property private void ReadCurrentParam() { if (NumberOfParamsBeforeNextMessage <= 0) { //no more parameters to read CurrentParamInfo = new ParamInfo(-1, 0); return; } DeliverControlMessagesIfAny(); //very important since queue arrays may be changed by these messages Assert.IsTrue(_currentArray[_currentArrayPos] != 0); if (_currentArray[_currentArrayPos] > 0) //is a single value parameter { CurrentParamInfo = new ParamInfo(_currentArray[_currentArrayPos], -1); ++_currentArrayPos; } else // is an array parameter (queue id set as negative as a mark it is an array param, so size is at the next position) { CurrentParamInfo = new ParamInfo(- _currentArray[_currentArrayPos], _currentArray[_currentArrayPos + 1]); _currentArrayPos += 2; } } //Check if the next item on the control queue is a control message and deliver it if that is the case //more than one control message may come in sequence before the next non control message or the next parameter private void DeliverControlMessagesIfAny() { //Control messages are marked by having 0 as receiverId (UnityMessager itself as receiver) and by //having the number of parameters set as negative. while (_currentArray[_currentArrayPos] == 0 && _currentArray[_currentArrayPos + 2] < 0) { int msgId = _currentArray[_currentArrayPos + 1]; int nOfParams = -_currentArray[_currentArrayPos + 2]; int firstIdx = _currentArrayPos + 3; _currentArrayPos += (3 + nOfParams); //only integer parameters are supported on control messages, all passed directly on the control queue UnityMessager.Instance.HandleControlMessage(msgId, new ArrayParam<int>(_currentArray, firstIdx, nOfParams)); } } //code to mark all the messages were delivered, UM_EMPTY_CONTROL_QUEUE_CODE is the corresponding constant at C++ private const int _emptyCode = -123456; } private class ParamQueue<T> : MessageQueue<T> { //Singleton access point. public static ParamQueue<T> Instance { get; private set; } //Creates the singleton instance based on the base instance, which exists only for holding first and current id //values and also the current position while real ParamQueue was not instanced by the generic parameter reader methods. public static void CreateInstance(MessageQueueBase baseInst) { Assert.IsTrue(Instance == null, "[UnityMessager] More than one ParamQueue instance being created for a same type!"); Instance = new ParamQueue<T>(baseInst); } //Read the next value on the queue as a single param value public T ReadNext() { return _currentArray[_currentArrayPos++]; } //Read the next value on the queue as an array value public ArrayParam<T> ReadNextAsArray(int length) { _currentArrayPos += length; return new ArrayParam<T>(_currentArray, _currentArrayPos - length, length); } //Read the next value on the queue as an string. ONLY VALID FOR THE Byte ParamQueue!!! public string ReadNextAsString(int length) { _currentArrayPos += length; return System.Text.ASCIIEncoding.ASCII.GetString(_currentArray as byte[], _currentArrayPos - length, length); } private ParamQueue(MessageQueueBase baseInst) : base(baseInst) {} } #if (UNITY_WEBGL || UNITY_IOS) && !(UNITY_EDITOR) const string DLL_NAME = "__Internal"; #elif UNITY_ANDROID && !UNITY_EDITOR const string DLL_NAME = "unityforcpp"; #else const string DLL_NAME = "UnityForCpp"; #endif //Expose C++ DLL methods related to the UnityMessager C++ code, check comments on that for more details on these methods private class UnityMessagerDLL { [DllImport(DLL_NAME)] public static extern int UM_InitUnityMessagerAndGetControlQueueId(int maxNOfReceiverIds, int maxQueueArraysSizeInBytes); [DllImport(DLL_NAME)] public static extern void UM_OnStartMessageDelivering(); [DllImport(DLL_NAME)] public static extern void UM_ReleasePossibleQueueArrays(); [DllImport(DLL_NAME)] public static extern void UM_OnDestroy(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Baseline; using Baseline.Dates; using LamarCodeGeneration; using Marten.Exceptions; using Marten.Linq; using Marten.Linq.Includes; using Marten.Linq.Parsing; using Marten.Util; using Npgsql; namespace Marten.Internal.CompiledQueries { internal class QueryCompiler { internal static readonly IList<IParameterFinder> Finders = new List<IParameterFinder>{new EnumParameterFinder()}; private static void forType<T>(Func<int, T[]> uniqueValues) { var finder = new SimpleParameterFinder<T>(uniqueValues); Finders.Add(finder); } static QueryCompiler() { forType(count => { var values = new string[count]; for (int i = 0; i < values.Length; i++) { values[i] = Guid.NewGuid().ToString(); } return values; }); forType(count => { var values = new Guid[count]; for (int i = 0; i < values.Length; i++) { values[i] = Guid.NewGuid(); } return values; }); forType(count => { var value = -100000; var values = new int[count]; for (int i = 0; i < values.Length; i++) { values[i] = value--; } return values; }); forType(count => { var value = -200000L; var values = new long[count]; for (int i = 0; i < values.Length; i++) { values[i] = value--; } return values; }); forType(count => { var value = -300000L; var values = new float[count]; for (int i = 0; i < values.Length; i++) { values[i] = value--; } return values; }); forType(count => { var value = -300000L; var values = new decimal[count]; for (int i = 0; i < values.Length; i++) { values[i] = value--; } return values; }); forType(count => { var value = new DateTime(1600, 1, 1); var values = new DateTime[count]; for (int i = 0; i < values.Length; i++) { values[i] = value.AddDays(-1); } return values; }); forType(count => { var value = new DateTimeOffset(1600, 1, 1, 0, 0, 0, 0.Seconds()); var values = new DateTimeOffset[count]; for (int i = 0; i < values.Length; i++) { values[i] = value.AddDays(-1); } return values; }); } public static CompiledQueryPlan BuildPlan(IMartenSession session, Type queryType, StoreOptions storeOptions) { var querySignature = queryType.FindInterfaceThatCloses(typeof(ICompiledQuery<,>)); if (querySignature == null) throw new ArgumentOutOfRangeException(nameof(queryType), $"Cannot derive query type for {queryType.FullNameInCode()}"); var builder = typeof(CompiledQueryPlanBuilder<,>).CloseAndBuildAs<ICompiledQueryPlanBuilder>( querySignature.GetGenericArguments()); return builder.BuildPlan(session, queryType, storeOptions); } public class CompiledQueryPlanBuilder<TDoc, TOut>: ICompiledQueryPlanBuilder { public CompiledQueryPlan BuildPlan(IMartenSession session, Type queryType, StoreOptions storeOptions) { object query; try { query = Activator.CreateInstance(queryType); } catch (Exception e) { throw new InvalidOperationException( $"Unable to create query type {queryType.FullNameInCode()}. If you receive this message, add a no-arg constructor that can be either public or non-public", e); } return QueryCompiler.BuildPlan<TDoc, TOut>(session, (ICompiledQuery<TDoc, TOut>) query, storeOptions); } } public interface ICompiledQueryPlanBuilder { CompiledQueryPlan BuildPlan(IMartenSession session, Type queryType, StoreOptions storeOptions); } public static CompiledQueryPlan BuildPlan<TDoc, TOut>(IMartenSession session, ICompiledQuery<TDoc, TOut> query, StoreOptions storeOptions) { eliminateStringNulls(query); var plan = new CompiledQueryPlan(query.GetType(), typeof(TOut)); plan.FindMembers(); assertValidityOfQueryType(plan, query.GetType()); // This *could* throw var queryTemplate = plan.CreateQueryTemplate(query); var statistics = plan.GetStatisticsIfAny(query); var builder = BuildDatabaseCommand(session, queryTemplate, statistics, out var command); plan.IncludePlans.AddRange(new List<IIncludePlan>()); var handler = builder.BuildHandler<TOut>(); if (handler is IIncludeQueryHandler<TOut> i) handler = i.Inner; plan.HandlerPrototype = handler; plan.ReadCommand(command, storeOptions); return plan; } internal static LinqHandlerBuilder BuildDatabaseCommand<TDoc, TOut>(IMartenSession session, ICompiledQuery<TDoc, TOut> queryTemplate, QueryStatistics statistics, out NpgsqlCommand command) { Expression expression = queryTemplate.QueryIs(); var invocation = Expression.Invoke(expression, Expression.Parameter(typeof(IMartenQueryable<TDoc>))); var builder = new LinqHandlerBuilder(new MartenLinqQueryProvider(session){Statistics = statistics}, session, invocation, forCompiled: true); command = builder.BuildDatabaseCommand(statistics); return builder; } private static void eliminateStringNulls(object query) { var type = query.GetType(); foreach (var propertyInfo in type.GetProperties().Where(x => x.CanWrite && x.PropertyType == typeof(string))) { var raw = propertyInfo.GetValue(query); if (raw == null) { propertyInfo.SetValue(query, string.Empty); } } foreach (var fieldInfo in type.GetFields().Where(x => x.FieldType == typeof(string))) { var raw = fieldInfo.GetValue(query); if (raw == null) { fieldInfo.SetValue(query, string.Empty); } } } private static void assertValidityOfQueryType(CompiledQueryPlan plan, Type type) { if (plan.InvalidMembers.Any()) { var members = plan.InvalidMembers.Select(x => $"{x.GetRawMemberType().NameInCode()} {x.Name}") .Join(", "); var message = $"Members {members} cannot be used as parameters to a compiled query"; throw new InvalidCompiledQueryException(message); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Data/AssetDigestEntry.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Data { /// <summary>Holder for reflection information generated from POGOProtos/Data/AssetDigestEntry.proto</summary> public static partial class AssetDigestEntryReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Data/AssetDigestEntry.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AssetDigestEntryReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiZQT0dPUHJvdG9zL0RhdGEvQXNzZXREaWdlc3RFbnRyeS5wcm90bxIPUE9H", "T1Byb3Rvcy5EYXRhIncKEEFzc2V0RGlnZXN0RW50cnkSEAoIYXNzZXRfaWQY", "ASABKAkSEwoLYnVuZGxlX25hbWUYAiABKAkSDwoHdmVyc2lvbhgDIAEoAxIQ", "CghjaGVja3N1bRgEIAEoBxIMCgRzaXplGAUgASgFEgsKA2tleRgGIAEoDGIG", "cHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.AssetDigestEntry), global::POGOProtos.Data.AssetDigestEntry.Parser, new[]{ "AssetId", "BundleName", "Version", "Checksum", "Size", "Key" }, null, null, null) })); } #endregion } #region Messages public sealed partial class AssetDigestEntry : pb::IMessage<AssetDigestEntry> { private static readonly pb::MessageParser<AssetDigestEntry> _parser = new pb::MessageParser<AssetDigestEntry>(() => new AssetDigestEntry()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AssetDigestEntry> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Data.AssetDigestEntryReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AssetDigestEntry() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AssetDigestEntry(AssetDigestEntry other) : this() { assetId_ = other.assetId_; bundleName_ = other.bundleName_; version_ = other.version_; checksum_ = other.checksum_; size_ = other.size_; key_ = other.key_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AssetDigestEntry Clone() { return new AssetDigestEntry(this); } /// <summary>Field number for the "asset_id" field.</summary> public const int AssetIdFieldNumber = 1; private string assetId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string AssetId { get { return assetId_; } set { assetId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "bundle_name" field.</summary> public const int BundleNameFieldNumber = 2; private string bundleName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BundleName { get { return bundleName_; } set { bundleName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "version" field.</summary> public const int VersionFieldNumber = 3; private long version_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long Version { get { return version_; } set { version_ = value; } } /// <summary>Field number for the "checksum" field.</summary> public const int ChecksumFieldNumber = 4; private uint checksum_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint Checksum { get { return checksum_; } set { checksum_ = value; } } /// <summary>Field number for the "size" field.</summary> public const int SizeFieldNumber = 5; private int size_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Size { get { return size_; } set { size_ = value; } } /// <summary>Field number for the "key" field.</summary> public const int KeyFieldNumber = 6; private pb::ByteString key_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Key { get { return key_; } set { key_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AssetDigestEntry); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AssetDigestEntry other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (AssetId != other.AssetId) return false; if (BundleName != other.BundleName) return false; if (Version != other.Version) return false; if (Checksum != other.Checksum) return false; if (Size != other.Size) return false; if (Key != other.Key) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (AssetId.Length != 0) hash ^= AssetId.GetHashCode(); if (BundleName.Length != 0) hash ^= BundleName.GetHashCode(); if (Version != 0L) hash ^= Version.GetHashCode(); if (Checksum != 0) hash ^= Checksum.GetHashCode(); if (Size != 0) hash ^= Size.GetHashCode(); if (Key.Length != 0) hash ^= Key.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (AssetId.Length != 0) { output.WriteRawTag(10); output.WriteString(AssetId); } if (BundleName.Length != 0) { output.WriteRawTag(18); output.WriteString(BundleName); } if (Version != 0L) { output.WriteRawTag(24); output.WriteInt64(Version); } if (Checksum != 0) { output.WriteRawTag(37); output.WriteFixed32(Checksum); } if (Size != 0) { output.WriteRawTag(40); output.WriteInt32(Size); } if (Key.Length != 0) { output.WriteRawTag(50); output.WriteBytes(Key); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (AssetId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(AssetId); } if (BundleName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BundleName); } if (Version != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Version); } if (Checksum != 0) { size += 1 + 4; } if (Size != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Size); } if (Key.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Key); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AssetDigestEntry other) { if (other == null) { return; } if (other.AssetId.Length != 0) { AssetId = other.AssetId; } if (other.BundleName.Length != 0) { BundleName = other.BundleName; } if (other.Version != 0L) { Version = other.Version; } if (other.Checksum != 0) { Checksum = other.Checksum; } if (other.Size != 0) { Size = other.Size; } if (other.Key.Length != 0) { Key = other.Key; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { AssetId = input.ReadString(); break; } case 18: { BundleName = input.ReadString(); break; } case 24: { Version = input.ReadInt64(); break; } case 37: { Checksum = input.ReadFixed32(); break; } case 40: { Size = input.ReadInt32(); break; } case 50: { Key = input.ReadBytes(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Linq; using NetGore.Extensions; using NUnit.Framework; using SFML.Graphics; namespace NetGore.Tests.NetGore { [TestFixture] public class Vector4Tests { #region Unit tests [Test] public void AbsTest() { for (var x = -10; x < 10; x++) { for (var y = -10; y < 10; y++) { for (var z = -10; z < 10; z++) { for (var w = -10; w < 10; w++) { var v = new Vector4(x, y, z, w); v = v.Abs(); Assert.LessOrEqual(0, v.X); Assert.LessOrEqual(0, v.Y); Assert.LessOrEqual(0, v.Z); } } } } } [Test] public void CeilingTest() { const int max = 1000; var r = new Random(987); for (var i = 0; i < 30; i++) { var v = new Vector4(r.NextFloat() * max, r.NextFloat() * max, r.NextFloat() * max, r.NextFloat() * max); var c = v.Ceiling(); Assert.AreEqual(Math.Ceiling(v.X), c.X); Assert.AreEqual(Math.Ceiling(v.Y), c.Y); Assert.AreEqual(Math.Ceiling(v.Z), c.Z); Assert.AreEqual(Math.Ceiling(v.W), c.W); } } [Test] public void FloorTest() { const int max = 1000; var r = new Random(102); for (var i = 0; i < 30; i++) { var v = new Vector4(r.NextFloat() * max, r.NextFloat() * max, r.NextFloat() * max, r.NextFloat() * max); var c = v.Floor(); Assert.AreEqual(Math.Floor(v.X), c.X); Assert.AreEqual(Math.Floor(v.Y), c.Y); Assert.AreEqual(Math.Floor(v.Z), c.Z); Assert.AreEqual(Math.Floor(v.W), c.W); } } [Test] public void IsGreaterOrEqualTest() { for (var x1 = -1; x1 < 1; x1++) { for (var y1 = -1; y1 < 1; y1++) { for (var z1 = -1; z1 < 1; z1++) { for (var w1 = -2; w1 < 2; w1++) { for (var x2 = -2; x2 < 2; x2++) { for (var y2 = -2; y2 < 2; y2++) { for (var z2 = -2; z2 < 2; z2++) { for (var w2 = -3; w2 < 3; w2++) { var v1 = new Vector4(x1, y1, z1, w1); var v2 = new Vector4(x2, y2, z2, w2); var b1 = (v1.X >= v2.X && v1.Y >= v2.Y && v1.Z >= v2.Z && v1.W >= v2.W); Assert.AreEqual(b1, v1.IsGreaterOrEqual(v2)); var b2 = (v2.X >= v1.X && v2.Y >= v1.Y && v2.Z >= v1.Z && v2.W >= v1.W); Assert.AreEqual(b2, v2.IsGreaterOrEqual(v1)); } } } } } } } } } [Test] public void IsGreaterThanTest() { for (var x1 = -1; x1 < 1; x1++) { for (var y1 = -1; y1 < 1; y1++) { for (var z1 = -1; z1 < 1; z1++) { for (var w1 = -2; w1 < 2; w1++) { for (var x2 = -2; x2 < 2; x2++) { for (var y2 = -2; y2 < 2; y2++) { for (var z2 = -2; z2 < 2; z2++) { for (var w2 = -3; w2 < 3; w2++) { var v1 = new Vector4(x1, y1, z1, w1); var v2 = new Vector4(x2, y2, z2, w2); var b1 = (v1.X > v2.X && v1.Y > v2.Y && v1.Z > v2.Z && v1.W > v2.W); Assert.AreEqual(b1, v1.IsGreaterThan(v2)); var b2 = (v2.X > v1.X && v2.Y > v1.Y && v2.Z > v1.Z && v2.W > v1.W); Assert.AreEqual(b2, v2.IsGreaterThan(v1)); } } } } } } } } } [Test] public void IsLessOrEqualTest() { for (var x1 = -1; x1 < 1; x1++) { for (var y1 = -1; y1 < 1; y1++) { for (var z1 = -1; z1 < 1; z1++) { for (var w1 = -2; w1 < 2; w1++) { for (var x2 = -2; x2 < 2; x2++) { for (var y2 = -2; y2 < 2; y2++) { for (var z2 = -2; z2 < 2; z2++) { for (var w2 = -3; w2 < 3; w2++) { var v1 = new Vector4(x1, y1, z1, w1); var v2 = new Vector4(x2, y2, z2, w2); var b1 = (v1.X <= v2.X && v1.Y <= v2.Y && v1.Z <= v2.Z && v1.W <= v2.W); Assert.AreEqual(b1, v1.IsLessOrEqual(v2)); var b2 = (v2.X <= v1.X && v2.Y <= v1.Y && v2.Z <= v1.Z && v2.W <= v1.W); Assert.AreEqual(b2, v2.IsLessOrEqual(v1)); } } } } } } } } } [Test] public void IsLessThanTest() { for (var x1 = -1; x1 < 1; x1++) { for (var y1 = -1; y1 < 1; y1++) { for (var z1 = -1; z1 < 1; z1++) { for (var w1 = -2; w1 < 2; w1++) { for (var x2 = -2; x2 < 2; x2++) { for (var y2 = -2; y2 < 2; y2++) { for (var z2 = -2; z2 < 2; z2++) { for (var w2 = -3; w2 < 3; w2++) { var v1 = new Vector4(x1, y1, z1, w1); var v2 = new Vector4(x2, y2, z2, w2); var b1 = (v1.X < v2.X && v1.Y < v2.Y && v1.Z < v2.Z && v1.W < v2.W); Assert.AreEqual(b1, v1.IsLessThan(v2)); var b2 = (v2.X < v1.X && v2.Y < v1.Y && v2.Z < v1.Z && v2.W < v1.W); Assert.AreEqual(b2, v2.IsLessThan(v1)); } } } } } } } } } [Test] public void RoundTest() { const int max = 1000; var r = new Random(578); for (var i = 0; i < 30; i++) { var v = new Vector4(r.NextFloat() * max, r.NextFloat() * max, r.NextFloat() * max, r.NextFloat() * max); var c = v.Round(); Assert.AreEqual(Math.Round(v.X), c.X); Assert.AreEqual(Math.Round(v.Y), c.Y); Assert.AreEqual(Math.Round(v.Z), c.Z); Assert.AreEqual(Math.Round(v.W), c.W); } } [Test] public void SumTest() { for (var x = -10; x < 10; x++) { for (var y = -10; y < 10; y++) { for (var z = -10; z < 10; z++) { for (var w = -10; w < 10; w++) { var v = new Vector4(x, y, z, w); Assert.AreEqual(x + y + z + w, v.Sum()); } } } } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using TheFactory.Datastore.Helpers; using System.Collections; using System.Text; using System.Threading.Tasks; using System.Threading; using Splat; using TheFactory.FileSystem; namespace TheFactory.Datastore { public class Options { public bool CreateIfMissing { get; set; } public bool DeleteOnClose { get; set; } public bool VerifyChecksums { get; set; } public int MaxMemoryTabletSize { get; set; } public TabletReaderOptions ReaderOptions { get; set; } public TabletWriterOptions WriterOptions { get; set; } public Options() { CreateIfMissing = true; DeleteOnClose = false; VerifyChecksums = false; MaxMemoryTabletSize = 1024 * 1024 * 4; /* 4MB default */ ReaderOptions = new TabletReaderOptions(); WriterOptions = new TabletWriterOptions(); } public override string ToString() { return String.Format( "CreateIfMissing = {0}\n" + "DeleteOnClose = {1}\n" + "VerifyChecksums = {2}\n" + "MaxMemoryTabletSize = {3}\n" + "ReaderOptions:\n{4}\n" + "WriterOptions:\n{5}\n", CreateIfMissing, DeleteOnClose, VerifyChecksums, MaxMemoryTabletSize, ReaderOptions.ToString(), WriterOptions.ToString()); } } public class KeyValueChangedEventArgs: EventArgs { public IKeyValuePair Pair { get; private set; } public KeyValueChangedEventArgs(IKeyValuePair kv) { Pair = kv; } } public class Database: IDatabase, IEnableLogger { private Options opts; private IFileSystem fs; // Database provides a unified key-value view across three things: // a mutable in-memory tablet (writes go here) // an immutable in-memory tablet (temporary; while being written to disk) // a collection of immutable file tablets // // The immutable file tablets are treated like the 0th level of leveldb: // they can contain overlapping keys // in case of duplicate keys, the most recently written tablet wins // // Changes to any of these references are protected with tabLock. private MemoryTablet mem = null; private MemoryTablet mem2 = null; private List<ITablet> tablets = new List<ITablet>(); private ManualResetEventSlim canCompact = new ManualResetEventSlim(true); // memLock protects access to the mutable memory tablet. tabLock protects // access to the tablets list. private object memLock = new object(); private object tabLock = new object(); private FileManager fileManager; private TransactionLogWriter writeLog; IDisposable fsLock; public event EventHandler<KeyValueChangedEventArgs> KeyValueChangedEvent; internal Database(string path, Options opts) { this.fileManager = new FileManager(path); this.opts = opts; this.fs = Locator.Current.GetService<IFileSystem>(); } public static IDatabase Open(string path) { return Open(path, new Options()); } public static IDatabase Open(string path, Options opts) { var db = new Database(path, opts); db.Open(); return db; } private void Open() { if (!fs.Exists(fileManager.Dir)) { if (!opts.CreateIfMissing) { throw new InvalidOperationException(String.Format("Directory `{0}` must exist", fileManager.Dir)); } fs.CreateDirectory(fileManager.Dir); } fsLock = fs.FileLock(fileManager.GetLockFile()); LoadMemoryTablets(); var tabletStack = fileManager.GetTabletStack(); if (fs.Exists(tabletStack)) { using (var file = fs.GetStream(tabletStack, FileMode.Open, FileAccess.Read)) { var reader = new StreamReader(file); while (!reader.EndOfStream) { var filename = fileManager.DbFilename(reader.ReadLine()); tablets.Add(new FileTablet(filename, opts.ReaderOptions)); } } } } void LoadMemoryTablets() { var transLog = fileManager.GetTransactionLog(); var immTransLog = fileManager.GetImmutableTransactionLog(); mem = new MemoryTablet(); if (fs.Exists(transLog)) { ReplayTransactions(mem, transLog); } // If we crashed while freezing a memory tablet, freeze it again. Block // database loading until it completes. if (fs.Exists(immTransLog)) { var tab = new MemoryTablet(); ReplayTransactions(tab, immTransLog); // Block until the immutable memory tablet has been frozen. Compact(tab); fs.Remove(immTransLog); } writeLog = new TransactionLogWriter(fs.GetStream(transLog, FileMode.Append, FileAccess.Write, FileShare.None)); } void ReplayTransactions(MemoryTablet tablet, string path) { using (var log = new TransactionLogReader(fs.GetStream(path, FileMode.Open, FileAccess.Read))) { foreach (var transaction in log.Transactions()) { tablet.Apply(new Batch(transaction)); } } } public void Close() { if (writeLog != null) { writeLog.Dispose(); writeLog = null; } // Wait until any compaction is finished. canCompact.Wait(); if (fsLock != null) { fsLock.Dispose(); fsLock = null; } if (opts.DeleteOnClose) { fs.RemoveDirectory(fileManager.Dir); } } public void Dispose() { Close(); } private bool EndOfBlocks(Stream stream) { var peek = stream.ReadInt(); stream.Seek(-4, SeekOrigin.Current); // The meta index block signals the end of blocks. return peek == Constants.MetaIndexMagic; } public void PushTablet(string filename) { lock (tabLock) { tablets.Add(new FileTablet(filename, opts.ReaderOptions)); WriteLevel0List(); } } void WriteLevel0List() { // tabLock must be held to call WriteLevel0List using (var stream = fs.GetStream(fileManager.GetTabletStack(), FileMode.Create, FileAccess.Write, FileShare.None)) { var writer = new StreamWriter(stream); foreach (var t in tablets) { writer.WriteLine(Path.GetFileName(t.Filename)); } writer.Dispose(); } } void MaybeCompactMem() { // This method locks the tablets briefly to determine whether mem is due for compaction. // // If mem is not due for compaction, it returns after that. // If it is due and no compaction is running, it fires off a background compaction task. // If a compaction is running, it blocks until that completes and checks again. // // Use the "canCompact" ManualResetEventSlim as a condition variable to accomplish the above. Func<bool> memFull = () => (mem.ApproxSize > opts.MaxMemoryTabletSize); bool shouldCompact; lock (tabLock) { shouldCompact = memFull(); } if (shouldCompact) { canCompact.Wait(); lock(tabLock) { if (memFull()) { canCompact.Reset(); CompactMem(); } } } } void CompactMem() { var transLog = fileManager.GetTransactionLog(); var immTransLog = fileManager.GetImmutableTransactionLog(); // Move the current writable memory tablet to mem2. lock (tabLock) { mem2 = mem; mem = new MemoryTablet(); writeLog.Dispose(); fs.Move(transLog, immTransLog); writeLog = new TransactionLogWriter(fs.GetStream(transLog, FileMode.Append, FileAccess.Write)); Task.Run(() => { try { Compact(mem2); fs.Remove(immTransLog); mem2 = null; } catch (Exception e) { this.Log().ErrorException("Exception in tablet compaction", e); } finally { // Set canCompact to avoid deadlock, but at this point we'll // try and fail to compact mem2 on every database write. canCompact.Set(); } }); } } void Compact(MemoryTablet tab) { var tabfile = fileManager.DbFilename(String.Format("{0}.tab", System.Guid.NewGuid().ToString())); var writer = new TabletWriter(); using (var stream = fs.GetStream(tabfile, FileMode.Create, FileAccess.Write)) using (var output = new BinaryWriter(stream)) { writer.WriteTablet(output, tab.Find(Slice.Empty), opts.WriterOptions); } PushTablet(tabfile); } ITablet[] CurrentTablets() { // Return all a snapshot of current tablets in order of search priority. var all = new List<ITablet>(tablets.Count + 2); lock(tabLock) { all.Add(mem); if (mem2 != null) { all.Add(mem2); } for (var i = tablets.Count - 1; i >= 0; i--) { all.Add(tablets[i]); } } return all.ToArray(); } public IEnumerable<IKeyValuePair> Find(Slice term) { var searches = CurrentTablets(); var iter = new ParallelEnumerator(searches.Count(), (i) => { return searches[i].Find(term).GetEnumerator(); }); using (iter) { while (iter.MoveNext()) { if (!iter.Current.IsDeleted) { yield return iter.Current; } } } yield break; } public Slice Get(Slice key) { foreach (var p in Find(key)) { if (Slice.Compare(p.Key, key) == 0) { return p.Value.Detach(); } else { break; } } return null; } internal void Apply(Batch batch) { lock (memLock) { writeLog.EmitTransaction(batch.ToSlice()); mem.Apply(batch); MaybeCompactMem(); } if (KeyValueChangedEvent != null) { foreach (var kv in batch.Pairs()) { KeyValueChangedEvent(this, new KeyValueChangedEventArgs(kv)); } } } public void Put(Slice key, Slice val) { var batch = new Batch(); batch.Put(key, val); Apply(batch); } public void Delete(Slice key) { var batch = new Batch(); batch.Delete(key); Apply(batch); } private class ParallelEnumerator: IEnumerator<IKeyValuePair> { SortedSet<QueuePair> queue; List<IEnumerator<IKeyValuePair>> iters; Pair current; public ParallelEnumerator(int n, Func<int, IEnumerator<IKeyValuePair>> func) { queue = new SortedSet<QueuePair>(new PriorityComparer()); iters = new List<IEnumerator<IKeyValuePair>>(n); for (int i = 0; i < n; i++) { var iter = func(i); if (iter.MoveNext()) { queue.Add(new QueuePair(-i, iter.Current)); } iters.Add(iter); } current = new Pair(); } object IEnumerator.Current { get { return current; } } public IKeyValuePair Current { get { return current; } } public bool MoveNext() { if (queue.Count == 0) { current = null; return false; } current = Pop(); while (queue.Count > 0 && current.Key.Equals(queue.Min.kv.Key)) { // skip any items in other iterators that have the same key Pop(); } return true; } private Pair Pop() { var cur = queue.Min; queue.Remove(cur); // set up new references to this item, since we're about to advance its iterator below var ret = new Pair(); ret.Key = cur.kv.Key; ret.Value = cur.kv.Value; ret.IsDeleted = cur.kv.IsDeleted; var iter = iters[-cur.Priority]; if (iter.MoveNext()) { queue.Add(new QueuePair(cur.Priority, iter.Current)); } return ret; } public void Dispose() { foreach (var iter in iters) { iter.Dispose(); } } // from IEnumerator: it's ok not to support this public void Reset() { throw new NotSupportedException(); } private class QueuePair { public int Priority { get; set; } public IKeyValuePair kv { get; set; } public QueuePair(int priority, IKeyValuePair kv) { this.Priority = priority; this.kv = kv; } } private class PriorityComparer : IComparer<QueuePair>, IComparer { public int Compare(Object x, Object y) { return this.Compare((QueuePair)x, (QueuePair)y); } public int Compare(QueuePair x, QueuePair y) { if (ReferenceEquals(x, y)) { return 0; } var cmp = Slice.Compare(x.kv.Key, y.kv.Key); if (cmp == 0) { // Key is the same, the higher priority pair wins return y.Priority - x.Priority; } return cmp; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.ResourceManager.Fluent.Core; namespace Microsoft.Azure.Management.Compute.Fluent { /// <summary> /// Compute resource sku names. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuQ29tcHV0ZVNrdU5hbWU= public partial class ComputeSkuName : ExpandableStringEnum<Microsoft.Azure.Management.Compute.Fluent.ComputeSkuName>, IBeta { /** * Static value Standard_F32s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF32sv2 = Parse("Standard_F32s_v2"); /** * Static value Standard_DS2_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS2v2 = Parse("Standard_DS2_v2"); /** * Static value Standard_H16r for ComputeSkuName. */ public static readonly ComputeSkuName StandardH16r = Parse("Standard_H16r"); /** * Static value Standard_H16m for ComputeSkuName. */ public static readonly ComputeSkuName StandardH16m = Parse("Standard_H16m"); /** * Static value Standard_D1 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD1 = Parse("Standard_D1"); /** * Static value Standard_F16s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF16sv2 = Parse("Standard_F16s_v2"); /** * Static value Standard_DS5_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS5v2Promo = Parse("Standard_DS5_v2_Promo"); /** * Static value Standard_E4s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE4sv3 = Parse("Standard_E4s_v3"); /** * Static value Standard_D1_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD1v2 = Parse("Standard_D1_v2"); /** * Static value Standard_DS12_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS12v2Promo = Parse("Standard_DS12_v2_Promo"); /** * Static value Standard_D64s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD64sv3 = Parse("Standard_D64s_v3"); /** * Static value Standard_M128-32ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardM128_32ms = Parse("Standard_M128-32ms"); /** * Static value Standard_D4 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD4 = Parse("Standard_D4"); /** * Static value Standard_D3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD3 = Parse("Standard_D3"); /** * Static value Standard_D2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD2 = Parse("Standard_D2"); /** * Static value Standard_M128s for ComputeSkuName. */ public static readonly ComputeSkuName StandardM128s = Parse("Standard_M128s"); /** * Static value Standard_D4s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD4sv3 = Parse("Standard_D4s_v3"); /** * Static value Standard_F2s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF2sv2 = Parse("Standard_F2s_v2"); /** * Static value Standard_F1s for ComputeSkuName. */ public static readonly ComputeSkuName StandardF1s = Parse("Standard_F1s"); /** * Static value Standard_A8m_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA8mv2 = Parse("Standard_A8m_v2"); /** * Static value Standard_NC24 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNC24 = Parse("Standard_NC24"); /** * Static value Standard_B1s for ComputeSkuName. */ public static readonly ComputeSkuName StandardB1s = Parse("Standard_B1s"); /** * Static value Standard_E2s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE2sv3 = Parse("Standard_E2s_v3"); /** * Static value Standard_D8s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD8sv3 = Parse("Standard_D8s_v3"); /** * Static value Standard_DS14_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS14v2 = Parse("Standard_DS14_v2"); /** * Static value Standard_H16mr for ComputeSkuName. */ public static readonly ComputeSkuName StandardH16mr = Parse("Standard_H16mr"); /** * Static value Standard_DS13_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS13v2Promo = Parse("Standard_DS13_v2_Promo"); /** * Static value Standard_ND12s for ComputeSkuName. */ public static readonly ComputeSkuName StandardND12s = Parse("Standard_ND12s"); /** * Static value Standard_DS5_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS5v2 = Parse("Standard_DS5_v2"); /** * Static value Standard_D15_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD15v2 = Parse("Standard_D15_v2"); /** * Static value Standard_ND24s for ComputeSkuName. */ public static readonly ComputeSkuName StandardND24s = Parse("Standard_ND24s"); /** * Static value Standard_F4s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF4sv2 = Parse("Standard_F4s_v2"); /** * Static value Standard_GS5-16 for ComputeSkuName. */ public static readonly ComputeSkuName StandardGS5_16 = Parse("Standard_GS5-16"); /** * Static value Standard_F2s for ComputeSkuName. */ public static readonly ComputeSkuName StandardF2s = Parse("Standard_F2s"); /** * Static value Standard_B2ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardB2ms = Parse("Standard_B2ms"); /** * Static value Standard_B2s for ComputeSkuName. */ public static readonly ComputeSkuName StandardB2s = Parse("Standard_B2s"); /** * Static value Standard_E2_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE2v3 = Parse("Standard_E2_v3"); /** * Static value Standard_A4_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA4v2 = Parse("Standard_A4_v2"); /** * Static value Standard_DS4_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS4v2 = Parse("Standard_DS4_v2"); /** * Static value Standard_F8s for ComputeSkuName. */ public static readonly ComputeSkuName StandardF8s = Parse("Standard_F8s"); /** * Static value Standard_D12_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD12v2 = Parse("Standard_D12_v2"); /** * Static value Standard_A2m_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA2mv2 = Parse("Standard_A2m_v2"); /** * Static value Standard_DS13-4_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS13_4v2 = Parse("Standard_DS13-4_v2"); /** * Static value Standard_M128ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardM128ms = Parse("Standard_M128ms"); /** * Static value Standard_DS15_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS15v2 = Parse("Standard_DS15_v2"); /** * Static value Standard_F2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF2 = Parse("Standard_F2"); /** * Static value Standard_F1 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF1 = Parse("Standard_F1"); /** * Static value Standard_DS14_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS14v2Promo = Parse("Standard_DS14_v2_Promo"); /** * Static value Standard_GS4-8 for ComputeSkuName. */ public static readonly ComputeSkuName StandardGS4_8 = Parse("Standard_GS4-8"); /** * Static value Standard_E32-8s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE32_8sv3 = Parse("Standard_E32-8s_v3"); /** * Static value Standard_F8 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF8 = Parse("Standard_F8"); /** * Static value Standard_F16 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF16 = Parse("Standard_F16"); /** * Static value Standard_F4 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF4 = Parse("Standard_F4"); /** * Static value Standard_GS4-4 for ComputeSkuName. */ public static readonly ComputeSkuName StandardGS4_4 = Parse("Standard_GS4-4"); /** * Static value Standard_F72s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF72sv2 = Parse("Standard_F72s_v2"); /** * Static value Standard_D16s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD16sv3 = Parse("Standard_D16s_v3"); /** * Static value Standard_D2_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardD2v2Promo = Parse("Standard_D2_v2_Promo"); /** * Static value Standard_A1_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA1v2 = Parse("Standard_A1_v2"); /** * Static value Standard_NC6 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNC6 = Parse("Standard_NC6"); /** * Static value Standard_E16s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE16sv3 = Parse("Standard_E16s_v3"); /** * Static value Standard_A10 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA10 = Parse("Standard_A10"); /** * Static value Standard_A4m_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA4mv2 = Parse("Standard_A4m_v2"); /** * Static value Standard_A11 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA11 = Parse("Standard_A11"); /** * Static value Standard_DS12_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS12v2 = Parse("Standard_DS12_v2"); /** * Static value Standard_E16_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE16v3 = Parse("Standard_E16_v3"); /** * Static value Standard_D4_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD4v3 = Parse("Standard_D4_v3"); /** * Static value Standard_G4 for ComputeSkuName. */ public static readonly ComputeSkuName StandardG4 = Parse("Standard_G4"); /** * Static value Standard_G3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardG3 = Parse("Standard_G3"); /** * Static value Standard_NC24s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNC24sv2 = Parse("Standard_NC24s_v2"); /** * Static value Standard_G2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardG2 = Parse("Standard_G2"); /** * Static value Classic for ComputeSkuName. */ public static readonly ComputeSkuName Classic = Parse("Classic"); /** * Static value Standard_D4_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD4v2 = Parse("Standard_D4_v2"); /** * Static value Standard_G1 for ComputeSkuName. */ public static readonly ComputeSkuName StandardG1 = Parse("Standard_G1"); /** * Static value Standard_E64_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE64v3 = Parse("Standard_E64_v3"); /** * Static value Standard_DS3_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS3v2Promo = Parse("Standard_DS3_v2_Promo"); /** * Static value Standard_L4s for ComputeSkuName. */ public static readonly ComputeSkuName StandardL4s = Parse("Standard_L4s"); /** * Static value Standard_E8_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE8v3 = Parse("Standard_E8_v3"); /** * Static value Standard_G5 for ComputeSkuName. */ public static readonly ComputeSkuName StandardG5 = Parse("Standard_G5"); /** * Static value Standard_F8s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF8sv2 = Parse("Standard_F8s_v2"); /** * Static value Standard_DS11_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS11v2Promo = Parse("Standard_DS11_v2_Promo"); /** * Static value Standard_D2s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD2sv3 = Parse("Standard_D2s_v3"); /** * Static value Standard_D13_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardD13v2Promo = Parse("Standard_D13_v2_Promo"); /** * Static value Standard_NC12 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNC12 = Parse("Standard_NC12"); /** * Static value Standard_D4_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardD4v2Promo = Parse("Standard_D4_v2_Promo"); /** * Static value Standard_L16s for ComputeSkuName. */ public static readonly ComputeSkuName StandardL16s = Parse("Standard_L16s"); /** * Static value Standard_DS13-2_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS13_2v2 = Parse("Standard_DS13-2_v2"); /** * Static value Standard_DS13_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS13v2 = Parse("Standard_DS13_v2"); /** * Static value Standard_GS5-8 for ComputeSkuName. */ public static readonly ComputeSkuName StandardGS5_8 = Parse("Standard_GS5-8"); /** * Static value Standard_D5_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD5v2 = Parse("Standard_D5_v2"); /** * Static value Standard_NC24r for ComputeSkuName. */ public static readonly ComputeSkuName StandardNC24r = Parse("Standard_NC24r"); /** * Static value Standard_L32s for ComputeSkuName. */ public static readonly ComputeSkuName StandardL32s = Parse("Standard_L32s"); /** * Static value Standard_D14_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD14v2 = Parse("Standard_D14_v2"); /** * Static value Standard_E32_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE32v3 = Parse("Standard_E32_v3"); /** * Static value Standard_ND6s for ComputeSkuName. */ public static readonly ComputeSkuName StandardND6s = Parse("Standard_ND6s"); /** * Static value Standard_H8 for ComputeSkuName. */ public static readonly ComputeSkuName StandardH8 = Parse("Standard_H8"); /** * Static value Basic_A4 for ComputeSkuName. */ public static readonly ComputeSkuName BasicA4 = Parse("Basic_A4"); /** * Static value Standard_DS2_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS2v2Promo = Parse("Standard_DS2_v2_Promo"); /** * Static value Basic_A1 for ComputeSkuName. */ public static readonly ComputeSkuName BasicA1 = Parse("Basic_A1"); /** * Static value Basic_A0 for ComputeSkuName. */ public static readonly ComputeSkuName BasicA0 = Parse("Basic_A0"); /** * Static value Basic_A3 for ComputeSkuName. */ public static readonly ComputeSkuName BasicA3 = Parse("Basic_A3"); /** * Static value Basic_A2 for ComputeSkuName. */ public static readonly ComputeSkuName BasicA2 = Parse("Basic_A2"); /** * Static value Standard_D11_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD11v2 = Parse("Standard_D11_v2"); /** * Static value Standard_DS14-8_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS14_8v2 = Parse("Standard_DS14-8_v2"); /** * Static value Standard_DS1_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS1v2 = Parse("Standard_DS1_v2"); /** * Static value Standard_E64-16s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE64_16sv3 = Parse("Standard_E64-16s_v3"); /** * Static value Standard_D2_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD2v2 = Parse("Standard_D2_v2"); /** * Static value Standard_D2_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD2v3 = Parse("Standard_D2_v3"); /** * Static value Standard_D32_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD32v3 = Parse("Standard_D32_v3"); /** * Static value Standard_D11_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardD11v2Promo = Parse("Standard_D11_v2_Promo"); /** * Static value Standard_F64s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardF64sv2 = Parse("Standard_F64s_v2"); /** * Static value Standard_A6 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA6 = Parse("Standard_A6"); /** * Static value Standard_M128-64ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardM128_64ms = Parse("Standard_M128-64ms"); /** * Static value Standard_A5 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA5 = Parse("Standard_A5"); /** * Static value Standard_A4 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA4 = Parse("Standard_A4"); /** * Static value Standard_A3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA3 = Parse("Standard_A3"); /** * Static value Standard_A2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA2 = Parse("Standard_A2"); /** * Static value Standard_D32s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD32sv3 = Parse("Standard_D32s_v3"); /** * Static value Standard_A1 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA1 = Parse("Standard_A1"); /** * Static value Standard_A0 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA0 = Parse("Standard_A0"); /** * Static value Standard_M64-32ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardM64_32ms = Parse("Standard_M64-32ms"); /** * Static value Standard_A8_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA8v2 = Parse("Standard_A8_v2"); /** * Static value Standard_B4ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardB4ms = Parse("Standard_B4ms"); /** * Static value Standard_GS3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardGS3 = Parse("Standard_GS3"); /** * Static value Standard_GS2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardGS2 = Parse("Standard_GS2"); /** * Static value Standard_GS5 for ComputeSkuName. */ public static readonly ComputeSkuName StandardGS5 = Parse("Standard_GS5"); /** * Static value Standard_GS4 for ComputeSkuName. */ public static readonly ComputeSkuName StandardGS4 = Parse("Standard_GS4"); /** * Static value Standard_B8ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardB8ms = Parse("Standard_B8ms"); /** * Static value Standard_D64_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD64v3 = Parse("Standard_D64_v3"); /** * Static value Standard_A9 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA9 = Parse("Standard_A9"); /** * Static value Standard_A8 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA8 = Parse("Standard_A8"); /** * Static value Standard_GS1 for ComputeSkuName. */ public static readonly ComputeSkuName StandardGS1 = Parse("Standard_GS1"); /** * Static value Standard_A7 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA7 = Parse("Standard_A7"); /** * Static value Standard_E64-32s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE64_32sv3 = Parse("Standard_E64-32s_v3"); /** * Static value Standard_NV12 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNV12 = Parse("Standard_NV12"); /** * Static value Standard_NC6s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNC6sv2 = Parse("Standard_NC6s_v2"); /** * Static value Standard_NC24rs_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNC24rsv2 = Parse("Standard_NC24rs_v2"); /** * Static value Standard_H8m for ComputeSkuName. */ public static readonly ComputeSkuName StandardH8m = Parse("Standard_H8m"); /** * Static value Standard_DS11_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS11v2 = Parse("Standard_DS11_v2"); /** * Static value Premium_LRS for ComputeSkuName. */ public static readonly ComputeSkuName PremiumLRS = Parse("Premium_LRS"); /** * Static value Standard_D3_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD3v2 = Parse("Standard_D3_v2"); /** * Static value Standard_D16_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD16v3 = Parse("Standard_D16_v3"); /** * Static value Standard_F16s for ComputeSkuName. */ public static readonly ComputeSkuName StandardF16s = Parse("Standard_F16s"); /** * Static value Standard_ND24rs for ComputeSkuName. */ public static readonly ComputeSkuName StandardND24rs = Parse("Standard_ND24rs"); /** * Static value Standard_DS13 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS13 = Parse("Standard_DS13"); /** * Static value Standard_NV6 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNV6 = Parse("Standard_NV6"); /** * Static value Standard_DS12 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS12 = Parse("Standard_DS12"); /** * Static value Standard_E8s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE8sv3 = Parse("Standard_E8s_v3"); /** * Static value Standard_DS11 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS11 = Parse("Standard_DS11"); /** * Static value Standard_H16 for ComputeSkuName. */ public static readonly ComputeSkuName StandardH16 = Parse("Standard_H16"); /** * Static value Standard_DS14 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS14 = Parse("Standard_DS14"); /** * Static value Standard_D14 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD14 = Parse("Standard_D14"); /** * Static value Standard_D12_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardD12v2Promo = Parse("Standard_D12_v2_Promo"); /** * Static value Standard_D13 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD13 = Parse("Standard_D13"); /** * Static value Standard_D5_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardD5v2Promo = Parse("Standard_D5_v2_Promo"); /** * Static value Standard_DS14-4_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS14_4v2 = Parse("Standard_DS14-4_v2"); /** * Static value Standard_D12 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD12 = Parse("Standard_D12"); /** * Static value Standard_D11 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD11 = Parse("Standard_D11"); /** * Static value Standard_DS3_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS3v2 = Parse("Standard_DS3_v2"); /** * Static value Standard_D14_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardD14v2Promo = Parse("Standard_D14_v2_Promo"); /** * Static value Standard_D8_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD8v3 = Parse("Standard_D8_v3"); /** * Static value Standard_NV24 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNV24 = Parse("Standard_NV24"); /** * Static value Standard_DS4_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS4v2Promo = Parse("Standard_DS4_v2_Promo"); /** * Static value Standard_D13_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardD13v2 = Parse("Standard_D13_v2"); /** * Static value Standard_M64s for ComputeSkuName. */ public static readonly ComputeSkuName StandardM64s = Parse("Standard_M64s"); /** * Static value Standard_M64ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardM64ms = Parse("Standard_M64ms"); /** * Static value Standard_E32s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE32sv3 = Parse("Standard_E32s_v3"); /** * Static value Standard_M64-16ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardM64_16ms = Parse("Standard_M64-16ms"); /** * Static value Standard_E32-16s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE32_16sv3 = Parse("Standard_E32-16s_v3"); /** * Static value Standard_D3_v2_Promo for ComputeSkuName. */ public static readonly ComputeSkuName StandardD3v2Promo = Parse("Standard_D3_v2_Promo"); /** * Static value Standard_B1ms for ComputeSkuName. */ public static readonly ComputeSkuName StandardB1ms = Parse("Standard_B1ms"); /** * Static value Standard_E64s_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE64sv3 = Parse("Standard_E64s_v3"); /** * Static value Standard_LRS for ComputeSkuName. */ public static readonly ComputeSkuName StandardLRS = Parse("Standard_LRS"); /** * Static value Standard_NC12s_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardNC12sv2 = Parse("Standard_NC12s_v2"); /** * Static value Standard_L8s for ComputeSkuName. */ public static readonly ComputeSkuName StandardL8s = Parse("Standard_L8s"); /** * Static value Standard_E4_v3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardE4v3 = Parse("Standard_E4_v3"); /** * Static value Aligned for ComputeSkuName. */ public static readonly ComputeSkuName Aligned = Parse("Aligned"); /** * Static value Standard_DS2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS2 = Parse("Standard_DS2"); /** * Static value Standard_DS1 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS1 = Parse("Standard_DS1"); /** * Static value Standard_F4s for ComputeSkuName. */ public static readonly ComputeSkuName StandardF4s = Parse("Standard_F4s"); /** * Static value Standard_DS4 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS4 = Parse("Standard_DS4"); /** * Static value Standard_A2_v2 for ComputeSkuName. */ public static readonly ComputeSkuName StandardA2v2 = Parse("Standard_A2_v2"); /** * Static value Standard_DS3 for ComputeSkuName. */ public static readonly ComputeSkuName StandardDS3 = Parse("Standard_DS3"); } }
using System; using System.Fabric; using System.Fabric.Description; using System.Net; using System.Numerics; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Newtonsoft.Json; using NSubstitute; using Orleans; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Hosting.ServiceFabric; using Orleans.ServiceFabric; using Xunit; namespace TestServiceFabric { [TestCategory("ServiceFabric"), TestCategory("Functional")] public class OrleansCommunicationListenerTests { private readonly ICodePackageActivationContext activationContext = Substitute.For<ICodePackageActivationContext>(); private readonly NodeContext nodeContext = new NodeContext( "bobble", new NodeId(BigInteger.One, BigInteger.One), BigInteger.One, "amazing", Dns.GetHostName()); private readonly MockServiceContext serviceContext; public OrleansCommunicationListenerTests() { serviceContext = new MockServiceContext( this.nodeContext, this.activationContext, "ChocolateMunchingService", new Uri("fabric:/Cocoa/ChocolateMunchingService"), new byte[0], Guid.NewGuid(), 9823); } [Fact] public async Task SimpleUsageScenarioTest() { var endpoints = new EndpointsCollection { CreateEndpoint(ServiceFabricConstants.SiloEndpointName, 9082), CreateEndpoint(ServiceFabricConstants.GatewayEndpointName, 8888) }; activationContext.GetEndpoints().Returns(_ => endpoints); var listener = new OrleansCommunicationListener( builder => { builder.ConfigureServices( services => { // Use our mock silo host. services.Replace(ServiceDescriptor.Singleton<ISiloHost>(sp => Substitute.ForPartsOf<MockSiloHost>(sp))); }); builder.UseLocalhostClustering(); builder.Configure<EndpointOptions>(options => { options.SiloPort = 9082; options.GatewayPort = 8888; }); }); var result = await listener.OpenAsync(CancellationToken.None); var siloHost = listener.Host; var publishedEndpoints = JsonConvert.DeserializeObject<FabricSiloInfo>(result); var siloAddress = publishedEndpoints.SiloAddress; siloAddress.Generation.Should().NotBe(0); siloAddress.Endpoint.Port.ShouldBeEquivalentTo(9082); var gatewayAddress = publishedEndpoints.GatewayAddress; gatewayAddress.Generation.Should().Be(0); gatewayAddress.Endpoint.Port.ShouldBeEquivalentTo(8888); await siloHost.ReceivedWithAnyArgs(1).StartAsync(Arg.Is<CancellationToken>(c => !c.IsCancellationRequested)); await siloHost.DidNotReceive().StopAsync(Arg.Any<CancellationToken>()); siloHost.ClearReceivedCalls(); await listener.CloseAsync(CancellationToken.None); await siloHost.ReceivedWithAnyArgs(1).StopAsync(Arg.Is<CancellationToken>(c => !c.IsCancellationRequested)); await siloHost.DidNotReceiveWithAnyArgs().StartAsync(Arg.Any<CancellationToken>()); } [Fact] public async Task AbortStopAndDisposesSilo() { var endpoints = new EndpointsCollection { CreateEndpoint(ServiceFabricConstants.SiloEndpointName, 9082), CreateEndpoint(ServiceFabricConstants.GatewayEndpointName, 8888) }; activationContext.GetEndpoints().Returns(_ => endpoints); var listener = new OrleansCommunicationListener( builder => { builder.ConfigureServices( services => { // Use our mock silo host. services.Replace(ServiceDescriptor.Singleton<ISiloHost>(sp => Substitute.ForPartsOf<MockSiloHost>(sp))); }); builder.Configure<EndpointOptions>(options => { options.SiloPort = 9082; options.GatewayPort = 8888; }); builder.UseLocalhostClustering(); }); await listener.OpenAsync(CancellationToken.None); var siloHost = listener.Host; siloHost.ClearReceivedCalls(); listener.Abort(); await siloHost.ReceivedWithAnyArgs(1).StopAsync(Arg.Is<CancellationToken>(c => c.IsCancellationRequested)); await siloHost.DidNotReceiveWithAnyArgs().StartAsync(Arg.Any<CancellationToken>()); } [Fact] public async Task CloseStopsSilo() { var endpoints = new EndpointsCollection { CreateEndpoint(ServiceFabricConstants.SiloEndpointName, 9082), CreateEndpoint(ServiceFabricConstants.GatewayEndpointName, 8888) }; activationContext.GetEndpoints().Returns(_ => endpoints); var listener = new OrleansCommunicationListener( builder => { builder.ConfigureServices( services => { // Use our mock silo host. services.Replace(ServiceDescriptor.Singleton<ISiloHost>(sp => Substitute.ForPartsOf<MockSiloHost>(sp))); }); builder.Configure<EndpointOptions>(options => { options.SiloPort = 9082; options.GatewayPort = 8888; }); builder.UseLocalhostClustering(); }); await listener.OpenAsync(CancellationToken.None); var siloHost = listener.Host; siloHost.ClearReceivedCalls(); await listener.CloseAsync(CancellationToken.None); await siloHost.ReceivedWithAnyArgs(1).StopAsync(Arg.Is<CancellationToken>(c => !c.IsCancellationRequested)); await siloHost.DidNotReceiveWithAnyArgs().StartAsync(Arg.Any<CancellationToken>()); } private static EndpointResourceDescription CreateEndpoint(string name, int port) { var endpoint = new EndpointResourceDescription { Name = name }; typeof(EndpointResourceDescription).GetProperty("Port") .GetSetMethod(true) .Invoke(endpoint, new object[] { port }); return endpoint; } public class MockSiloHost : ISiloHost { private readonly TaskCompletionSource<int> stopped = new TaskCompletionSource<int>(); public MockSiloHost(IServiceProvider services) { this.Services = services; } /// <inheritdoc /> public virtual IServiceProvider Services { get; } /// <inheritdoc /> public virtual Task Stopped => this.stopped.Task; /// <inheritdoc /> public virtual async Task StartAsync(CancellationToken cancellationToken) { // Await to avoid compiler warnings. await Task.CompletedTask; } /// <inheritdoc /> public virtual Task StopAsync(CancellationToken cancellationToken) { this.stopped.TrySetResult(0); return Task.CompletedTask; } public void Dispose() { } public ValueTask DisposeAsync() => default; } } /// <summary> /// A grain which is not used but which satisfies startup configuration checks. /// </summary> public class UnusedGrain : Grain { } public interface IUnusedGrain : IGrain { } }
using UnityEngine; using Pathfinding; using Pathfinding.Serialization; namespace Pathfinding { public class PointNode : GraphNode { public GraphNode[] connections; public uint[] connectionCosts; /** Used for internal linked list structure. * \warning Do not modify */ public PointNode next; //public override Int3 Position {get { return position; } } public void SetPosition (Int3 value) { position = value; } public PointNode (AstarPath astar) : base (astar) { } public override void GetConnections (GraphNodeDelegate del) { if (connections == null) return; for (int i=0;i<connections.Length;i++) del (connections[i]); } public override void ClearConnections (bool alsoReverse) { if (alsoReverse && connections != null) { for (int i=0;i<connections.Length;i++) { connections[i].RemoveConnection (this); } } connections = null; connectionCosts = null; } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { UpdateG (path,pathNode); handler.PushNode (pathNode); for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; PathNode otherPN = handler.GetPathNode (other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) { other.UpdateRecursiveG (path, otherPN,handler); } } } public override bool ContainsConnection (GraphNode node) { for (int i=0;i<connections.Length;i++) if (connections[i] == node) return true; return false; } /** Add a connection from this node to the specified node. * If the connection already exists, the cost will simply be updated and * no extra connection added. * * \note Only adds a one-way connection. Consider calling the same function on the other node * to get a two-way connection. */ public override void AddConnection (GraphNode node, uint cost) { if (connections != null) { for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { connectionCosts[i] = cost; return; } } } int connLength = connections != null ? connections.Length : 0; GraphNode[] newconns = new GraphNode[connLength+1]; uint[] newconncosts = new uint[connLength+1]; for (int i=0;i<connLength;i++) { newconns[i] = connections[i]; newconncosts[i] = connectionCosts[i]; } newconns[connLength] = node; newconncosts[connLength] = cost; connections = newconns; connectionCosts = newconncosts; } /** Removes any connection from this node to the specified node. * If no such connection exists, nothing will be done. * * \note This only removes the connection from this node to the other node. * You may want to call the same function on the other node to remove its eventual connection * to this node. */ public override void RemoveConnection (GraphNode node) { if (connections == null) return; for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { int connLength = connections.Length; GraphNode[] newconns = new GraphNode[connLength-1]; uint[] newconncosts = new uint[connLength-1]; for (int j=0;j<i;j++) { newconns[j] = connections[j]; newconncosts[j] = connectionCosts[j]; } for (int j=i+1;j<connLength;j++) { newconns[j-1] = connections[j]; newconncosts[j-1] = connectionCosts[j]; } connections = newconns; connectionCosts = newconncosts; return; } } } public override void Open (Path path, PathNode pathNode, PathHandler handler) { if (connections == null) return; for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; if (path.CanTraverse (other)) { PathNode pathOther = handler.GetPathNode (other); if (pathOther.pathID != handler.PathID) { pathOther.parent = pathNode; pathOther.pathID = handler.PathID; pathOther.cost = connectionCosts[i]; pathOther.H = path.CalculateHScore (other); other.UpdateG (path, pathOther); handler.PushNode (pathOther); } else { //If not we can test if the path from this node to the other one is a better one then the one already used uint tmpCost = connectionCosts[i]; if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) { pathOther.cost = tmpCost; pathOther.parent = pathNode; other.UpdateRecursiveG (path, pathOther,handler); //handler.PushNode (pathOther); } else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) { //Or if the path from the other node to this one is better pathNode.parent = pathOther; pathNode.cost = tmpCost; UpdateRecursiveG (path, pathNode,handler); //handler.PushNode (pathNode); } } } } } public override void SerializeNode (GraphSerializationContext ctx) { base.SerializeNode (ctx); ctx.writer.Write (position.x); ctx.writer.Write (position.y); ctx.writer.Write (position.z); } public override void DeserializeNode (GraphSerializationContext ctx) { base.DeserializeNode (ctx); position = new Int3 (ctx.reader.ReadInt32(), ctx.reader.ReadInt32(), ctx.reader.ReadInt32()); } public override void SerializeReferences (GraphSerializationContext ctx) { if (connections == null) { ctx.writer.Write(-1); } else { ctx.writer.Write (connections.Length); for (int i=0;i<connections.Length;i++) { ctx.writer.Write (ctx.GetNodeIdentifier (connections[i])); ctx.writer.Write (connectionCosts[i]); } } } public override void DeserializeReferences (GraphSerializationContext ctx) { int count = ctx.reader.ReadInt32(); if (count == -1) { connections = null; connectionCosts = null; } else { connections = new GraphNode[count]; connectionCosts = new uint[count]; for (int i=0;i<count;i++) { connections[i] = ctx.GetNodeFromIdentifier (ctx.reader.ReadInt32()); connectionCosts[i] = ctx.reader.ReadUInt32(); } } } } }
namespace Loon.Action.Sprite { using Loon.Core; using Loon.Core.Graphics; using Loon.Java.Collections; using Loon.Core.Geom; using Loon.Utils; using Microsoft.Xna.Framework; using Loon.Core.Timer; using Loon.Core.Graphics.Opengl; using System.Collections.Generic; public class WaitSprite : LObject, ISprite { private sealed class DrawWait { private readonly float sx = 1.0f, sy = 1.0f; private readonly int ANGLE_STEP = 15; private readonly int ARCRADIUS = 120; private LColor color; private double r; private List<object> list; internal int width, height; private int angle; private int style; private int paintX, paintY, paintWidth, paintHeight; private LColor Fill; public DrawWait(int s, int width, int height) { this.style = s; this.width = width; this.height = height; this.color = new LColor(1f, 1f, 1f); switch (style) { case 0: int r1 = width / 8, r2 = height / 8; this.r = ((r1 < r2) ? r1 : r2) / 2; this.list = new List<object>(Arrays.AsList<object>(new object[] { new RectBox(sx + 3 * r, sy + 0 * r, 2 * r, 2 * r), new RectBox(sx + 5 * r, sy + 1 * r, 2 * r, 2 * r), new RectBox(sx + 6 * r, sy + 3 * r, 2 * r, 2 * r), new RectBox(sx + 5 * r, sy + 5 * r, 2 * r, 2 * r), new RectBox(sx + 3 * r, sy + 6 * r, 2 * r, 2 * r), new RectBox(sx + 1 * r, sy + 5 * r, 2 * r, 2 * r), new RectBox(sx + 0 * r, sy + 3 * r, 2 * r, 2 * r), new RectBox(sx + 1 * r, sy + 1 * r, 2 * r, 2 * r) })); break; case 1: this.Fill = new LColor(165, 0, 0, 255); this.paintX = (width - ARCRADIUS); this.paintY = (height - ARCRADIUS); this.paintWidth = paintX + ARCRADIUS; this.paintHeight = paintY + ARCRADIUS; break; } } public void Next() { switch (style) { case 0: CollectionUtils.Add(list, CollectionUtils.RemoveAt(list, 0)); break; case 1: angle += ANGLE_STEP; break; } } public void Draw(GLEx g, int x, int y) { LColor oldColor = g.GetColor(); g.SetColor(color); switch (style) { case 0: float alpha = 0.0f; int nx = x + width / 2 - (int)r * 4, ny = y + height / 2 - (int)r * 4; g.Translate(nx, ny); for (IIterator it = new IteratorAdapter(list.GetEnumerator()); it.HasNext(); ) { RectBox s = (RectBox)it.Next(); alpha = alpha + 0.1f; g.SetAlpha(alpha); g.FillOval(s.x, s.y, s.width, s.height); } g.SetAlpha(1.0F); g.Translate(-nx, -ny); break; case 1: g.SetLineWidth(10); g.Translate(x, y); g.SetColor(Fill); g.DrawOval(0, 0, width, height); int sa = angle % 360; g.FillArc(x + (width - paintWidth) / 2, y + (height - paintHeight) / 2, paintWidth, paintHeight, sa, sa + ANGLE_STEP); g.Translate(-x, -y); g.ResetLineWidth(); break; } g.SetColor(oldColor); } } private LTimer delay; private bool visible; private DrawWait wait; private int style; private Cycle cycle; public WaitSprite(int s):this(s, LSystem.screenRect.width, LSystem.screenRect.height) { } public WaitSprite(int s, int w, int h) { this.style = s; this.wait = new DrawWait(s, w, h); this.delay = new LTimer(120); this.alpha = 1.0F; this.visible = true; if (s > 1) { int width = w / 2; int height = h / 2; cycle = NewSample(s - 2, width, height); RectBox limit = cycle.GetCollisionBox(); SetLocation( (w - ((limit.GetWidth() == 0) ? 20 : limit.GetWidth())) / 2, (h - ((limit.GetHeight() == 0) ? 20 : limit.GetHeight())) / 2); } Update(0); } private static Cycle NewSample(int type, float srcWidth, float srcHeight) { float width = 1; float height = 1; float offset = 0; int padding = 0; switch (type) { case 0: offset = 12; if (srcWidth < srcHeight) { width = 60; height = 60; padding = -35; } else { width = 100; height = 100; padding = -35; } break; case 1: width = 100; height = 40; if (srcWidth < srcHeight) { offset = 0; } else { offset = 8; } break; case 2: width = 30; height = 30; if (srcWidth < srcHeight) { offset = 0; } else { offset = 6; } break; case 3: width = 100; height = 100; padding = -30; break; case 4: width = 80; height = 80; offset = 14; padding = -15; break; case 5: width = 100; height = 100; if (srcWidth < srcHeight) { offset = -4; } break; case 6: width = 60; height = 60; offset = 12; if (srcWidth < srcHeight) { padding = -60; } else { padding = -80; } break; case 7: width = 60; height = 60; offset = 12; if (srcWidth < srcHeight) { padding = -80; } else { padding = -120; } break; case 8: width = 60; height = 60; offset = 12; if (srcWidth < srcHeight) { padding = -60; } else { padding = -80; } break; case 9: width = 80; height = 80; if (srcWidth < srcHeight) { offset = -2; padding = -20; } else { padding = -30; } break; } return Cycle.GetSample(type, srcWidth, srcHeight, width, height, offset, padding); } public void CreateUI(GLEx g) { if (!visible) { return; } if (style < 2) { if (alpha > 0.1f && alpha < 1.0f) { g.SetAlpha(alpha); wait.Draw(g, X(), Y()); g.SetAlpha(1.0F); } else { wait.Draw(g, X(), Y()); } } else { if (cycle != null) { cycle.CreateUI(g); } } } public override int GetHeight() { if (cycle != null) { return cycle.GetCollisionBox().height; } else { return wait.height; } } public override int GetWidth() { if (cycle != null) { return cycle.GetCollisionBox().width; } else { return wait.width; } } public override void Update(long elapsedTime) { if (!visible) { return; } if (cycle != null) { if (cycle.X() != X() || cycle.Y() != Y()) { cycle.SetLocation(X(), Y()); } cycle.Update(elapsedTime); } else { if (delay.Action(elapsedTime)) { wait.Next(); } } } public override void SetAlpha(float alpha) { if (cycle != null) { cycle.SetAlpha(alpha); } else { this.alpha = alpha; } } public override float GetAlpha() { if (cycle != null) { return cycle.GetAlpha(); } else { return alpha; } } public RectBox GetCollisionBox() { if (cycle != null) { return cycle.GetCollisionBox(); } else { return GetRect(X(), Y(), GetWidth(), GetHeight()); } } public bool IsVisible() { return (cycle != null) ? cycle.IsVisible() : visible; } public void SetVisible(bool visible) { if (cycle != null) { cycle.SetVisible(visible); } else { this.visible = visible; } } public LTexture GetBitmap() { return null; } public void Dispose() { } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Reflection; using System.Collections; using System.Linq; using System.Globalization; using System.Runtime.Serialization.Formatters; using System.Text; using System.Text.RegularExpressions; namespace Newtonsoft.Json.Utilities { internal static class ReflectionUtils { public static Type GetObjectType(object v) { return (v != null) ? v.GetType() : null; } public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat) { switch (assemblyFormat) { case FormatterAssemblyStyle.Simple: return GetSimpleTypeName(t); case FormatterAssemblyStyle.Full: return t.AssemblyQualifiedName; default: throw new ArgumentOutOfRangeException(); } } private static string GetSimpleTypeName(Type type) { #if !SILVERLIGHT string fullyQualifiedTypeName = type.FullName + ", " + type.Assembly.GetName().Name; // for type names with no nested type names then return if (!type.IsGenericType || type.IsGenericTypeDefinition) return fullyQualifiedTypeName; #else // Assembly.GetName() is marked SecurityCritical string fullyQualifiedTypeName = type.AssemblyQualifiedName; #endif StringBuilder builder = new StringBuilder(); // loop through the type name and filter out qualified assembly details from nested type names bool writingAssemblyName = false; bool skippingAssemblyDetails = false; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ',': if (!writingAssemblyName) { writingAssemblyName = true; builder.Append(current); } else { skippingAssemblyDetails = true; } break; default: if (!skippingAssemblyDetails) builder.Append(current); break; } } return builder.ToString(); } public static bool IsInstantiatableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsAbstract || t.IsInterface || t.IsArray || t.IsGenericTypeDefinition || t == typeof(void)) return false; if (!HasDefaultConstructor(t)) return false; return true; } public static bool HasDefaultConstructor(Type t) { return HasDefaultConstructor(t, false); } public static bool HasDefaultConstructor(Type t, bool nonPublic) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType) return true; return (GetDefaultConstructor(t, nonPublic) != null); } public static ConstructorInfo GetDefaultConstructor(Type t) { return GetDefaultConstructor(t, false); } public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) { BindingFlags accessModifier = BindingFlags.Public; if (nonPublic) accessModifier = accessModifier | BindingFlags.NonPublic; return t.GetConstructor(accessModifier | BindingFlags.Instance, null, new Type[0], null); } public static bool IsNullable(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType) return IsNullableType(t); return true; } public static bool IsNullableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static Type EnsureNotNullableType(Type t) { return (IsNullableType(t)) ? Nullable.GetUnderlyingType(t) : t; } //public static bool IsValueTypeUnitializedValue(ValueType value) //{ // if (value == null) // return true; // return value.Equals(CreateUnitializedValue(value.GetType())); //} public static bool IsUnitializedValue(object value) { if (value == null) { return true; } else { object unitializedValue = CreateUnitializedValue(value.GetType()); return value.Equals(unitializedValue); } } public static object CreateUnitializedValue(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); if (type.IsGenericTypeDefinition) throw new ArgumentException("Type {0} is a generic type definition and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type"); if (type.IsClass || type.IsInterface || type == typeof(void)) return null; else if (type.IsValueType) return Activator.CreateInstance(type); else throw new ArgumentException("Type {0} cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type"); } public static bool IsPropertyIndexed(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return !CollectionUtils.IsNullOrEmpty<ParameterInfo>(property.GetIndexParameters()); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { Type implementingType; return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition"); if (!genericInterfaceDefinition.IsInterface || !genericInterfaceDefinition.IsGenericTypeDefinition) throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); if (type.IsInterface) { if (type.IsGenericType) { Type interfaceDefinition = type.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = type; return true; } } } foreach (Type i in type.GetInterfaces()) { if (i.IsGenericType) { Type interfaceDefinition = i.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = i; return true; } } } implementingType = null; return false; } public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match) { Type current = type; while (current != null) { if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal)) { match = current; return true; } current = current.BaseType; } foreach (Type i in type.GetInterfaces()) { if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) { match = type; return true; } } match = null; return false; } public static bool AssignableToTypeName(this Type type, string fullTypeName) { Type match; return type.AssignableToTypeName(fullTypeName, out match); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) { Type implementingType; return InheritsGenericDefinition(type, genericClassDefinition, out implementingType); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition"); if (!genericClassDefinition.IsClass || !genericClassDefinition.IsGenericTypeDefinition) throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) { if (currentType.IsGenericType) { Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition(); if (genericClassDefinition == currentGenericClassDefinition) { implementingType = currentType; return true; } } if (currentType.BaseType == null) { implementingType = null; return false; } return InheritsGenericDefinitionInternal(currentType.BaseType, genericClassDefinition, out implementingType); } /// <summary> /// Gets the type of the typed collection's items. /// </summary> /// <param name="type">The type.</param> /// <returns>The type of the typed collection's items.</returns> public static Type GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); Type genericListType; if (type.IsArray) { return type.GetElementType(); } else if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) { if (genericListType.IsGenericTypeDefinition) throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); return genericListType.GetGenericArguments()[0]; } else if (typeof(IEnumerable).IsAssignableFrom(type)) { return null; } else { throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } } public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, "type"); Type genericDictionaryType; if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition) throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); keyType = dictionaryGenericArguments[0]; valueType = dictionaryGenericArguments[1]; return; } else if (typeof(IDictionary).IsAssignableFrom(dictionaryType)) { keyType = null; valueType = null; return; } else { throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); } } public static Type GetDictionaryValueType(Type dictionaryType) { Type keyType; Type valueType; GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); return valueType; } public static Type GetDictionaryKeyType(Type dictionaryType) { Type keyType; Type valueType; GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); return keyType; } /// <summary> /// Tests whether the list's items are their unitialized value. /// </summary> /// <param name="list">The list.</param> /// <returns>Whether the list's items are their unitialized value</returns> public static bool ItemsUnitializedValue<T>(IList<T> list) { ValidationUtils.ArgumentNotNull(list, "list"); Type elementType = GetCollectionItemType(list.GetType()); if (elementType.IsValueType) { object unitializedValue = CreateUnitializedValue(elementType); for (int i = 0; i < list.Count; i++) { if (!list[i].Equals(unitializedValue)) return false; } } else if (elementType.IsClass) { for (int i = 0; i < list.Count; i++) { object value = list[i]; if (value != null) return false; } } else { throw new Exception("Type {0} is neither a ValueType or a Class.".FormatWith(CultureInfo.InvariantCulture, elementType)); } return true; } /// <summary> /// Gets the member's underlying type. /// </summary> /// <param name="member">The member.</param> /// <returns>The underlying type of the member.</returns> public static Type GetMemberUnderlyingType(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); switch (member.MemberType) { case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.Event: return ((EventInfo)member).EventHandlerType; default: throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo or EventInfo", "member"); } } /// <summary> /// Determines whether the member is an indexed property. /// </summary> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) return IsIndexedProperty(propertyInfo); else return false; } /// <summary> /// Determines whether the property is an indexed property. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return (property.GetIndexParameters().Length > 0); } /// <summary> /// Gets the member's value on the object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target object.</param> /// <returns>The member's value on the object.</returns> public static object GetMemberValue(MemberInfo member, object target) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType) { case MemberTypes.Field: return ((FieldInfo)member).GetValue(target); case MemberTypes.Property: try { return ((PropertyInfo)member).GetValue(target, null); } catch (TargetParameterCountException e) { throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e); } default: throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Sets the member's value on the target object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target.</param> /// <param name="value">The value.</param> public static void SetMemberValue(MemberInfo member, object target, object value) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType) { case MemberTypes.Field: ((FieldInfo)member).SetValue(target, value); break; case MemberTypes.Property: ((PropertyInfo)member).SetValue(target, value, null); break; default: throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Determines whether the specified MemberInfo can be read. /// </summary> /// <param name="member">The MemberInfo to determine whether can be read.</param> /// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>. /// </returns> public static bool CanReadMemberValue(MemberInfo member, bool nonPublic) { switch (member.MemberType) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo) member; if (!propertyInfo.CanRead) return false; if (nonPublic) return true; return (propertyInfo.GetGetMethod(nonPublic) != null); default: return false; } } /// <summary> /// Determines whether the specified MemberInfo can be set. /// </summary> /// <param name="member">The MemberInfo to determine whether can be set.</param> /// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>. /// </returns> public static bool CanSetMemberValue(MemberInfo member, bool nonPublic) { switch (member.MemberType) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (fieldInfo.IsInitOnly) return false; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanWrite) return false; if (nonPublic) return true; return (propertyInfo.GetSetMethod(nonPublic) != null); default: return false; } } public static List<MemberInfo> GetFieldsAndProperties<T>(BindingFlags bindingAttr) { return GetFieldsAndProperties(typeof(T), bindingAttr); } public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { List<MemberInfo> targetMembers = new List<MemberInfo>(); targetMembers.AddRange(GetFields(type, bindingAttr)); targetMembers.AddRange(GetProperties(type, bindingAttr)); // for some reason .NET returns multiple members when overriding a generic member on a base class // http://forums.msdn.microsoft.com/en-US/netfxbcl/thread/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/ // filter members to only return the override on the topmost class // update: I think this is fixed in .NET 3.5 SP1 - leave this in for now... List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count); var groupedMembers = targetMembers.GroupBy(m => m.Name).Select(g => new { Count = g.Count(), Members = g.Cast<MemberInfo>() }); foreach (var groupedMember in groupedMembers) { if (groupedMember.Count == 1) { distinctMembers.Add(groupedMember.Members.First()); } else { var members = groupedMember.Members.Where(m => !IsOverridenGenericMember(m, bindingAttr) || m.Name == "Item"); distinctMembers.AddRange(members); } } return distinctMembers; } private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { if (memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property) throw new ArgumentException("Member must be a field or property."); Type declaringType = memberInfo.DeclaringType; if (!declaringType.IsGenericType) return false; Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); if (genericTypeDefinition == null) return false; MemberInfo[] members = genericTypeDefinition.GetMember(memberInfo.Name, bindingAttr); if (members.Length == 0) return false; Type memberUnderlyingType = GetMemberUnderlyingType(members[0]); if (!memberUnderlyingType.IsGenericParameter) return false; return true; } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute { return GetAttribute<T>(attributeProvider, true); } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute { T[] attributes = GetAttributes<T>(attributeProvider, inherit); return CollectionUtils.GetSingleItem(attributes, true); } public static T[] GetAttributes<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute { ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider"); // http://hyperthink.net/blog/getcustomattributes-gotcha/ // ICustomAttributeProvider doesn't do inheritance if (attributeProvider is Assembly) return (T[])Attribute.GetCustomAttributes((Assembly)attributeProvider, typeof(T), inherit); if (attributeProvider is MemberInfo) return (T[])Attribute.GetCustomAttributes((MemberInfo)attributeProvider, typeof(T), inherit); if (attributeProvider is Module) return (T[])Attribute.GetCustomAttributes((Module)attributeProvider, typeof(T), inherit); if (attributeProvider is ParameterInfo) return (T[])Attribute.GetCustomAttributes((ParameterInfo)attributeProvider, typeof(T), inherit); return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit); } public static string GetNameAndAssessmblyName(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return t.FullName + ", " + t.Assembly.GetName().Name; } public static Type MakeGenericType(Type genericTypeDefinition, params Type[] innerTypes) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); ValidationUtils.ArgumentNotNullOrEmpty<Type>(innerTypes, "innerTypes"); ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition, "genericTypeDefinition", "Type {0} is not a generic type definition.".FormatWith(CultureInfo.InvariantCulture, genericTypeDefinition)); return genericTypeDefinition.MakeGenericType(innerTypes); } public static object CreateGeneric(Type genericTypeDefinition, Type innerType, params object[] args) { return CreateGeneric(genericTypeDefinition, new [] { innerType }, args); } public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, params object[] args) { return CreateGeneric(genericTypeDefinition, innerTypes, (t, a) => CreateInstance(t, a.ToArray()), args); } public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, Func<Type, IList<object>, object> instanceCreator, params object[] args) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); ValidationUtils.ArgumentNotNullOrEmpty(innerTypes, "innerTypes"); ValidationUtils.ArgumentNotNull(instanceCreator, "createInstance"); Type specificType = MakeGenericType(genericTypeDefinition, innerTypes.ToArray()); return instanceCreator(specificType, args); } public static bool IsCompatibleValue(object value, Type type) { if (value == null) return IsNullable(type); if (type.IsAssignableFrom(value.GetType())) return true; return false; } public static object CreateInstance(Type type, params object[] args) { ValidationUtils.ArgumentNotNull(type, "type"); #if !PocketPC return Activator.CreateInstance(type, args); #else // CF doesn't have a Activator.CreateInstance overload that takes args // lame if (type.IsValueType && CollectionUtils.IsNullOrEmpty<object>(args)) return Activator.CreateInstance(type); ConstructorInfo[] constructors = type.GetConstructors(); ConstructorInfo match = constructors.Where(c => { ParameterInfo[] parameters = c.GetParameters(); if (parameters.Length != args.Length) return false; for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameter = parameters[i]; object value = args[i]; if (!IsCompatibleValue(value, parameter.ParameterType)) return false; } return true; }).FirstOrDefault(); if (match == null) throw new Exception("Could not create '{0}' with given parameters.".FormatWith(CultureInfo.InvariantCulture, type)); return match.Invoke(args); #endif } public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName) { int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); if (assemblyDelimiterIndex != null) { typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.Value).Trim(); assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.Value + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.Value - 1).Trim(); } else { typeName = fullyQualifiedTypeName; assemblyName = null; } } private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) { // we need to get the first comma following all surrounded in brackets because of generic types // e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 int scope = 0; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': scope++; break; case ']': scope--; break; case ',': if (scope == 0) return i; break; } } return null; } public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr)); // Type.GetFields doesn't return inherited private fields // manually find private fields from base class GetChildPrivateFields(fieldInfos, targetType, bindingAttr); return fieldInfos.Cast<FieldInfo>(); } private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType) != null) { // filter out protected fields IEnumerable<MemberInfo> childPrivateFields = targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>(); initialFields.AddRange(childPrivateFields); } } } public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr)); GetChildPrivateProperties(propertyInfos, targetType, bindingAttr); // a base class private getter/setter will be inaccessable unless the property was gotten from the base class for (int i = 0; i < propertyInfos.Count; i++) { PropertyInfo member = propertyInfos[i]; if (member.DeclaringType != targetType) { Type[] types = member.GetIndexParameters().Select(p => p.ParameterType).ToArray(); PropertyInfo declaredMember = member.DeclaringType.GetProperty(member.Name, bindingAttr, null, member.PropertyType, types, null); propertyInfos[i] = declaredMember; } } return propertyInfos; } public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag) { return ((bindingAttr & flag) == flag) ? bindingAttr ^ flag : bindingAttr; } private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type // find base type properties and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType) != null) { foreach (PropertyInfo propertyInfo in targetType.GetProperties(nonPublicBindingAttr)) { PropertyInfo nonPublicProperty = propertyInfo; // have to test on name rather than reference because instances are different // depending on the type that GetProperties was called on int index = initialProperties.IndexOf(p => p.Name == nonPublicProperty.Name); if (index == -1) { initialProperties.Add(nonPublicProperty); } else { // replace nonpublic properties for a child, but gotten from // the parent with the one from the child // the property gotten from the child will have access to private getter/setter initialProperties[index] = nonPublicProperty; } } } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Management.ExpressRoute; using Microsoft.WindowsAzure.Management.ExpressRoute.Models; namespace Microsoft.WindowsAzure.Management.ExpressRoute { /// <summary> /// The Express Route API provides programmatic access to the functionality /// needed by the customer to set up Dedicated Circuits and Dedicated /// Circuit Links. The Express Route Customer API is a REST API. All API /// operations are performed over SSL and mutually authenticated using /// X.509 v3 certificates. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for /// more information) /// </summary> public static partial class DedicatedCircuitPeeringRouteTableInfoOperationsExtensions { /// <summary> /// The Get DedicatedCircuitPeeringRouteTableInfo operation retrives /// RouteTable. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableInfoOperations. /// </param> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public or microsoft. /// </param> /// <param name='devicePath'> /// Required. Whether the device is primary or secondary. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static ExpressRouteOperationResponse BeginGet(this IDedicatedCircuitPeeringRouteTableInfoOperations operations, string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath) { return Task.Factory.StartNew((object s) => { return ((IDedicatedCircuitPeeringRouteTableInfoOperations)s).BeginGetAsync(serviceKey, accessType, devicePath); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get DedicatedCircuitPeeringRouteTableInfo operation retrives /// RouteTable. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableInfoOperations. /// </param> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public or microsoft. /// </param> /// <param name='devicePath'> /// Required. Whether the device is primary or secondary. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<ExpressRouteOperationResponse> BeginGetAsync(this IDedicatedCircuitPeeringRouteTableInfoOperations operations, string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath) { return operations.BeginGetAsync(serviceKey, accessType, devicePath, CancellationToken.None); } /// <summary> /// The Get DedicatedCircuitPeeringRouteTableInfo operation retrives /// RouteTable. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableInfoOperations. /// </param> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public or microsoft. /// </param> /// <param name='devicePath'> /// Required. Whether the device is primary or secondary. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static ExpressRouteOperationStatusResponse Get(this IDedicatedCircuitPeeringRouteTableInfoOperations operations, string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath) { return Task.Factory.StartNew((object s) => { return ((IDedicatedCircuitPeeringRouteTableInfoOperations)s).GetAsync(serviceKey, accessType, devicePath); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get DedicatedCircuitPeeringRouteTableInfo operation retrives /// RouteTable. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableInfoOperations. /// </param> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public or microsoft. /// </param> /// <param name='devicePath'> /// Required. Whether the device is primary or secondary. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static Task<ExpressRouteOperationStatusResponse> GetAsync(this IDedicatedCircuitPeeringRouteTableInfoOperations operations, string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath) { return operations.GetAsync(serviceKey, accessType, devicePath, CancellationToken.None); } /// <summary> /// The Get Express Route operation status gets information on the /// status of Express Route operations in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableInfoOperations. /// </param> /// <param name='operationId'> /// Required. The id of the operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static ExpressRouteOperationStatusResponse GetOperationStatus(this IDedicatedCircuitPeeringRouteTableInfoOperations operations, string operationId) { return Task.Factory.StartNew((object s) => { return ((IDedicatedCircuitPeeringRouteTableInfoOperations)s).GetOperationStatusAsync(operationId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Express Route operation status gets information on the /// status of Express Route operations in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableInfoOperations. /// </param> /// <param name='operationId'> /// Required. The id of the operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static Task<ExpressRouteOperationStatusResponse> GetOperationStatusAsync(this IDedicatedCircuitPeeringRouteTableInfoOperations operations, string operationId) { return operations.GetOperationStatusAsync(operationId, CancellationToken.None); } } }
//------------------------------------------------------------------------------ // <copyright file="ActionFrame.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Xsl.XsltOld { using Res = System.Xml.Utils.Res; using System; using System.Xml; using System.Xml.XPath; using MS.Internal.Xml.XPath; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Xml.Xsl.XsltOld.Debugger; internal class ActionFrame : IStackFrame { private int state; // Action execution state private int counter; // Counter, for the use of particular action private object [] variables; // Store for template local variable values private Hashtable withParams; private Action action; // Action currently being executed private ActionFrame container; // Frame of enclosing container action and index within it private int currentAction; private XPathNodeIterator nodeSet; // Current node set private XPathNodeIterator newNodeSet; // Node set for processing children or other templates // Variables to store action data between states: private PrefixQName calulatedName; // Used in ElementAction and AttributeAction private string storedOutput; // Used in NumberAction, CopyOfAction, ValueOfAction and ProcessingInstructionAction internal PrefixQName CalulatedName { get { return this.calulatedName; } set { this.calulatedName = value; } } internal string StoredOutput { get { return this.storedOutput; } set { this.storedOutput = value; } } internal int State { get { return this.state; } set { this.state = value; } } internal int Counter { get { return this.counter; } set { this.counter = value; } } internal ActionFrame Container { get { return this.container; } } internal XPathNavigator Node { get { if (this.nodeSet != null) { return this.nodeSet.Current; } return null; } } internal XPathNodeIterator NodeSet { get { return this.nodeSet; } } internal XPathNodeIterator NewNodeSet { get { return this.newNodeSet; } } internal int IncrementCounter() { return ++ this.counter; } [System.Runtime.TargetedPatchingOptOutAttribute("Performance critical to inline across NGen image boundaries")] internal void AllocateVariables(int count) { if (0 < count) { this.variables = new object [count]; } else { this.variables = null; } } internal object GetVariable(int index) { Debug.Assert(this.variables != null && index < this.variables.Length); return this.variables[index]; } internal void SetVariable(int index, object value) { Debug.Assert(this.variables != null && index < this.variables.Length); this.variables[index] = value; } internal void SetParameter(XmlQualifiedName name, object value) { if (this.withParams == null) { this.withParams = new Hashtable(); } Debug.Assert(! this.withParams.Contains(name), "We should check duplicate params at compile time"); this.withParams[name] = value; } internal void ResetParams() { if (this.withParams != null) this.withParams.Clear(); } internal object GetParameter(XmlQualifiedName name) { if (this.withParams != null) { return this.withParams[name]; } return null; } internal void InitNodeSet(XPathNodeIterator nodeSet) { Debug.Assert(nodeSet != null); this.nodeSet = nodeSet; } internal void InitNewNodeSet(XPathNodeIterator nodeSet) { Debug.Assert(nodeSet != null); this.newNodeSet = nodeSet; } internal void SortNewNodeSet(Processor proc, ArrayList sortarray) { Debug.Assert(0 < sortarray.Count); int numSorts = sortarray.Count; XPathSortComparer comparer = new XPathSortComparer(numSorts); for (int i = 0; i < numSorts; i++) { Sort sort = (Sort) sortarray[i]; Query expr = proc.GetCompiledQuery(sort.select); comparer.AddSort(expr, new XPathComparerHelper(sort.order, sort.caseOrder, sort.lang, sort.dataType)); } List<SortKey> results = new List<SortKey>(); Debug.Assert(proc.ActionStack.Peek() == this, "the trick we are doing with proc.Current will work only if this is topmost frame"); while (NewNextNode(proc)) { XPathNodeIterator savedNodeset = this.nodeSet; this.nodeSet = this.newNodeSet; // trick proc.Current node SortKey key = new SortKey(numSorts, /*originalPosition:*/results.Count, this.newNodeSet.Current.Clone()); for (int j = 0; j < numSorts; j ++) { key[j] = comparer.Expression(j).Evaluate(this.newNodeSet); } results.Add(key); this.nodeSet = savedNodeset; // restore proc.Current node } results.Sort(comparer); this.newNodeSet = new XPathSortArrayIterator(results); } // Finished internal void Finished() { State = Action.Finished; } internal void Inherit(ActionFrame parent) { Debug.Assert(parent != null); this.variables = parent.variables; } private void Init(Action action, ActionFrame container, XPathNodeIterator nodeSet) { this.state = Action.Initialized; this.action = action; this.container = container; this.currentAction = 0; this.nodeSet = nodeSet; this.newNodeSet = null; } internal void Init(Action action, XPathNodeIterator nodeSet) { Init(action, null, nodeSet); } internal void Init(ActionFrame containerFrame, XPathNodeIterator nodeSet) { Init(containerFrame.GetAction(0), containerFrame, nodeSet); } internal void SetAction(Action action) { SetAction(action, Action.Initialized); } internal void SetAction(Action action, int state) { this.action = action; this.state = state; } private Action GetAction(int actionIndex) { Debug.Assert(this.action is ContainerAction); return((ContainerAction) this.action).GetAction(actionIndex); } internal void Exit() { Finished(); this.container = null; } /* * Execute * return values: true - pop, false - nothing */ internal bool Execute(Processor processor) { if (this.action == null) { return true; } // Execute the action this.action.Execute(processor, this); // Process results if (State == Action.Finished) { // Advanced to next action if(this.container != null) { this.currentAction ++; this.action = this.container.GetAction(this.currentAction); State = Action.Initialized; } else { this.action = null; } return this.action == null; } return false; // Do not pop, unless specified otherwise } internal bool NextNode(Processor proc) { bool next = this.nodeSet.MoveNext(); if (next && proc.Stylesheet.Whitespace) { XPathNodeType type = this.nodeSet.Current.NodeType; if (type == XPathNodeType.Whitespace) { XPathNavigator nav = this.nodeSet.Current.Clone(); bool flag; do { nav.MoveTo(this.nodeSet.Current); nav.MoveToParent(); flag = ! proc.Stylesheet.PreserveWhiteSpace(proc, nav) && (next = this.nodeSet.MoveNext()); type = this.nodeSet.Current.NodeType; } while (flag && (type == XPathNodeType.Whitespace )); } } return next; } internal bool NewNextNode(Processor proc) { bool next = this.newNodeSet.MoveNext(); if (next && proc.Stylesheet.Whitespace) { XPathNodeType type = this.newNodeSet.Current.NodeType; if (type == XPathNodeType.Whitespace) { XPathNavigator nav = this.newNodeSet.Current.Clone(); bool flag; do { nav.MoveTo(this.newNodeSet.Current); nav.MoveToParent(); flag = ! proc.Stylesheet.PreserveWhiteSpace(proc, nav) && (next = this.newNodeSet.MoveNext()) ; type = this.newNodeSet.Current.NodeType; } while(flag && (type == XPathNodeType.Whitespace )); } } return next; } // ----------------------- IStackFrame : -------------------- XPathNavigator IStackFrame.Instruction { get { if (this.action == null) { return null; // for builtIn action this shoud be null; } return this.action.GetDbgData(this).StyleSheet; } } XPathNodeIterator IStackFrame.NodeSet { get { return this.nodeSet.Clone(); } } // Variables: int IStackFrame.GetVariablesCount() { if (this.action == null) { return 0; } return this.action.GetDbgData(this).Variables.Length; } XPathNavigator IStackFrame.GetVariable(int varIndex) { return this.action.GetDbgData(this).Variables[varIndex].GetDbgData(null).StyleSheet; } object IStackFrame.GetVariableValue(int varIndex) { return GetVariable(this.action.GetDbgData(this).Variables[varIndex].VarKey); } // special array iterator that iterates over ArrayList of SortKey private class XPathSortArrayIterator : XPathArrayIterator { public XPathSortArrayIterator(List<SortKey> list) : base(list) { } public XPathSortArrayIterator(XPathSortArrayIterator it) : base(it) {} public override XPathNodeIterator Clone() { return new XPathSortArrayIterator(this); } public override XPathNavigator Current { get { Debug.Assert(index > 0, "MoveNext() wasn't called"); return ((SortKey) this.list[this.index - 1]).Node; } } } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class Slice : Node { protected Expression _begin; protected Expression _end; protected Expression _step; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Slice CloneNode() { return (Slice)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Slice CleanClone() { return (Slice)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.Slice; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnSlice(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( Slice)node; if (!Node.Matches(_begin, other._begin)) return NoMatch("Slice._begin"); if (!Node.Matches(_end, other._end)) return NoMatch("Slice._end"); if (!Node.Matches(_step, other._step)) return NoMatch("Slice._step"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_begin == existing) { this.Begin = (Expression)newNode; return true; } if (_end == existing) { this.End = (Expression)newNode; return true; } if (_step == existing) { this.Step = (Expression)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { Slice clone = (Slice)FormatterServices.GetUninitializedObject(typeof(Slice)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _begin) { clone._begin = _begin.Clone() as Expression; clone._begin.InitializeParent(clone); } if (null != _end) { clone._end = _end.Clone() as Expression; clone._end.InitializeParent(clone); } if (null != _step) { clone._step = _step.Clone() as Expression; clone._step.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _begin) { _begin.ClearTypeSystemBindings(); } if (null != _end) { _end.ClearTypeSystemBindings(); } if (null != _step) { _step.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Begin { get { return _begin; } set { if (_begin != value) { _begin = value; if (null != _begin) { _begin.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression End { get { return _end; } set { if (_end != value) { _end = value; if (null != _end) { _end.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Step { get { return _step; } set { if (_step != value) { _step = value; if (null != _step) { _step.InitializeParent(this); } } } } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Scriban.Helpers; namespace Scriban.Parsing { /// <summary> /// Lexer enumerator that generates <see cref="Token"/>, to use in a foreach. /// </summary> #if SCRIBAN_PUBLIC public #else internal #endif class Lexer : IEnumerable<Token> { private TextPosition _position; private readonly int _textLength; private Token _token; private char c; private BlockType _blockType; private bool _isLiquidTagBlock; private List<LogMessage> _errors; private int _openBraceCount; private int _escapeRawCharCount; private bool _isExpectingFrontMatter; private readonly bool _isLiquid; private readonly char _stripWhiteSpaceFullSpecialChar; private readonly char _stripWhiteSpaceRestrictedSpecialChar; private const char RawEscapeSpecialChar = '%'; private readonly Queue<Token> _pendingTokens; private readonly TryMatchCustomTokenDelegate _tryMatchCustomToken; /// <summary> /// Lexer options. /// </summary> public readonly LexerOptions Options; /// <summary> /// Initialize a new instance of this <see cref="Lexer" />. /// </summary> /// <param name="text">The text to analyze</param> /// <param name="sourcePath">The sourcePath</param> /// <param name="options">The options for the lexer</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="System.ArgumentNullException"></exception> public Lexer(string text, string sourcePath = null, LexerOptions? options = null) { Text = text ?? throw new ArgumentNullException(nameof(text)); // Setup options var localOptions = options ?? LexerOptions.Default; if (localOptions.FrontMatterMarker == null) { localOptions.FrontMatterMarker = LexerOptions.DefaultFrontMatterMarker; } Options = localOptions; _tryMatchCustomToken = Options.TryMatchCustomToken; _position = Options.StartPosition; if (_position.Offset > text.Length) { throw new ArgumentOutOfRangeException($"The starting position `{_position.Offset}` of range [0, {text.Length - 1}]"); } _textLength = text.Length; SourcePath = sourcePath ?? "<input>"; _blockType = Options.Mode == ScriptMode.ScriptOnly ? BlockType.Code : BlockType.Raw; _pendingTokens = new Queue<Token>(); _isExpectingFrontMatter = Options.Mode == ScriptMode.FrontMatterOnly || Options.Mode == ScriptMode.FrontMatterAndContent; _isLiquid = Options.Lang == ScriptLang.Liquid; _stripWhiteSpaceFullSpecialChar = '-'; _stripWhiteSpaceRestrictedSpecialChar = '~'; } /// <summary> /// Gets the text being parsed by this lexer /// </summary> public string Text { get; } /// <summary> /// /// </summary> public string SourcePath { get; private set; } /// <summary> /// Gets a boolean indicating whether this lexer has errors. /// </summary> public bool HasErrors => _errors != null && _errors.Count > 0; /// <summary> /// Gets error messages. /// </summary> public IEnumerable<LogMessage> Errors => _errors ?? Enumerable.Empty<LogMessage>(); /// <summary> /// Enumerator. Use simply <code>foreach</code> on this instance to automatically trigger an enumeration of the tokens. /// </summary> /// <returns></returns> public Enumerator GetEnumerator() { return new Enumerator(this); } private bool MoveNext() { var previousPosition = new TextPosition(); bool isFirstLoop = true; while (true) { if (_pendingTokens.Count > 0) { _token = _pendingTokens.Dequeue(); return true; } // If we have errors or we are already at the end of the file, we don't continue if (_token.Type == TokenType.Eof) { return false; } if (_position.Offset == _textLength) { _token = Token.Eof; return true; } // Safe guard in any case where the lexer has an error and loop forever (in case we forget to eat a token) if (!isFirstLoop && previousPosition == _position) { throw new InvalidOperationException("Invalid internal state of the lexer in a forever loop"); } isFirstLoop = false; previousPosition = _position; if (Options.Mode != ScriptMode.ScriptOnly) { if (_blockType == BlockType.Raw) { TokenType whiteSpaceMode; if (IsCodeEnterOrEscape(out whiteSpaceMode)) { ReadCodeEnterOrEscape(); return true; } else if (_isExpectingFrontMatter && TryParseFrontMatterMarker()) { _blockType = BlockType.Code; return true; } Debug.Assert(_blockType == BlockType.Raw || _blockType == BlockType.Escape); // Else we have a BlockType.EscapeRaw, so we need to parse the raw block } if (_blockType != BlockType.Raw && IsCodeExit()) { var wasInBlock = _blockType == BlockType.Code; ReadCodeExitOrEscape(); if (wasInBlock) { return true; } // We are exiting from a BlockType.EscapeRaw, so we are back to a raw block or code, so we loop again continue; } if (_blockType == BlockType.Code && _isExpectingFrontMatter && TryParseFrontMatterMarker()) { // Once we have parsed a front matter, we don't expect them any longer _blockType = BlockType.Raw; _isExpectingFrontMatter = false; return true; } } // We may me directly at the end of the EOF without reading anykind of block // So we need to exit here if (_position.Offset == _textLength) { _token = Token.Eof; return true; } if (_blockType == BlockType.Code) { if (_isLiquid) { if (ReadCodeLiquid()) { break; } } else if (ReadCode()) { break; } } else { if (ReadRaw()) { break; } } } return true; } private enum BlockType { Code, Escape, Raw, } private bool TryParseFrontMatterMarker() { var start = _position; var end = _position; var marker = Options.FrontMatterMarker; int i = 0; for (; i < marker.Length; i++) { if (PeekChar(i) != marker[i]) { return false; } } var pc = PeekChar(i); while (pc == ' ' || pc == '\t') { i++; pc = PeekChar(i); } bool valid = false; if (pc == '\n') { valid = true; } else if (pc == '\r') { valid = true; if (PeekChar(i + 1) == '\n') { i++; } } if (valid) { while (i-- >= 0) { end = _position; NextChar(); } _token = new Token(TokenType.FrontMatterMarker, start, end); return true; } return false; } private bool IsCodeEnterOrEscape(out TokenType whitespaceMode) { whitespaceMode = TokenType.Invalid; if (c == '{') { int i = 1; var nc = PeekChar(i); if (!_isLiquid) { while (nc == RawEscapeSpecialChar) { i++; nc = PeekChar(i); } } if (nc == '{' || (_isLiquid && nc == '%')) { var charSpace = PeekChar(i + 1); if (charSpace == _stripWhiteSpaceFullSpecialChar) { whitespaceMode = TokenType.WhitespaceFull; } else if (!_isLiquid && charSpace == _stripWhiteSpaceRestrictedSpecialChar) { whitespaceMode = TokenType.Whitespace; } return true; } } return false; } private void ReadCodeEnterOrEscape() { var start = _position; var end = _position; NextChar(); // Skip { if (!_isLiquid) { while (c == RawEscapeSpecialChar) { _escapeRawCharCount++; end = end.NextColumn(); NextChar(); } } end = end.NextColumn(); if (_isLiquid && c == '%') { _isLiquidTagBlock = true; } NextChar(); // Skip { or % if (c == _stripWhiteSpaceFullSpecialChar || (!_isLiquid && c == _stripWhiteSpaceRestrictedSpecialChar)) { end = end.NextColumn(); NextChar(); } if (_escapeRawCharCount > 0) { _blockType = BlockType.Escape; _token = new Token(TokenType.EscapeEnter, start, end); } else { if (_isLiquid && _isLiquidTagBlock) { if (TryReadLiquidCommentOrRaw(start, end)) { return; } } _blockType = BlockType.Code; _token = new Token(_isLiquidTagBlock ? TokenType.LiquidTagEnter : TokenType.CodeEnter, start, end); } } private bool TryReadLiquidCommentOrRaw(TextPosition codeEnterStart, TextPosition codeEnterEnd) { var start = _position; int offset = 0; PeekSkipSpaces(ref offset); bool isComment; if ((isComment = TryMatchPeek("comment", offset, out offset)) || TryMatchPeek("raw", offset, out offset)) { PeekSkipSpaces(ref offset); if (TryMatchPeek("%}", offset, out offset)) { codeEnterEnd = new TextPosition(start.Offset + offset - 1, start.Line, start.Column + offset - 1); start = new TextPosition(start.Offset + offset, start.Line, start.Column + offset); // Reinitialize the position to the prior character _position = new TextPosition(start.Offset - 1, start.Line, start.Column - 1); c = '}'; while (true) { var end = _position; NextChar(); var codeExitStart = _position; if (c == '{') { NextChar(); if (c == '%') { NextChar(); if (c == '-') { NextChar(); } SkipSpaces(); if (TryMatch(isComment ? "endcomment" : "endraw")) { SkipSpaces(); if (c == '-') { NextChar(); } if (c == '%') { NextChar(); if (c == '}') { var codeExitEnd = _position; NextChar(); // Skip } _blockType = BlockType.Raw; if (isComment) { // Convert a liquid comment into a Scriban multi-line {{ ## comment ## }} _token = new Token(TokenType.CodeEnter, codeEnterStart, codeEnterEnd); _pendingTokens.Enqueue(new Token(TokenType.CommentMulti, start, end)); _pendingTokens.Enqueue(new Token(TokenType.CodeExit, codeExitStart, codeExitEnd)); } else { // Convert a liquid comment into a Scriban multi-line {{ ## comment ## }} _token = new Token(TokenType.EscapeEnter, codeEnterStart, codeEnterEnd); _pendingTokens.Enqueue(new Token(TokenType.Escape, start, end)); _pendingTokens.Enqueue(new Token(TokenType.EscapeExit, codeExitStart, codeExitEnd)); } _isLiquidTagBlock = false; return true; } } } } } else if (c == 0) { break; } } } } return false; } private void SkipSpaces() { while (IsWhitespace(c)) { NextChar(); } } private void PeekSkipSpaces(ref int i) { while (true) { var nc = PeekChar(i); if (nc == ' ' || nc == '\t') { i++; } else { break; } } } private bool TryMatchPeek(string text, int offset, out int offsetOut) { offsetOut = offset; for (int index = 0; index < text.Length; offset++, index++) { if (PeekChar(offset) != text[index]) { return false; } } offsetOut = offset; return true; } private bool TryMatch(string text) { for (int i = 0; i < text.Length; i++) { if (c != text[i]) { return false; } NextChar(); } return true; } private bool IsCodeExit() { // Do we have any brace still opened? If yes, let ReadCode handle them if (_openBraceCount > 0) { return false; } // Do we have a ~}} or ~}%} int start = 0; if (c == _stripWhiteSpaceFullSpecialChar || (!_isLiquid && c == _stripWhiteSpaceRestrictedSpecialChar)) { start = 1; } // Check for either }} or ( %} if liquid active) if (PeekChar(start) != (_isLiquidTagBlock? '%' : '}')) { return false; } start++; if (!_isLiquid) { for (int i = 0; i < _escapeRawCharCount; i++) { if (PeekChar(i + start) != RawEscapeSpecialChar) { return false; } } } return PeekChar(_escapeRawCharCount + start) == '}'; } private void ReadCodeExitOrEscape() { var start = _position; var whitespaceMode = TokenType.Invalid; if (c == _stripWhiteSpaceFullSpecialChar) { whitespaceMode = TokenType.WhitespaceFull; NextChar(); } else if (!_isLiquid && c == _stripWhiteSpaceRestrictedSpecialChar) { whitespaceMode = TokenType.Whitespace; NextChar(); } NextChar(); // skip } or % if (!_isLiquid) { for (int i = 0; i < _escapeRawCharCount; i++) { NextChar(); // skip ! } } var end = _position; NextChar(); // skip } if (_escapeRawCharCount > 0) { // We limit the escape count to 9 levels (only for roundtrip mode) _pendingTokens.Enqueue(new Token(TokenType.EscapeExit, start, end)); _escapeRawCharCount = 0; } else { _token = new Token(_isLiquidTagBlock ? TokenType.LiquidTagExit : TokenType.CodeExit, start, end); } // Eat spaces after an exit if (whitespaceMode != TokenType.Invalid) { var startSpace = _position; var endSpace = new TextPosition(); if (ConsumeWhitespace(whitespaceMode == TokenType.Whitespace, ref endSpace, whitespaceMode == TokenType.Whitespace)) { _pendingTokens.Enqueue(new Token(whitespaceMode, startSpace, endSpace)); } } _isLiquidTagBlock = false; _blockType = BlockType.Raw; } private bool ReadRaw() { var start = _position; var end = new TextPosition(-1, 0, 0); bool nextCodeEnterOrEscapeExit = false; var whitespaceMode = TokenType.Invalid; bool isEmptyRaw = false; var beforeSpaceFull = TextPosition.Eof; var beforeSpaceRestricted = TextPosition.Eof; var lastSpaceFull = TextPosition.Eof; var lastSpaceRestricted = TextPosition.Eof; while (c != '\0') { if (_blockType == BlockType.Raw && IsCodeEnterOrEscape(out whitespaceMode) || _blockType == BlockType.Escape && IsCodeExit()) { isEmptyRaw = end.Offset < 0; nextCodeEnterOrEscapeExit = true; break; } if (char.IsWhiteSpace(c)) { if (lastSpaceFull.Offset < 0) { lastSpaceFull = _position; beforeSpaceFull = end; } if (!(c == '\n' || (c == '\r' && PeekChar() != '\n'))) { if (lastSpaceRestricted.Offset < 0) { lastSpaceRestricted = _position; beforeSpaceRestricted = end; } } else { lastSpaceRestricted.Offset = -1; beforeSpaceRestricted.Offset = -1; } } else { // Reset white space if any lastSpaceFull.Offset = -1; beforeSpaceFull.Offset = -1; lastSpaceRestricted.Offset = -1; beforeSpaceRestricted.Offset = -1; } end = _position; NextChar(); } if (end.Offset < 0) { end = start; } var lastSpace = lastSpaceFull; var beforeSpace = beforeSpaceFull; if (whitespaceMode == TokenType.Whitespace) { lastSpace = lastSpaceRestricted; beforeSpace = beforeSpaceRestricted; } if (whitespaceMode != TokenType.Invalid && lastSpace.Offset >= 0) { _pendingTokens.Enqueue(new Token(whitespaceMode, lastSpace, end)); if (beforeSpace.Offset < 0) { return false; } end = beforeSpace; } Debug.Assert(_blockType == BlockType.Raw || _blockType == BlockType.Escape); if (nextCodeEnterOrEscapeExit) { if (isEmptyRaw) { end = new TextPosition(start.Offset - 1, start.Line, start.Column - 1); } } _token = new Token(_blockType == BlockType.Escape ? TokenType.Escape : TokenType.Raw, start, end); // Go to eof if (!nextCodeEnterOrEscapeExit) { NextChar(); } return true; } private bool ReadCode() { bool hasTokens = true; var start = _position; // Try match a custom token if (TryMatchCustomToken(start)) { return true; } switch (c) { case '\n': _token = new Token(TokenType.NewLine, start, _position); NextChar(); // consume all remaining space including new lines ConsumeWhitespace(false, ref _token.End); break; case ';': _token = new Token(TokenType.SemiColon, start, _position); NextChar(); break; case '\r': NextChar(); // case of: \r\n if (c == '\n') { _token = new Token(TokenType.NewLine, start, _position); NextChar(); // consume all remaining space including new lines ConsumeWhitespace(false, ref _token.End); break; } // case of \r _token = new Token(TokenType.NewLine, start, start); // consume all remaining space including new lines ConsumeWhitespace(false, ref _token.End); break; case ':': _token = new Token(TokenType.Colon, start, start); NextChar(); break; case '@': _token = new Token(TokenType.Arroba, start, start); NextChar(); break; case '^': NextChar(); if (c == '^') { _token = new Token(TokenType.DoubleCaret, start, _position); NextChar(); break; } _token = new Token(TokenType.Caret, start, start); break; case '*': _token = new Token(TokenType.Asterisk, start, start); NextChar(); break; case '/': NextChar(); if (c == '/') { _token = new Token(TokenType.DoubleDivide, start, _position); NextChar(); break; } _token = new Token(TokenType.Divide, start, start); break; case '+': _token = new Token(TokenType.Plus, start, start); NextChar(); break; case '-': _token = new Token(TokenType.Minus, start, start); NextChar(); break; case '%': _token = new Token(TokenType.Percent, start, start); NextChar(); break; case ',': _token = new Token(TokenType.Comma, start, start); NextChar(); break; case '&': NextChar(); if (c == '&') { _token = new Token(TokenType.DoubleAmp, start, _position); NextChar(); break; } // & is an invalid char alone _token = new Token(TokenType.Amp, start, start); break; case '?': NextChar(); if (c == '?') { _token = new Token(TokenType.DoubleQuestion, start, _position); NextChar(); break; } if (c == '.') { _token = new Token(TokenType.QuestionDot, start, _position); NextChar(); break; } _token = new Token(TokenType.Question, start, start); break; case '|': NextChar(); if (c == '|') { _token = new Token(TokenType.DoubleVerticalBar, start, _position); NextChar(); break; } else if (c == '>') { _token = new Token(TokenType.PipeGreater, start, _position); NextChar(); break; } _token = new Token(TokenType.VerticalBar, start, start); break; case '.': NextChar(); if (c == '.') { var index = _position; NextChar(); if (c == '<') { _token = new Token(TokenType.DoubleDotLess, start, _position); NextChar(); break; } if (c == '.') { _token = new Token(TokenType.TripleDot, start, _position); NextChar(); break; } _token = new Token(TokenType.DoubleDot, start, index); break; } _token = new Token(TokenType.Dot, start, start); break; case '!': NextChar(); if (c == '=') { _token = new Token(TokenType.ExclamationEqual, start, _position); NextChar(); break; } _token = new Token(TokenType.Exclamation, start, start); break; case '=': NextChar(); if (c == '=') { _token = new Token(TokenType.DoubleEqual, start, _position); NextChar(); break; } _token = new Token(TokenType.Equal, start, start); break; case '<': NextChar(); if (c == '=') { _token = new Token(TokenType.LessEqual, start, _position); NextChar(); break; } if (c == '<') { _token = new Token(TokenType.DoubleLessThan, start, _position); NextChar(); break; } _token = new Token(TokenType.Less, start, start); break; case '>': NextChar(); if (c == '=') { _token = new Token(TokenType.GreaterEqual, start, _position); NextChar(); break; } if (c == '>') { _token = new Token(TokenType.DoubleGreaterThan, start, _position); NextChar(); break; } _token = new Token(TokenType.Greater, start, start); break; case '(': _token = new Token(TokenType.OpenParen, _position, _position); NextChar(); break; case ')': _token = new Token(TokenType.CloseParen, _position, _position); NextChar(); break; case '[': _token = new Token(TokenType.OpenBracket, _position, _position); NextChar(); break; case ']': _token = new Token(TokenType.CloseBracket, _position, _position); NextChar(); break; case '{': // We count brace open to match then correctly later and avoid confusing with code exit _openBraceCount++; _token = new Token(TokenType.OpenBrace, _position, _position); NextChar(); break; case '}': if (_openBraceCount > 0) { // We match first brace open/close _openBraceCount--; _token = new Token(TokenType.CloseBrace, _position, _position); NextChar(); } else { if (Options.Mode != ScriptMode.ScriptOnly && IsCodeExit()) { // We have no tokens for this ReadCode hasTokens = false; } else { // Else we have a close brace but it is invalid AddError("Unexpected } while no matching {", _position, _position); // Remove the previous error token to still output a valid token _token = new Token(TokenType.CloseBrace, _position, _position); NextChar(); } } break; case '#': ReadComment(); break; case '"': case '\'': ReadString(); break; case '`': ReadVerbatimString(); break; case '\0': _token = Token.Eof; break; default: // Eat any whitespace var lastSpace = new TextPosition(); if (ConsumeWhitespace(true, ref lastSpace)) { if (Options.KeepTrivia) { _token = new Token(TokenType.Whitespace, start, lastSpace); } else { // We have no tokens for this ReadCode hasTokens = false; } break; } bool specialIdentifier = c == '$'; if (IsFirstIdentifierLetter(c) || specialIdentifier) { ReadIdentifier(specialIdentifier); break; } if (char.IsDigit(c)) { ReadNumber(); break; } // invalid char _token = new Token(TokenType.Invalid, _position, _position); NextChar(); break; } return hasTokens; } private bool TryMatchCustomToken(TextPosition start) { if (_tryMatchCustomToken != null) { if (_tryMatchCustomToken(Text, _position, out var matchLength, out var matchTokenType)) { if (matchLength <= 0) throw new InvalidOperationException($"Invalid match length ({matchLength}) for custom token must be > 0"); if (_position.Offset + matchLength > Text.Length) throw new InvalidOperationException($"Invalid match length ({matchLength}) out of range of the input text."); if (matchTokenType < TokenType.Custom && matchTokenType > TokenType.Custom9) throw new InvalidOperationException($"Invalid token type {matchTokenType}. Expecting between {nameof(TokenType)}.{TokenType.Custom} ... {nameof(TokenType)}.{TokenType.Custom9}."); TextPosition matchEnd = _position; while (matchLength > 0) { NextChar(); if (_position.Line != start.Line) { throw new InvalidOperationException($"Invalid match, cannot match between new lines at {_position}"); } matchEnd = _position; matchLength--; } _token = new Token(matchTokenType, start, matchEnd); return true; } } return false; } private bool ReadCodeLiquid() { bool hasTokens = true; var start = _position; switch (c) { case ':': _token = new Token(TokenType.Colon, start, start); NextChar(); break; case ',': _token = new Token(TokenType.Comma, start, start); NextChar(); break; case '|': _token = new Token(TokenType.VerticalBar, start, start); NextChar(); break; case '?': NextChar(); _token = new Token(TokenType.Question, start, start); break; case '-': _token = new Token(TokenType.Minus, start, start); NextChar(); break; case '.': NextChar(); if (c == '.') { _token = new Token(TokenType.DoubleDot, start, _position); NextChar(); break; } _token = new Token(TokenType.Dot, start, start); break; case '!': NextChar(); if (c == '=') { _token = new Token(TokenType.ExclamationEqual, start, _position); NextChar(); break; } _token = new Token(TokenType.Invalid, start, start); break; case '=': NextChar(); if (c == '=') { _token = new Token(TokenType.DoubleEqual, start, _position); NextChar(); break; } _token = new Token(TokenType.Equal, start, start); break; case '<': NextChar(); if (c == '=') { _token = new Token(TokenType.LessEqual, start, _position); NextChar(); break; } _token = new Token(TokenType.Less, start, start); break; case '>': NextChar(); if (c == '=') { _token = new Token(TokenType.GreaterEqual, start, _position); NextChar(); break; } _token = new Token(TokenType.Greater, start, start); break; case '(': _token = new Token(TokenType.OpenParen, _position, _position); NextChar(); break; case ')': _token = new Token(TokenType.CloseParen, _position, _position); NextChar(); break; case '[': _token = new Token(TokenType.OpenBracket, _position, _position); NextChar(); break; case ']': _token = new Token(TokenType.CloseBracket, _position, _position); NextChar(); break; case '"': case '\'': ReadString(); break; case '\0': _token = Token.Eof; break; default: // Eat any whitespace var lastSpace = new TextPosition(); if (ConsumeWhitespace(true, ref lastSpace)) { if (Options.KeepTrivia) { _token = new Token(TokenType.Whitespace, start, lastSpace); } else { // We have no tokens for this ReadCode hasTokens = false; } break; } if (IsFirstIdentifierLetter(c)) { ReadIdentifier(false); break; } if (char.IsDigit(c)) { ReadNumber(); break; } // invalid char _token = new Token(TokenType.Invalid, _position, _position); NextChar(); break; } return hasTokens; } private bool ConsumeWhitespace(bool stopAtNewLine, ref TextPosition lastSpace, bool keepNewLine = false) { var start = _position; while (char.IsWhiteSpace(c)) { if (stopAtNewLine && IsNewLine(c)) { if (keepNewLine) { lastSpace = _position; NextChar(); } break; } lastSpace = _position; NextChar(); } return start != _position; } private static bool IsNewLine(char c) { return c == '\n'; } private void ReadIdentifier(bool special) { var start = _position; TextPosition beforePosition; bool first = true; do { beforePosition = _position; NextChar(); // Special $$ variable allowed only here if (first && special && c == '$') { _token = new Token(TokenType.IdentifierSpecial, start, _position); NextChar(); return; } first = false; } while (IsIdentifierLetter(c)); _token = new Token(special ? TokenType.IdentifierSpecial : TokenType.Identifier, start, beforePosition); // If we have an include token, we are going to parse spaces and non_white_spaces // in order to support the tag "include" if (_isLiquid && Options.EnableIncludeImplicitString && _token.Match("include", Text) && char.IsWhiteSpace(c)) { var startSpace = _position; var endSpace = startSpace; ConsumeWhitespace(false, ref startSpace); _pendingTokens.Enqueue(new Token(TokenType.Whitespace, startSpace, endSpace)); var startPath = _position; var endPath = startPath; while (!char.IsWhiteSpace(c) && c != 0 && c != '%' && PeekChar() != '}') { endPath = _position; NextChar(); } _pendingTokens.Enqueue(new Token(TokenType.ImplicitString, startPath, endPath)); } } [MethodImpl(MethodImplOptionsPortable.AggressiveInlining)] private static bool IsFirstIdentifierLetter(char c) { return c == '_' || char.IsLetter(c); } [MethodImpl(MethodImplOptionsPortable.AggressiveInlining)] private bool IsIdentifierLetter(char c) { return IsFirstIdentifierLetter(c) || char.IsDigit(c) || (_isLiquid && c == '-'); } private void ReadNumber() { var start = _position; var end = _position; var isFloat = false; var isZero = c == '0'; NextChar(); if (isZero && c == 'x') { ReadHexa(start); return; } if (isZero && c == 'b') { ReadBinary(start); return; } // Read first part if (char.IsDigit(c) || c == '_') { do { end = _position; NextChar(); } while (char.IsDigit(c) || c == '_'); } // Read any number following if (c == '.') { // If the next char is a '.' it means that we have a range iterator, so we don't touch it var nc = PeekChar(); // Only support . followed // - by the postfix: 1.f 2.f // - by a digit: 1.0 // - by an exponent 1.e10 if (nc != '.' && (IsNumberPostFix(nc) || char.IsDigit(nc) || !char.IsLetter(nc) || nc == 'e' || nc == 'E')) { isFloat = true; end = _position; NextChar(); while (char.IsDigit(c)) { end = _position; NextChar(); } } } if (c == 'e' || c == 'E') { end = _position; NextChar(); if (c == '+' || c == '-') { end = _position; NextChar(); } if (!char.IsDigit(c)) { AddError("Expecting at least one digit after the exponent", _position, _position); return; } while (char.IsDigit(c)) { end = _position; NextChar(); } } if (!IsIdentifierLetter(PeekChar()) && IsNumberPostFix(c)) { isFloat = true; end = _position; NextChar(); } _token = new Token(isFloat ? TokenType.Float : TokenType.Integer, start, end); } private static bool IsNumberPostFix(char c) { return c == 'f' || c == 'F' || c == 'd' || c == 'D' || c == 'm' || c == 'M'; } private void ReadHexa(TextPosition start) { var end = _position; NextChar(); // skip x bool hasHexa = false; while (true) { if (CharHelper.IsHexa(c)) hasHexa = true; else if (c != '_') break; end = _position; NextChar(); } if (!IsIdentifierLetter(PeekChar()) && (c == 'u' || c == 'U')) { end = _position; NextChar(); } if (!hasHexa) { AddError($"Invalid hex number, expecting at least a hex digit [0-9a-fA-F] after 0x", start, end); } else { _token = new Token(TokenType.HexaInteger, start, end); } } private void ReadBinary(TextPosition start) { var end = _position; NextChar(); // skip b // Read first part bool hasBinary = false; bool hasDotAlready = false; while (true) { if (CharHelper.IsBinary(c)) hasBinary = true; else if (c != '_') break; end = _position; NextChar(); if (c == '.') { if (hasDotAlready) break; var nc = PeekChar(); if (nc != '0' && nc != '1') break; hasDotAlready = true; NextChar(); } } if (!IsIdentifierLetter(PeekChar()) && (c == 'u' || c == 'U' || hasDotAlready && (c == 'f' || c == 'F' || c == 'd' || c == 'D'))) { end = _position; NextChar(); } if (!hasBinary) { AddError($"Invalid binary number, expecting at least a binary digit 0 or 1 after 0b", start, end); } else { _token = new Token(TokenType.BinaryInteger, start, end); } } private void ReadString() { var start = _position; var end = _position; char startChar = c; NextChar(); // Skip " while (true) { if (c == '\\') { end = _position; NextChar(); // 0 ' " \ b f n r t v u0000-uFFFF x00-xFF switch (c) { case '\n': end = _position; NextChar(); continue; case '\r': end = _position; NextChar(); if (c == '\n') { end = _position; NextChar(); } continue; case '0': case '\'': case '"': case '\\': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': end = _position; NextChar(); continue; case 'u': end = _position; NextChar(); // Must be followed 4 hex numbers (0000-FFFF) if (c.IsHex()) // 1 { end = _position; NextChar(); if (c.IsHex()) // 2 { end = _position; NextChar(); if (c.IsHex()) // 3 { end = _position; NextChar(); if (c.IsHex()) // 4 { end = _position; NextChar(); continue; } } } } AddError($"Unexpected hex number `{c}` following `\\u`. Expecting `\\u0000` to `\\uffff`.", _position, _position); break; case 'x': end = _position; NextChar(); // Must be followed 2 hex numbers (00-FF) if (c.IsHex()) { end = _position; NextChar(); if (c.IsHex()) { end = _position; NextChar(); continue; } } AddError($"Unexpected hex number `{c}` following `\\x`. Expecting `\\x00` to `\\xff`", _position, _position); break; } AddError($"Unexpected escape character `{c}` in string. Only 0 ' \\ \" b f n r t v u0000-uFFFF x00-xFF are allowed", _position, _position); } else if (c == '\0') { AddError($"Unexpected end of file while parsing a string not terminated by a {startChar}", end, end); return; } else if (c == startChar) { end = _position; NextChar(); break; } else { end = _position; NextChar(); } } _token = new Token(TokenType.String, start, end); } private void ReadVerbatimString() { var start = _position; var end = _position; char startChar = c; NextChar(); // Skip ` while (true) { if (c == '\0') { AddError($"Unexpected end of file while parsing a verbatim string not terminated by a {startChar}", end, end); return; } else if (c == startChar) { end = _position; NextChar(); // Do we have an escape? if (c != startChar) { break; } end = _position; NextChar(); } else { end = _position; NextChar(); } } _token = new Token(TokenType.VerbatimString, start, end); } private void ReadComment() { var start = _position; var end = _position; NextChar(); // Is Multiline? bool isMulti = false; if (c == '#') { isMulti = true; end = _position; NextChar(); while (!IsCodeExit()) { if (c == '\0') { break; } var mayBeEndOfComment = c == '#'; end = _position; NextChar(); if (mayBeEndOfComment && c == '#') { end = _position; NextChar(); break; } } } else { while (Options.Mode == ScriptMode.ScriptOnly || !IsCodeExit()) { if (c == '\0' || c == '\r' || c == '\n') { break; } end = _position; NextChar(); } } _token = new Token(isMulti ? TokenType.CommentMulti : TokenType.Comment, start, end); } [MethodImpl(MethodImplOptionsPortable.AggressiveInlining)] private char PeekChar(int count = 1) { var offset = _position.Offset + count; return offset >= 0 && offset < _textLength ? Text[offset] : '\0'; } [MethodImpl(MethodImplOptionsPortable.AggressiveInlining)] private void NextChar() { _position.Offset++; if (_position.Offset < _textLength) { var nc = Text[_position.Offset]; if (c == '\n' || (c == '\r' && nc != '\n')) { _position.Column = 0; _position.Line += 1; } else { _position.Column++; } c = nc; } else { _position.Offset = _textLength; c = '\0'; } } IEnumerator<Token> IEnumerable<Token>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private void AddError(string message, TextPosition start, TextPosition end) { _token = new Token(TokenType.Invalid, start, end); if (_errors == null) { _errors = new List<LogMessage>(); } _errors.Add(new LogMessage(ParserMessageType.Error, new SourceSpan(SourcePath, start, end), message)); } private void Reset() { c = Text.Length > 0 ? Text[Options.StartPosition.Offset] : '\0'; _position = Options.StartPosition; _errors = null; } private static bool IsWhitespace(char c) { return c == ' ' || c == '\t'; } /// <summary> /// Custom enumerator on <see cref="Token"/> /// </summary> public struct Enumerator : IEnumerator<Token> { private readonly Lexer lexer; public Enumerator(Lexer lexer) { this.lexer = lexer; lexer.Reset(); } public bool MoveNext() { return lexer.MoveNext(); } public void Reset() { lexer.Reset(); } public Token Current => lexer._token; object IEnumerator.Current => Current; public void Dispose() { } } } }
// // 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 System.Collections.Generic; using System.Linq; using System.Text; using NetworkCommsDotNet; using NetworkCommsDotNet.DPSBase; using NetworkCommsDotNet.Tools.XPlatformHelper; using NetworkCommsDotNet.Connections; using NetworkCommsDotNet.Tools; using NetworkCommsDotNet.Connections.TCP; using NetworkCommsDotNet.Connections.UDP; using System.Net; namespace Examples.ExamplesChat.WinRT { /// <summary> /// In an attempt to keep things as clear as possible all shared implementation across chat examples /// has been provided in this base class. /// </summary> public abstract class ChatAppBase { #region Private Fields /// <summary> /// A boolean used to track the very first initialisation /// </summary> protected bool FirstInitialisation { get; set; } /// <summary> /// Dictionary to keep track of which peer messages have already been written to the chat window /// </summary> protected Dictionary<ShortGuid, ChatMessage> lastPeerMessageDict = new Dictionary<ShortGuid, ChatMessage>(); /// <summary> /// The maximum number of times a chat message will be relayed /// </summary> int relayMaximum = 3; /// <summary> /// A local counter used to track the number of messages sent from /// this instance. /// </summary> long messageSendIndex = 0; /// <summary> /// An optional encryption key to use should one be required. /// This can be changed freely but must obviously be the same /// for both sender and receiver. /// </summary> string _encryptionKey = "ljlhjf8uyfln23490jf;m21-=scm20--iflmk;"; #endregion #region Public Fields /// <summary> /// The type of connection currently used to send and receive messages. Default is TCP. /// </summary> public ConnectionType ConnectionType { get; set; } /// <summary> /// The IP address of the server /// </summary> public string ServerIPAddress { get; set; } /// <summary> /// The port of the server /// </summary> public int ServerPort { get; set; } /// <summary> /// The serializer to use /// </summary> public DataSerializer Serializer { get; set; } /// <summary> /// The local name used when sending messages /// </summary> public string LocalName { get; set; } /// <summary> /// A boolean used to track if the local device is acting as a server /// </summary> public bool LocalServerEnabled { get; set; } /// <summary> /// A boolean used to track if encryption is currently being used /// </summary> public bool EncryptionEnabled { get; set; } #endregion /// <summary> /// Constructor for ChatAppBase /// </summary> public ChatAppBase(string name, ConnectionType connectionType) { LocalName = name; ConnectionType = connectionType; //Initialise the default values ServerIPAddress = ""; ServerPort = 10000; LocalServerEnabled = false; EncryptionEnabled = false; FirstInitialisation = true; } #region NetworkComms.Net Methods /// <summary> /// Updates the configuration of this instance depending on set fields /// </summary> public void RefreshNetworkCommsConfiguration() { #region First Initialisation //On first initialisation we need to configure NetworkComms.Net to handle our incoming packet types //We only need to add the packet handlers once. If we call NetworkComms.Shutdown() at some future point these are not removed. if (FirstInitialisation) { FirstInitialisation = false; //Configure NetworkComms.Net to handle any incoming packet of type 'ChatMessage' //e.g. If we receive a packet of type 'ChatMessage' execute the method 'HandleIncomingChatMessage' NetworkComms.AppendGlobalIncomingPacketHandler<ChatMessage>("ChatMessage", HandleIncomingChatMessage); //Configure NetworkComms.Net to perform some action when a connection is closed //e.g. When a connection is closed execute the method 'HandleConnectionClosed' NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed); } #endregion #region Set serializer //Set the default send recieve options to use the specified serializer. Keep the DataProcessors and Options from the previous defaults NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(Serializer, NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options); #endregion #region Optional Encryption //Configure encryption if requested if (EncryptionEnabled && !NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>())) { //Encryption is currently implemented using a pre-shared key (PSK) system //NetworkComms.Net supports multiple data processors which can be used with any level of granularity //To enable encryption globally (i.e. for all connections) we first add the encryption password as an option RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, _encryptionKey); //Finally we add the RijndaelPSKEncrypter data processor to the sendReceiveOptions NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>()); } else if (!EncryptionEnabled && NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>())) { //If encryption has been disabled but is currently enabled //To disable encryption we just remove the RijndaelPSKEncrypter data processor from the sendReceiveOptions NetworkComms.DefaultSendReceiveOptions.DataProcessors.Remove(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>()); } #endregion #region Local Server Mode and Connection Type Changes if (LocalServerEnabled && ConnectionType == ConnectionType.TCP && !Connection.Listening(ConnectionType.TCP)) { //If we were previously listening for UDP we first shutdown NetworkComms.Net. if (Connection.Listening(ConnectionType.UDP)) { AppendLineToChatHistory("Connection mode has been changed. Any existing connections will be closed."); NetworkComms.Shutdown(); } else { AppendLineToChatHistory("Enabling local server mode. Any existing connections will be closed."); NetworkComms.Shutdown(); } //Start listening for new incoming TCP connections //We want to select a random port on all available adaptors so provide //an IPEndPoint using IPAddress.Any and port 0. Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0)); //Write the IP addresses and ports that we are listening on to the chatBox AppendLineToChatHistory("Listening for incoming TCP connections on:"); foreach (IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) AppendLineToChatHistory(listenEndPoint.Address + ":" + listenEndPoint.Port); //Add a blank line after the initialisation output AppendLineToChatHistory(System.Environment.NewLine); } else if (LocalServerEnabled && ConnectionType == ConnectionType.UDP && !Connection.Listening(ConnectionType.UDP)) { //If we were previously listening for TCP we first shutdown NetworkComms.Net. if (Connection.Listening(ConnectionType.TCP)) { AppendLineToChatHistory("Connection mode has been changed. Any existing connections will be closed."); NetworkComms.Shutdown(); } else { AppendLineToChatHistory("Enabling local server mode. Any existing connections will be closed."); NetworkComms.Shutdown(); } //Start listening for new incoming UDP connections //We want to select a random port on all available adaptors so provide //an IPEndPoint using IPAddress.Any and port 0. Connection.StartListening(ConnectionType.UDP, new IPEndPoint(IPAddress.Any, 0)); //Write the IP addresses and ports that we are listening on to the chatBox AppendLineToChatHistory("Listening for incoming UDP connections on:"); foreach (IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.UDP)) AppendLineToChatHistory(listenEndPoint.Address + ":" + listenEndPoint.Port); //Add a blank line after the initialisation output AppendLineToChatHistory(System.Environment.NewLine); } else if (!LocalServerEnabled && (Connection.Listening(ConnectionType.TCP) || Connection.Listening(ConnectionType.UDP))) { //If the local server mode has been disabled but we are still listening we need to stop accepting incoming connections NetworkComms.Shutdown(); AppendLineToChatHistory("Local server mode disabled. Any existing connections will be closed."); AppendLineToChatHistory(System.Environment.NewLine); } else if (!LocalServerEnabled && ((ConnectionType == ConnectionType.UDP && NetworkComms.GetExistingConnection(ConnectionType.TCP).Count > 0) || (ConnectionType == ConnectionType.TCP && NetworkComms.GetExistingConnection(ConnectionType.UDP).Count > 0))) { //If we are not running a local server but have changed the connection type after creating connections we need to close //existing connections. NetworkComms.Shutdown(); AppendLineToChatHistory("Connection mode has been changed. Existing connections will be closed."); AppendLineToChatHistory(System.Environment.NewLine); } #endregion } /// <summary> /// Performs whatever functions we might so desire when we receive an incoming ChatMessage /// </summary> /// <param name="header">The PacketHeader corresponding with the received object</param> /// <param name="connection">The Connection from which this object was received</param> /// <param name="incomingMessage">The incoming ChatMessage we are after</param> protected virtual void HandleIncomingChatMessage(PacketHeader header, Connection connection, ChatMessage incomingMessage) { //We only want to write a message once to the chat window //Because we support relaying and may receive the same message twice from multiple sources //we use our history and message indexes to ensure we have a new message //We perform this action within a lock as HandleIncomingChatMessage could be called in parallel lock (lastPeerMessageDict) { if (lastPeerMessageDict.ContainsKey(incomingMessage.SourceIdentifier)) { if (lastPeerMessageDict[incomingMessage.SourceIdentifier].MessageIndex < incomingMessage.MessageIndex) { //If this message index is greater than the last seen from this source we can safely //write the message to the ChatBox AppendLineToChatHistory(incomingMessage.SourceName + " - " + incomingMessage.Message); //We now replace the last received message with the current one lastPeerMessageDict[incomingMessage.SourceIdentifier] = incomingMessage; } } else { //If we have never had a message from this source before then it has to be new //by definition lastPeerMessageDict.Add(incomingMessage.SourceIdentifier, incomingMessage); AppendLineToChatHistory(incomingMessage.SourceName + " - " + incomingMessage.Message); } } //This last section of the method is the relay feature //We start by checking to see if this message has already been relayed the maximum number of times if (incomingMessage.RelayCount < relayMaximum) { //If we are going to relay this message we need an array of //all known connections, excluding the current one var allRelayConnections = (from current in NetworkComms.GetExistingConnection() where current != connection select current).ToArray(); //We increment the relay count before we send incomingMessage.IncrementRelayCount(); //We now send the message to every other connection foreach (var relayConnection in allRelayConnections) { //We ensure we perform the send within a try catch //To ensure a single failed send will not prevent the //relay to all working connections. try { relayConnection.SendObject("ChatMessage", incomingMessage); } catch (CommsException) { /* Catch the general comms exception, ignore and continue */ } } } } /// <summary> /// Performs whatever functions we might so desire when an existing connection is closed. /// </summary> /// <param name="connection">The closed connection</param> private void HandleConnectionClosed(Connection connection) { //We are going to write a message to the chat history when a connection disconnects //We perform the following within a lock in case multiple connections disconnect simultaneously lock (lastPeerMessageDict) { //Get the remoteIdentifier from the closed connection //This a unique GUID which can be used to identify peers ShortGuid remoteIdentifier = connection.ConnectionInfo.NetworkIdentifier; //If at any point we received a message with a matching identifier we can //include the peer name in the disconnection message. if (lastPeerMessageDict.ContainsKey(remoteIdentifier)) AppendLineToChatHistory("Connection with '" + lastPeerMessageDict[remoteIdentifier].SourceName + "' has been closed."); else AppendLineToChatHistory("Connection with '" + connection.ToString() + "' has been closed."); //Last thing is to remove this peer from our message history lastPeerMessageDict.Remove(connection.ConnectionInfo.NetworkIdentifier); } } /// <summary> /// Send a message. /// </summary> public void SendMessage(string stringToSend) { //If we have tried to send a zero length string we just return if (stringToSend.Trim() == "") return; //We may or may not have entered some server connection information ConnectionInfo serverConnectionInfo = null; if (ServerIPAddress != "") { try { serverConnectionInfo = new ConnectionInfo(ServerIPAddress, ServerPort); } catch (Exception) { ShowMessage("Failed to parse the server IP and port. Please ensure it is correct and try again"); return; } } //We wrap everything we want to send in the ChatMessage class we created ChatMessage chatMessage = new ChatMessage(NetworkComms.NetworkIdentifier, LocalName, stringToSend, messageSendIndex++); //We add our own message to the message history in case it gets relayed back to us lock (lastPeerMessageDict) lastPeerMessageDict[NetworkComms.NetworkIdentifier] = chatMessage; //We write our own message to the chatBox AppendLineToChatHistory(chatMessage.SourceName + " - " + chatMessage.Message); //Clear the input box text ClearInputLine(); //If we provided server information we send to the server first if (serverConnectionInfo != null) { //We perform the send within a try catch to ensure the application continues to run if there is a problem. try { if (ConnectionType == ConnectionType.TCP) TCPConnection.GetConnection(serverConnectionInfo).SendObject("ChatMessage", chatMessage); else if (ConnectionType == ConnectionType.UDP) UDPConnection.GetConnection(serverConnectionInfo, UDPOptions.None).SendObject("ChatMessage", chatMessage); else throw new Exception("An invalid connectionType is set."); } catch (CommsException) { AppendLineToChatHistory("Error: A communication error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again."); } catch (Exception) { AppendLineToChatHistory("Error: A general error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again."); } } //If we have any other connections we now send the message to those as well //This ensures that if we are the server everyone who is connected to us gets our message //We want a list of all established connections not including the server if set List<ConnectionInfo> otherConnectionInfos; if (serverConnectionInfo != null) otherConnectionInfos = (from current in NetworkComms.AllConnectionInfo() where current.RemoteEndPoint != serverConnectionInfo.RemoteEndPoint select current).ToList(); else otherConnectionInfos = NetworkComms.AllConnectionInfo(); foreach (ConnectionInfo info in otherConnectionInfos) { //We perform the send within a try catch to ensure the application continues to run if there is a problem. try { if (ConnectionType == ConnectionType.TCP) TCPConnection.GetConnection(info).SendObject("ChatMessage", chatMessage); else if (ConnectionType == ConnectionType.UDP) UDPConnection.GetConnection(info, UDPOptions.None).SendObject("ChatMessage", chatMessage); else throw new Exception("An invalid connectionType is set."); } catch (CommsException) { AppendLineToChatHistory("Error: A communication error occurred while trying to send message to " + info + ". Please check settings and try again."); } catch (Exception) { AppendLineToChatHistory("Error: A general error occurred while trying to send message to " + info + ". Please check settings and try again."); } } return; } #endregion #region GUI Interface Methods /// <summary> /// Outputs the usage instructions to the chat window /// </summary> public void PrintUsageInstructions() { AppendLineToChatHistory(""); AppendLineToChatHistory("Chat usage instructions:"); AppendLineToChatHistory(""); AppendLineToChatHistory("Step 1. Open at least two chat applications. You can choose from Android, Windows Phone, iOS or native Windows versions."); AppendLineToChatHistory("Step 2. Enable local server mode in a single application, see settings."); AppendLineToChatHistory("Step 3. Provide remote server IP and port information in settings on remaining application."); AppendLineToChatHistory("Step 4. Start chatting."); AppendLineToChatHistory(""); AppendLineToChatHistory("Note: Connections are established on the first message send."); AppendLineToChatHistory(""); } /// <summary> /// Append the provided message to the chat history text box. /// </summary> /// <param name="message">Message to be appended</param> public abstract void AppendLineToChatHistory(string message); /// <summary> /// Clears the chat history /// </summary> public abstract void ClearChatHistory(); /// <summary> /// Clears the input text box /// </summary> public abstract void ClearInputLine(); /// <summary> /// Show a message box as an alternative to writing to the chat history /// </summary> /// <param name="message">Message to be output</param> public abstract void ShowMessage(string message); #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Common; using Microsoft.VisualStudio.Services.WebApi; using Newtonsoft.Json; using Agent.Sdk.Knob; namespace Agent.Sdk { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716: Identifiers should not match keywords")] public interface IAgentCommandPlugin { String Area { get; } String Event { get; } String DisplayName { get; } Task ProcessCommandAsync(AgentCommandPluginExecutionContext executionContext, CancellationToken token); } public class AgentCommandPluginExecutionContext : ITraceWriter { private VssConnection _connection; private readonly object _stdoutLock = new object(); private readonly object _stderrLock = new object(); public AgentCommandPluginExecutionContext() { this.Endpoints = new List<ServiceEndpoint>(); this.Properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); this.Variables = new Dictionary<string, VariableValue>(StringComparer.OrdinalIgnoreCase); } public string Data { get; set; } public Dictionary<string, string> Properties { get; set; } public List<ServiceEndpoint> Endpoints { get; set; } public Dictionary<string, VariableValue> Variables { get; set; } [JsonIgnore] public VssConnection VssConnection { get { if (_connection == null) { _connection = InitializeVssConnection(); } return _connection; } } public void Info(string message) { Debug(message); } public void Verbose(string message) { #if DEBUG Debug(message); #else string vstsAgentTrace = AgentKnobs.TraceVerbose.GetValue(UtilKnobValueContext.Instance()).AsString(); if (!string.IsNullOrEmpty(vstsAgentTrace)) { Debug(message); } #endif } public void Debug(string message) { if (StringUtil.ConvertToBoolean(this.Variables.GetValueOrDefault("system.debug")?.Value)) { Output($"##[debug]{message}"); } } public void Output(string message) { lock (_stdoutLock) { Console.Out.WriteLine(message); } } public void Error(string message) { lock (_stderrLock) { Console.Error.WriteLine(message); } } public VssConnection InitializeVssConnection() { var headerValues = new List<ProductInfoHeaderValue>(); headerValues.Add(new ProductInfoHeaderValue($"VstsAgentCore-Plugin", Variables.GetValueOrDefault("agent.version")?.Value ?? "Unknown")); headerValues.Add(new ProductInfoHeaderValue($"({RuntimeInformation.OSDescription.Trim()})")); if (VssClientHttpRequestSettings.Default.UserAgent != null && VssClientHttpRequestSettings.Default.UserAgent.Count > 0) { headerValues.AddRange(VssClientHttpRequestSettings.Default.UserAgent); } VssClientHttpRequestSettings.Default.UserAgent = headerValues; if (PlatformUtil.RunningOnLinux || PlatformUtil.RunningOnMacOS) { // The .NET Core 2.1 runtime switched its HTTP default from HTTP 1.1 to HTTP 2. // This causes problems with some versions of the Curl handler. // See GitHub issue https://github.com/dotnet/corefx/issues/32376 VssClientHttpRequestSettings.Default.UseHttp11 = true; } var certSetting = GetCertConfiguration(); if (certSetting != null) { if (!string.IsNullOrEmpty(certSetting.ClientCertificateArchiveFile)) { VssClientHttpRequestSettings.Default.ClientCertificateManager = new AgentClientCertificateManager(certSetting.ClientCertificateArchiveFile, certSetting.ClientCertificatePassword); } if (certSetting.SkipServerCertificateValidation) { VssClientHttpRequestSettings.Default.ServerCertificateValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; } } var proxySetting = GetProxyConfiguration(); if (proxySetting != null) { if (!string.IsNullOrEmpty(proxySetting.ProxyAddress)) { VssHttpMessageHandler.DefaultWebProxy = new AgentWebProxy(proxySetting.ProxyAddress, proxySetting.ProxyUsername, proxySetting.ProxyPassword, proxySetting.ProxyBypassList); } } ServiceEndpoint systemConnection = this.Endpoints.FirstOrDefault(e => string.Equals(e.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase)); ArgUtil.NotNull(systemConnection, nameof(systemConnection)); ArgUtil.NotNull(systemConnection.Url, nameof(systemConnection.Url)); VssCredentials credentials = VssUtil.GetVssCredential(systemConnection); ArgUtil.NotNull(credentials, nameof(credentials)); return VssUtil.CreateConnection(systemConnection.Url, credentials); } private AgentCertificateSettings GetCertConfiguration() { bool skipCertValidation = StringUtil.ConvertToBoolean(this.Variables.GetValueOrDefault("Agent.SkipCertValidation")?.Value); string caFile = this.Variables.GetValueOrDefault("Agent.CAInfo")?.Value; string clientCertFile = this.Variables.GetValueOrDefault("Agent.ClientCert")?.Value; if (!string.IsNullOrEmpty(caFile) || !string.IsNullOrEmpty(clientCertFile) || skipCertValidation) { var certConfig = new AgentCertificateSettings(); certConfig.SkipServerCertificateValidation = skipCertValidation; certConfig.CACertificateFile = caFile; if (!string.IsNullOrEmpty(clientCertFile)) { certConfig.ClientCertificateFile = clientCertFile; string clientCertKey = this.Variables.GetValueOrDefault("Agent.ClientCertKey")?.Value; string clientCertArchive = this.Variables.GetValueOrDefault("Agent.ClientCertArchive")?.Value; string clientCertPassword = this.Variables.GetValueOrDefault("Agent.ClientCertPassword")?.Value; certConfig.ClientCertificatePrivateKeyFile = clientCertKey; certConfig.ClientCertificateArchiveFile = clientCertArchive; certConfig.ClientCertificatePassword = clientCertPassword; } return certConfig; } else { return null; } } private AgentWebProxySettings GetProxyConfiguration() { string proxyUrl = this.Variables.GetValueOrDefault("Agent.ProxyUrl")?.Value; if (!string.IsNullOrEmpty(proxyUrl)) { string proxyUsername = this.Variables.GetValueOrDefault("Agent.ProxyUsername")?.Value; string proxyPassword = this.Variables.GetValueOrDefault("Agent.ProxyPassword")?.Value; List<string> proxyBypassHosts = StringUtil.ConvertFromJson<List<string>>(this.Variables.GetValueOrDefault("Agent.ProxyBypassList")?.Value ?? "[]"); return new AgentWebProxySettings() { ProxyAddress = proxyUrl, ProxyUsername = proxyUsername, ProxyPassword = proxyPassword, ProxyBypassList = proxyBypassHosts, }; } else { return null; } } } }
using System; using System.Runtime.InteropServices; using System.Text; namespace DbgEng.NoExceptions { [ComImport, ComConversionLoss, Guid("E391BBD8-9D8C-4418-840B-C006592A1752"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDebugSymbols4 : IDebugSymbols3 { #pragma warning disable CS0108 // XXX hides inherited member. This is COM default. #region IDebugSymbols [PreserveSig] int GetSymbolOptions( [Out] out uint Options); [PreserveSig] int AddSymbolOptions( [In] uint Options); [PreserveSig] int RemoveSymbolOptions( [In] uint Options); [PreserveSig] int SetSymbolOptions( [In] uint Options); [PreserveSig] int GetNameByOffset( [In] ulong Offset, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByName( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out ulong Offset); [PreserveSig] int GetNearNameByOffset( [In] ulong Offset, [In] int Delta, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetLineByOffset( [In] ulong Offset, [Out] out uint Line, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FileBuffer, [In] uint FileBufferSize, [Out] out uint FileSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByLine( [In] uint Line, [In, MarshalAs(UnmanagedType.LPStr)] string File, [Out] out ulong Offset); [PreserveSig] int GetNumberModules( [Out] out uint Loaded, [Out] out uint Unloaded); [PreserveSig] int GetModuleByIndex( [In] uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByModuleName( [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] uint StartIndex, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByOffset( [In] ulong Offset, [In] uint StartIndex, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleNames( [In] uint Index, [In] ulong Base, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ImageNameBuffer, [In] uint ImageNameBufferSize, [Out] out uint ImageNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ModuleNameBuffer, [In] uint ModuleNameBufferSize, [Out] out uint ModuleNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder LoadedImageNameBuffer, [In] uint LoadedImageNameBufferSize, [Out] out uint LoadedImageNameSize); [PreserveSig] int GetModuleParameters( [In] uint Count, [In] ref ulong Bases, [In] uint Start = default(uint), [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_MODULE_PARAMETERS[] Params = null); [PreserveSig] int GetSymbolModule( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out ulong Base); [PreserveSig] int GetTypeName( [In] ulong Module, [In] uint TypeId, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetTypeId( [In] ulong Module, [In, MarshalAs(UnmanagedType.LPStr)] string Name, [Out] out uint Id); [PreserveSig] int GetTypeSize( [In] ulong Module, [In] uint TypeId, [Out] out uint Size); [PreserveSig] int GetFieldOffset( [In] ulong Module, [In] uint TypeId, [In, MarshalAs(UnmanagedType.LPStr)] string Field, [Out] out uint Offset); [PreserveSig] int GetSymbolTypeId( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out uint TypeId, [Out] out ulong Module); [PreserveSig] int GetOffsetTypeId( [In] ulong Offset, [Out] out uint TypeId, [Out] out ulong Module); [PreserveSig] int ReadTypedDataVirtual( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteTypedDataVirtual( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int OutputTypedDataVirtual( [In] uint OutputControl, [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] uint Flags); [PreserveSig] int ReadTypedDataPhysical( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteTypedDataPhysical( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int OutputTypedDataPhysical( [In] uint OutputControl, [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] uint Flags); [PreserveSig] int GetScope( [Out] out ulong InstructionOffset, [Out] out _DEBUG_STACK_FRAME ScopeFrame, [Out] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int SetScope( [In] ulong InstructionOffset, [In] ref _DEBUG_STACK_FRAME ScopeFrame, [In] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int ResetScope(); [PreserveSig] int GetScopeSymbolGroup( [In] uint Flags, [In, MarshalAs(UnmanagedType.Interface)] IDebugSymbolGroup Update, [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup Symbols); [PreserveSig] int CreateSymbolGroup( [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup Symbols); [PreserveSig] int StartSymbolMatch( [In, MarshalAs(UnmanagedType.LPStr)] string Pattern, [Out] out ulong Handle); [PreserveSig] int GetNextSymbolMatch( [In] ulong Handle, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint MatchSize, [Out] out ulong Offset); [PreserveSig] int EndSymbolMatch( [In] ulong Handle); [PreserveSig] int Reload( [In, MarshalAs(UnmanagedType.LPStr)] string Module); [PreserveSig] int GetSymbolPath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetSymbolPath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] int AppendSymbolPath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] int GetImagePath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetImagePath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] int AppendImagePath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] int GetSourcePath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int GetSourcePathElement( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint ElementSize); [PreserveSig] int SetSourcePath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] int AppendSourcePath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] int FindSourceFile( [In] uint StartElement, [In, MarshalAs(UnmanagedType.LPStr)] string File, [In] uint Flags, [Out] out uint FoundElement, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint FoundSize); [PreserveSig] int GetSourceFileLineOffsets( [In, MarshalAs(UnmanagedType.LPStr)] string File, [Out] out ulong Buffer, [In] uint BufferLines, [Out] out uint FileLines); #endregion #region IDebugSymbols2 [PreserveSig] int GetModuleVersionInformation( [In] uint Index, [In] ulong Base, [In, MarshalAs(UnmanagedType.LPStr)] string Item, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint VerInfoSize); [PreserveSig] int GetModuleNameString( [In] uint Which, [In] uint Index, [In] ulong Base, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint NameSize); [PreserveSig] int GetConstantName( [In] ulong Module, [In] uint TypeId, [In] ulong Value, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetFieldName( [In] ulong Module, [In] uint TypeId, [In] uint FieldIndex, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetTypeOptions( [Out] out uint Options); [PreserveSig] int AddTypeOptions( [In] uint Options); [PreserveSig] int RemoveTypeOptions( [In] uint Options); [PreserveSig] int SetTypeOptions( [In] uint Options); #endregion #region IDebugSymbols3 [PreserveSig] int GetNameByOffsetWide( [In] ulong Offset, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [Out] out ulong Offset); [PreserveSig] int GetNearNameByOffsetWide( [In] ulong Offset, [In] int Delta, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetLineByOffsetWide( [In] ulong Offset, [Out] out uint Line, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder FileBuffer, [In] uint FileBufferSize, [Out] out uint FileSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByLineWide( [In] uint Line, [In, MarshalAs(UnmanagedType.LPWStr)] string File, [Out] out ulong Offset); [PreserveSig] int GetModuleByModuleNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [In] uint StartIndex, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetSymbolModuleWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [Out] out ulong Base); [PreserveSig] int GetTypeNameWide( [In] ulong Module, [In] uint TypeId, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetTypeIdWide( [In] ulong Module, [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [Out] out uint Id); [PreserveSig] int GetFieldOffsetWide( [In] ulong Module, [In] uint TypeId, [In, MarshalAs(UnmanagedType.LPWStr)] string Field, [Out] out uint Offset); [PreserveSig] int GetSymbolTypeIdWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [Out] out uint TypeId, [Out] out ulong Module); [PreserveSig] int GetScopeSymbolGroup2( [In] uint Flags, [In, MarshalAs(UnmanagedType.Interface)] IDebugSymbolGroup2 Update, [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup2 Symbols); [PreserveSig] int CreateSymbolGroup2( [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup2 Symbols); [PreserveSig] int StartSymbolMatchWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Pattern, [Out] out ulong Handle); [PreserveSig] int GetNextSymbolMatchWide( [In] ulong Handle, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint MatchSize, [Out] out ulong Offset); [PreserveSig] int ReloadWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Module); [PreserveSig] int GetSymbolPathWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetSymbolPathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); [PreserveSig] int AppendSymbolPathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Addition); [PreserveSig] int GetImagePathWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetImagePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); [PreserveSig] int AppendImagePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Addition); [PreserveSig] int GetSourcePathWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int GetSourcePathElementWide( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint ElementSize); [PreserveSig] int SetSourcePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); [PreserveSig] int AppendSourcePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Addition); [PreserveSig] int FindSourceFileWide( [In] uint StartElement, [In, MarshalAs(UnmanagedType.LPWStr)] string File, [In] uint Flags, [Out] out uint FoundElement, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint FoundSize); [PreserveSig] int GetSourceFileLineOffsetsWide( [In, MarshalAs(UnmanagedType.LPWStr)] string File, [Out] out ulong Buffer, [In] uint BufferLines, [Out] out uint FileLines); [PreserveSig] int GetModuleVersionInformationWide( [In] uint Index, [In] ulong Base, [In, MarshalAs(UnmanagedType.LPWStr)] string Item, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint VerInfoSize); [PreserveSig] int GetModuleNameStringWide( [In] uint Which, [In] uint Index, [In] ulong Base, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint NameSize); [PreserveSig] int GetConstantNameWide( [In] ulong Module, [In] uint TypeId, [In] ulong Value, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetFieldNameWide( [In] ulong Module, [In] uint TypeId, [In] uint FieldIndex, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int IsManagedModule( [In] uint Index, [In] ulong Base); [PreserveSig] int GetModuleByModuleName2( [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] uint StartIndex, [In] uint Flags, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByModuleName2Wide( [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [In] uint StartIndex, [In] uint Flags, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByOffset2( [In] ulong Offset, [In] uint StartIndex, [In] uint Flags, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int AddSyntheticModule( [In] ulong Base, [In] uint Size, [In, MarshalAs(UnmanagedType.LPStr)] string ImagePath, [In, MarshalAs(UnmanagedType.LPStr)] string ModuleName, [In] uint Flags); [PreserveSig] int AddSyntheticModuleWide( [In] ulong Base, [In] uint Size, [In, MarshalAs(UnmanagedType.LPWStr)] string ImagePath, [In, MarshalAs(UnmanagedType.LPWStr)] string ModuleName, [In] uint Flags); [PreserveSig] int RemoveSyntheticModule( [In] ulong Base); [PreserveSig] int GetCurrentScopeFrameIndex( [Out] out uint Index); [PreserveSig] int SetScopeFrameByIndex( [In] uint Index); [PreserveSig] int SetScopeFromJitDebugInfo( [In] uint OutputControl, [In] ulong InfoOffset); [PreserveSig] int SetScopeFromStoredEvent(); [PreserveSig] int OutputSymbolByOffset( [In] uint OutputControl, [In] uint Flags, [In] ulong Offset); [PreserveSig] int GetFunctionEntryByOffset( [In] ulong Offset, [In] uint Flags, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BufferNeeded); [PreserveSig] int GetFieldTypeAndOffset( [In] ulong Module, [In] uint ContainerTypeId, [In, MarshalAs(UnmanagedType.LPStr)] string Field, [Out] out uint FieldTypeId, [Out] out uint Offset); [PreserveSig] int GetFieldTypeAndOffsetWide( [In] ulong Module, [In] uint ContainerTypeId, [In, MarshalAs(UnmanagedType.LPWStr)] string Field, [Out] out uint FieldTypeId, [Out] out uint Offset); [PreserveSig] int AddSyntheticSymbol( [In] ulong Offset, [In] uint Size, [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] uint Flags, [Out] out _DEBUG_MODULE_AND_ID Id); [PreserveSig] int AddSyntheticSymbolWide( [In] ulong Offset, [In] uint Size, [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [In] uint Flags, [Out] out _DEBUG_MODULE_AND_ID Id); [PreserveSig] int RemoveSyntheticSymbol( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id); [PreserveSig] int GetSymbolEntriesByOffset( [In] ulong Offset, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_MODULE_AND_ID[] Ids, [Out, MarshalAs(UnmanagedType.LPArray)] ulong[] Displacements, [In] uint IdsCount, [Out] out uint Entries); [PreserveSig] int GetSymbolEntriesByName( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_MODULE_AND_ID[] Ids, [In] uint IdsCount, [Out] out uint Entries); [PreserveSig] int GetSymbolEntriesByNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_MODULE_AND_ID[] Ids, [In] uint IdsCount, [Out] out uint Entries); [PreserveSig] int GetSymbolEntryByToken( [In] ulong ModuleBase, [In] uint Token, [Out] out _DEBUG_MODULE_AND_ID Id); [PreserveSig] int GetSymbolEntryInformation( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id, [Out] out _DEBUG_SYMBOL_ENTRY Info); [PreserveSig] int GetSymbolEntryString( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id, [In] uint Which, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); [PreserveSig] int GetSymbolEntryStringWide( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id, [In] uint Which, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); [PreserveSig] int GetSymbolEntryOffsetRegions( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id, [In] uint Flags, [Out] IntPtr Regions, [In] uint RegionsCount, [Out] out uint RegionsAvail); [PreserveSig] int GetSymbolEntryBySymbolEntry( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID FromId, [In] uint Flags, [Out] out _DEBUG_MODULE_AND_ID Id); [PreserveSig] int GetSourceEntriesByOffset( [In] ulong Offset, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_SYMBOL_SOURCE_ENTRY[] Entries, [In] uint EntriesCount, [Out] out uint EntriesAvail); [PreserveSig] int GetSourceEntriesByLine( [In] uint Line, [In, MarshalAs(UnmanagedType.LPStr)] string File, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_SYMBOL_SOURCE_ENTRY[] Entries, [In] uint EntriesCount, [Out] out uint EntriesAvail); [PreserveSig] int GetSourceEntriesByLineWide( [In] uint Line, [In, MarshalAs(UnmanagedType.LPWStr)] string File, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_SYMBOL_SOURCE_ENTRY[] Entries, [In] uint EntriesCount, [Out] out uint EntriesAvail); [PreserveSig] int GetSourceEntryString( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_SYMBOL_SOURCE_ENTRY Entry, [In] uint Which, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); [PreserveSig] int GetSourceEntryStringWide( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_SYMBOL_SOURCE_ENTRY Entry, [In] uint Which, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); [PreserveSig] int GetSourceEntryOffsetRegions( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_SYMBOL_SOURCE_ENTRY Entry, [In] uint Flags, [Out] IntPtr Regions, [In] uint RegionsCount, [Out] out uint RegionsAvail); [PreserveSig] int GetSourceEntryBySourceEntry( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_SYMBOL_SOURCE_ENTRY FromEntry, [In] uint Flags, [Out] out _DEBUG_SYMBOL_SOURCE_ENTRY ToEntry); #endregion #pragma warning restore CS0108 // XXX hides inherited member. This is COM default. [PreserveSig] int GetScopeEx( [Out] out ulong InstructionOffset, [Out] out _DEBUG_STACK_FRAME_EX ScopeFrame, [Out] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int SetScopeEx( [In] ulong InstructionOffset, [In] ref _DEBUG_STACK_FRAME_EX ScopeFrame, [In] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int GetNameByInlineContext( [In] ulong Offset, [In] uint InlineContext, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetNameByInlineContextWide( [In] ulong Offset, [In] uint InlineContext, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetLineByInlineContext( [In] ulong Offset, [In] uint InlineContext, [Out] out uint Line, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FileBuffer, [In] uint FileBufferSize, [Out] out uint FileSize, [Out] out ulong Displacement); [PreserveSig] int GetLineByInlineContextWide( [In] ulong Offset, [In] uint InlineContext, [Out] out uint Line, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder FileBuffer, [In] uint FileBufferSize, [Out] out uint FileSize, [Out] out ulong Displacement); [PreserveSig] int OutputSymbolByInlineContext( [In] uint OutputControl, [In] uint Flags, [In] ulong Offset, [In] uint InlineContext); } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.Texttospeech.v1beta1 { /// <summary>The Texttospeech Service.</summary> public class TexttospeechService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public TexttospeechService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public TexttospeechService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Text = new TextResource(this); Voices = new VoicesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "texttospeech"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://texttospeech.googleapis.com/"; #else "https://texttospeech.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://texttospeech.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud Text-to-Speech API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Cloud Text-to-Speech API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Gets the Text resource.</summary> public virtual TextResource Text { get; } /// <summary>Gets the Voices resource.</summary> public virtual VoicesResource Voices { get; } } /// <summary>A base abstract class for Texttospeech requests.</summary> public abstract class TexttospeechBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new TexttospeechBaseServiceRequest instance.</summary> protected TexttospeechBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Texttospeech parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "text" collection of methods.</summary> public class TextResource { private const string Resource = "text"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TextResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Synthesizes speech synchronously: receive results after all text input has been processed. /// </summary> /// <param name="body">The body of the request.</param> public virtual SynthesizeRequest Synthesize(Google.Apis.Texttospeech.v1beta1.Data.SynthesizeSpeechRequest body) { return new SynthesizeRequest(service, body); } /// <summary> /// Synthesizes speech synchronously: receive results after all text input has been processed. /// </summary> public class SynthesizeRequest : TexttospeechBaseServiceRequest<Google.Apis.Texttospeech.v1beta1.Data.SynthesizeSpeechResponse> { /// <summary>Constructs a new Synthesize request.</summary> public SynthesizeRequest(Google.Apis.Services.IClientService service, Google.Apis.Texttospeech.v1beta1.Data.SynthesizeSpeechRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Texttospeech.v1beta1.Data.SynthesizeSpeechRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "synthesize"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/text:synthesize"; /// <summary>Initializes Synthesize parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } /// <summary>The "voices" collection of methods.</summary> public class VoicesResource { private const string Resource = "voices"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public VoicesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Returns a list of Voice supported for synthesis.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Returns a list of Voice supported for synthesis.</summary> public class ListRequest : TexttospeechBaseServiceRequest<Google.Apis.Texttospeech.v1beta1.Data.ListVoicesResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary> /// Optional. Recommended. [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. If not /// specified, the API will return all supported voices. If specified, the ListVoices call will only return /// voices that can be used to synthesize this language_code. E.g. when specifying "en-NZ", you will get /// supported "en-NZ" voices; when specifying "no", you will get supported "no-\*" (Norwegian) and "nb-\*" /// (Norwegian Bokmal) voices; specifying "zh" will also get supported "cmn-\*" voices; specifying "zh-hk" /// will also get supported "yue-hk" voices. /// </summary> [Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)] public virtual string LanguageCode { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/voices"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("languageCode", new Google.Apis.Discovery.Parameter { Name = "languageCode", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Texttospeech.v1beta1.Data { /// <summary>Description of audio data to be synthesized.</summary> public class AudioConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. The format of the audio byte stream.</summary> [Newtonsoft.Json.JsonPropertyAttribute("audioEncoding")] public virtual string AudioEncoding { get; set; } /// <summary> /// Optional. Input only. An identifier which selects 'audio effects' profiles that are applied on (post /// synthesized) text to speech. Effects are applied on top of each other in the order they are given. See /// [audio profiles](https://cloud.google.com/text-to-speech/docs/audio-profiles) for current supported profile /// ids. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("effectsProfileId")] public virtual System.Collections.Generic.IList<string> EffectsProfileId { get; set; } /// <summary> /// Optional. Input only. Speaking pitch, in the range [-20.0, 20.0]. 20 means increase 20 semitones from the /// original pitch. -20 means decrease 20 semitones from the original pitch. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("pitch")] public virtual System.Nullable<double> Pitch { get; set; } /// <summary> /// Optional. The synthesis sample rate (in hertz) for this audio. When this is specified in /// SynthesizeSpeechRequest, if this is different from the voice's natural sample rate, then the synthesizer /// will honor this request by converting to the desired sample rate (which might result in worse audio /// quality), unless the specified sample rate is not supported for the encoding chosen, in which case it will /// fail the request and return google.rpc.Code.INVALID_ARGUMENT. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sampleRateHertz")] public virtual System.Nullable<int> SampleRateHertz { get; set; } /// <summary> /// Optional. Input only. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 is the normal native speed /// supported by the specific voice. 2.0 is twice as fast, and 0.5 is half as fast. If unset(0.0), defaults to /// the native 1.0 speed. Any other values &amp;lt; 0.25 or &amp;gt; 4.0 will return an error. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("speakingRate")] public virtual System.Nullable<double> SpeakingRate { get; set; } /// <summary> /// Optional. Input only. Volume gain (in dB) of the normal native volume supported by the specific voice, in /// the range [-96.0, 16.0]. If unset, or set to a value of 0.0 (dB), will play at normal native signal /// amplitude. A value of -6.0 (dB) will play at approximately half the amplitude of the normal native signal /// amplitude. A value of +6.0 (dB) will play at approximately twice the amplitude of the normal native signal /// amplitude. Strongly recommend not to exceed +10 (dB) as there's usually no effective increase in loudness /// for any value greater than that. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("volumeGainDb")] public virtual System.Nullable<double> VolumeGainDb { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The message returned to the client by the `ListVoices` method.</summary> public class ListVoicesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The list of voices.</summary> [Newtonsoft.Json.JsonPropertyAttribute("voices")] public virtual System.Collections.Generic.IList<Voice> Voices { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Contains text input to be synthesized. Either `text` or `ssml` must be supplied. Supplying both or neither /// returns google.rpc.Code.INVALID_ARGUMENT. The input size is limited to 5000 characters. /// </summary> public class SynthesisInput : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The SSML document to be synthesized. The SSML document must be valid and well-formed. Otherwise the RPC will /// fail and return google.rpc.Code.INVALID_ARGUMENT. For more information, see /// [SSML](https://cloud.google.com/text-to-speech/docs/ssml). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("ssml")] public virtual string Ssml { get; set; } /// <summary>The raw text to be synthesized.</summary> [Newtonsoft.Json.JsonPropertyAttribute("text")] public virtual string Text { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The top-level message sent by the client for the `SynthesizeSpeech` method.</summary> public class SynthesizeSpeechRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. The configuration of the synthesized audio.</summary> [Newtonsoft.Json.JsonPropertyAttribute("audioConfig")] public virtual AudioConfig AudioConfig { get; set; } /// <summary>Whether and what timepoints are returned in the response.</summary> [Newtonsoft.Json.JsonPropertyAttribute("enableTimePointing")] public virtual System.Collections.Generic.IList<string> EnableTimePointing { get; set; } /// <summary>Required. The Synthesizer requires either plain text or SSML as input.</summary> [Newtonsoft.Json.JsonPropertyAttribute("input")] public virtual SynthesisInput Input { get; set; } /// <summary>Required. The desired voice of the synthesized audio.</summary> [Newtonsoft.Json.JsonPropertyAttribute("voice")] public virtual VoiceSelectionParams Voice { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The message returned to the client by the `SynthesizeSpeech` method.</summary> public class SynthesizeSpeechResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The audio metadata of `audio_content`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("audioConfig")] public virtual AudioConfig AudioConfig { get; set; } /// <summary> /// The audio data bytes encoded as specified in the request, including the header for encodings that are /// wrapped in containers (e.g. MP3, OGG_OPUS). For LINEAR16 audio, we include the WAV header. Note: as with all /// bytes fields, protobuffers use a pure binary representation, whereas JSON representations use base64. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("audioContent")] public virtual string AudioContent { get; set; } /// <summary> /// A link between a position in the original request input and a corresponding time in the output audio. It's /// only supported via `` of SSML input. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("timepoints")] public virtual System.Collections.Generic.IList<Timepoint> Timepoints { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// This contains a mapping between a certain point in the input text and a corresponding time in the output audio. /// </summary> public class Timepoint : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Timepoint name as received from the client within `` tag.</summary> [Newtonsoft.Json.JsonPropertyAttribute("markName")] public virtual string MarkName { get; set; } /// <summary>Time offset in seconds from the start of the synthesized audio.</summary> [Newtonsoft.Json.JsonPropertyAttribute("timeSeconds")] public virtual System.Nullable<double> TimeSeconds { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Description of a voice supported by the TTS service.</summary> public class Voice : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The languages that this voice supports, expressed as [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) /// language tags (e.g. "en-US", "es-419", "cmn-tw"). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("languageCodes")] public virtual System.Collections.Generic.IList<string> LanguageCodes { get; set; } /// <summary>The name of this voice. Each distinct voice has a unique name.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The natural sample rate (in hertz) for this voice.</summary> [Newtonsoft.Json.JsonPropertyAttribute("naturalSampleRateHertz")] public virtual System.Nullable<int> NaturalSampleRateHertz { get; set; } /// <summary>The gender of this voice.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ssmlGender")] public virtual string SsmlGender { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Description of which voice to use for a synthesis request.</summary> public class VoiceSelectionParams : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required. The language (and potentially also the region) of the voice expressed as a /// [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag, e.g. "en-US". This should not include a /// script tag (e.g. use "cmn-cn" rather than "cmn-Hant-cn"), because the script will be inferred from the input /// provided in the SynthesisInput. The TTS service will use this parameter to help choose an appropriate voice. /// Note that the TTS service may choose a voice with a slightly different language code than the one selected; /// it may substitute a different region (e.g. using en-US rather than en-CA if there isn't a Canadian voice /// available), or even a different language, e.g. using "nb" (Norwegian Bokmal) instead of "no" (Norwegian)". /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("languageCode")] public virtual string LanguageCode { get; set; } /// <summary> /// The name of the voice. If not set, the service will choose a voice based on the other parameters such as /// language_code and gender. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// The preferred gender of the voice. If not set, the service will choose a voice based on the other parameters /// such as language_code and name. Note that this is only a preference, not requirement; if a voice of the /// appropriate gender is not available, the synthesizer should substitute a voice with a different gender /// rather than failing the request. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("ssmlGender")] public virtual string SsmlGender { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using Microsoft.Practices.WizardFramework; using System.ComponentModel.Design; using System.Data.SqlClient; using System.Xml; using EnvDTE; using SPALM.SPSF.SharePointBridge; namespace SPALM.SPSF.Library.CustomWizardPages { /// <summary> /// Example of a class that is a custom wizard page /// </summary> public partial class ListTemplateImportPage : CustomWizardPage { public ListTemplateImportPage(WizardForm parent) : base(parent) { // This call is required by the Windows Form Designer. InitializeComponent(); } public override bool IsDataValid { get { try { IDictionaryService dictionaryService = GetService(typeof(IDictionaryService)) as IDictionaryService; if (dictionaryService.GetValue("ListTemplateType") == null) { return false; } } catch (Exception) { } return base.IsDataValid; } } private void button1_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; treeView_nodes.Nodes.Clear(); try { DTE dte = GetService(typeof(DTE)) as DTE; SharePointBrigdeHelper helper = new SharePointBrigdeHelper(dte); SharePointWeb rootweb = helper.GetRootWebOfSite(comboBox1.Text); DisplayWeb(rootweb, treeView_nodes.Nodes); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } Cursor = Cursors.Default; } private void DisplayWeb(SharePointWeb rootweb, TreeNodeCollection treeNodeCollection) { TreeNode node = new TreeNode(rootweb.Title); node.Tag = rootweb; node.ImageKey = "SPWeb"; node.SelectedImageKey = "SPWeb"; treeNodeCollection.Add(node); foreach (SharePointWeb childWeb in rootweb.ChildWebs) { DisplayWeb(childWeb, node.Nodes); } foreach (SharePointList childList in rootweb.Lists) { TreeNode listnode = new TreeNode(childList.Title); listnode.Tag = childList; listnode.ImageKey = "SPList"; listnode.SelectedImageKey = "SPList"; node.Nodes.Add(listnode); } } private void GetAllSiteCollections() { Cursor = Cursors.WaitCursor; this.comboBox1.Items.Clear(); try { DTE dte = GetService(typeof(DTE)) as DTE; SharePointBrigdeHelper helper = new SharePointBrigdeHelper(dte); foreach (SharePointSiteCollection sitecoll in helper.GetAllSiteCollections()) { comboBox1.Items.Add(sitecoll.Url); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } Cursor = Cursors.Default; } private void comboBox1_DropDown(object sender, EventArgs e) { if (comboBox1.Items.Count == 0) { GetAllSiteCollections(); } } private void treeView_nodes_AfterSelect(object sender, TreeViewEventArgs e) { //erstmal ListTemplateType auf leer setzen, damit der Dialog als NotValid angezeigt wird. SetAsInvalid(); if (e.Node != null) { if (e.Node.Tag != null) { if (e.Node.Tag is SharePointList) { try { IDictionaryService dictionaryService = GetService(typeof(IDictionaryService)) as IDictionaryService; SharePointList list = (SharePointList)e.Node.Tag; dictionaryService.SetValue("SiteUrl", list.Url); dictionaryService.SetValue("ListId", list.ID); dictionaryService.SetValue("ListTemplateFeatureId", list.TemplateFeatureId.ToString()); dictionaryService.SetValue("ListTemplateDisplayName", list.Title); dictionaryService.SetValue("ListTemplateDescription", list.Description); dictionaryService.SetValue("ListTemplateType", list.BaseTemplate); dictionaryService.SetValue("ListTemplateBaseType", list.BaseType); dictionaryService.SetValue("ListTemplateName", list.Title.Replace(" ", "").ToLower()); //dictionaryService.SetValue("ListTemplateType", ((int)list.BaseTemplate).ToString()); //dictionaryService.SetValue("ListTemplateCategory", list.templ); //dictionaryService.SetValue("ListTemplateSequence", list.Id); dictionaryService.SetValue("ListTemplateOnQuickLaunch", list.OnQuickLaunch); dictionaryService.SetValue("ListTemplateDisableAttachments", list.EnableAttachments); dictionaryService.SetValue("ListTemplateDisallowContentTypes", list.AllowContentTypes); dictionaryService.SetValue("ListTemplateVersioningEnabled", list.EnableVersioning); dictionaryService.SetValue("ListTemplateFolderCreation", list.EnableFolderCreation); dictionaryService.SetValue("ListTemplateEnableModeration", list.EnableModeration); dictionaryService.SetValue("ListTemplateHiddenList", list.Hidden); dictionaryService.SetValue("ListTemplateSecurityBitsRead", list.ReadSecurity); dictionaryService.SetValue("ListTemplateSecurityBitsEdit", list.WriteSecurity); dictionaryService.SetValue("ListTemplateImage", list.ImageUrl); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } } Wizard.OnValidationStateChanged(this); } private void SetAsInvalid() { try { IDictionaryService dictionaryService = GetService(typeof(IDictionaryService)) as IDictionaryService; dictionaryService.SetValue("ListTemplateType", null); } catch (Exception) { } } private void comboBox1_TextChanged(object sender, EventArgs e) { if (comboBox1.Text != "") { button1.Enabled = true; } else { button1.Enabled = false; } } } }
// This code is part of the Fungus library (https://github.com/snozbot/fungus) // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEditor; using UnityEngine; namespace Fungus.EditorUtils { [CanEditMultipleObjects] [CustomEditor (typeof(View))] public class ViewEditor : Editor { static Color viewColor = Color.yellow; protected SerializedProperty primaryAspectRatioProp; protected SerializedProperty secondaryAspectRatioProp; protected SerializedProperty viewSizeProp; // Draw Views when they're not selected #if UNITY_5_0 [DrawGizmo(GizmoType.NotSelected | GizmoType.SelectedOrChild, typeof(View))] #else [DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.InSelectionHierarchy, typeof(View))] #endif public static void RenderCustomGizmo(View view, GizmoType gizmoType) { DrawView(view, false); } protected virtual Vector2 LookupAspectRatio(int index) { switch (index) { default: case 1: return new Vector2(4, 3); case 2: return new Vector2(3, 2); case 3: return new Vector2(16, 10); case 4: return new Vector2(17, 10); case 5: return new Vector2(16, 9); case 6: return new Vector2(2, 1); case 7: return new Vector2(3, 4); case 8: return new Vector2(2, 3); case 9: return new Vector2(10, 16); case 10: return new Vector2(10, 17); case 11: return new Vector2(9, 16); case 12: return new Vector2(1, 2); } } protected virtual void OnEnable() { primaryAspectRatioProp = serializedObject.FindProperty ("primaryAspectRatio"); secondaryAspectRatioProp = serializedObject.FindProperty ("secondaryAspectRatio"); viewSizeProp = serializedObject.FindProperty("viewSize"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(viewSizeProp); string[] ratios = { "<None>", "Landscape / 4:3", "Landscape / 3:2", "Landscape / 16:10", "Landscape / 17:10", "Landscape / 16:9", "Landscape / 2:1", "Portrait / 3:4", "Portrait / 2:3", "Portrait / 10:16", "Portrait / 10:17", "Portrait / 9:16", "Portrait / 1:2" }; EditorGUILayout.PropertyField(primaryAspectRatioProp, new GUIContent("Primary Aspect Ratio", "Width and height values that define the primary aspect ratio (e.g. 4:3)")); int primaryIndex = EditorGUILayout.Popup("Select Aspect Ratio", 0, ratios); if (primaryIndex > 0) { primaryAspectRatioProp.vector2Value = LookupAspectRatio(primaryIndex); } EditorGUILayout.Separator(); EditorGUILayout.PropertyField(secondaryAspectRatioProp, new GUIContent("Secondary Aspect Ratio", "Width and height values that define the primary aspect ratio (e.g. 4:3)")); int secondaryIndex = EditorGUILayout.Popup("Select Aspect Ratio", 0, ratios); if (secondaryIndex > 0) { secondaryAspectRatioProp.vector2Value = LookupAspectRatio(secondaryIndex); } EditorGUILayout.Separator(); if (EditorGUI.EndChangeCheck()) { // Avoid divide by zero errors if (primaryAspectRatioProp.vector2Value.y == 0) { primaryAspectRatioProp.vector2Value = new Vector2(primaryAspectRatioProp.vector2Value.x, 1f); } if (secondaryAspectRatioProp.vector2Value.y == 0) { secondaryAspectRatioProp.vector2Value = new Vector2(secondaryAspectRatioProp.vector2Value.x, 1f); } SceneView.RepaintAll(); } serializedObject.ApplyModifiedProperties(); } protected virtual void OnSceneGUI () { View t = target as View; if (t.enabled) { EditViewBounds(); } } protected virtual void EditViewBounds() { View view = target as View; DrawView(view, true); Vector3 pos = view.transform.position; float viewSize = CalculateLocalViewSize(view); Vector3[] handles = new Vector3[2]; handles[0] = view.transform.TransformPoint(new Vector3(0, -viewSize, 0)); handles[1] = view.transform.TransformPoint(new Vector3(0, viewSize, 0)); Handles.color = Color.white; for (int i = 0; i < 2; ++i) { Vector3 newPos = Handles.FreeMoveHandle(handles[i], Quaternion.identity, HandleUtility.GetHandleSize(pos) * 0.1f, Vector3.zero, #if UNITY_5_6_OR_NEWER Handles.CubeHandleCap); #else Handles.CubeCap); #endif if (newPos != handles[i]) { Undo.RecordObject(view, "Set View Size"); view.ViewSize = (newPos - pos).magnitude; EditorUtility.SetDirty(view); break; } } } public static void DrawView(View view, bool drawInterior) { float height = CalculateLocalViewSize(view); float widthA = height * (view.PrimaryAspectRatio.x / view.PrimaryAspectRatio.y); float widthB = height * (view.SecondaryAspectRatio.x / view.SecondaryAspectRatio.y); Color transparent = new Color(1,1,1,0f); Color fill = viewColor; Color outline = viewColor; bool highlight = Selection.activeGameObject == view.gameObject; var flowchart = FlowchartWindow.GetFlowchart(); if (flowchart != null) { var selectedCommands = flowchart.SelectedCommands; foreach (var command in selectedCommands) { MoveToView moveToViewCommand = command as MoveToView; if (moveToViewCommand != null && moveToViewCommand.TargetView == view) { highlight = true; } else { FadeToView fadeToViewCommand = command as FadeToView; if (fadeToViewCommand != null && fadeToViewCommand.TargetView == view) { highlight = true; } } } } if (highlight) { fill = outline = Color.green; fill.a = 0.1f; outline.a = 1f; } else { fill.a = 0.1f; outline.a = 0.5f; } if (drawInterior) { // Draw left box { Vector3[] verts = new Vector3[4]; verts[0] = view.transform.TransformPoint(new Vector3(-widthB, -height, 0)); verts[1] = view.transform.TransformPoint(new Vector3(-widthB, height, 0)); verts[2] = view.transform.TransformPoint(new Vector3(-widthA, height, 0)); verts[3] = view.transform.TransformPoint(new Vector3(-widthA, -height, 0)); Handles.DrawSolidRectangleWithOutline(verts, fill, transparent); } // Draw right box { Vector3[] verts = new Vector3[4]; verts[0] = view.transform.TransformPoint(new Vector3(widthA, -height, 0)); verts[1] = view.transform.TransformPoint(new Vector3(widthA, height, 0)); verts[2] = view.transform.TransformPoint(new Vector3(widthB, height, 0)); verts[3] = view.transform.TransformPoint(new Vector3(widthB, -height, 0)); Handles.DrawSolidRectangleWithOutline(verts, fill, transparent); } // Draw inner box { Vector3[] verts = new Vector3[4]; verts[0] = view.transform.TransformPoint(new Vector3(-widthA, -height, 0)); verts[1] = view.transform.TransformPoint(new Vector3(-widthA, height, 0)); verts[2] = view.transform.TransformPoint(new Vector3(widthA, height, 0)); verts[3] = view.transform.TransformPoint(new Vector3(widthA, -height, 0)); Handles.DrawSolidRectangleWithOutline(verts, transparent, outline ); } } // Draw outer box { Vector3[] verts = new Vector3[4]; verts[0] = view.transform.TransformPoint(new Vector3(-widthB, -height, 0)); verts[1] = view.transform.TransformPoint(new Vector3(-widthB, height, 0)); verts[2] = view.transform.TransformPoint(new Vector3(widthB, height, 0)); verts[3] = view.transform.TransformPoint(new Vector3(widthB, -height, 0)); Handles.DrawSolidRectangleWithOutline(verts, transparent, outline ); } } // Calculate view size in local coordinates // Kinda expensive, but accurate and only called in editor. static float CalculateLocalViewSize(View view) { return view.transform.InverseTransformPoint(view.transform.position + new Vector3(0, view.ViewSize, 0)).magnitude; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// AvailableAddOnResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Preview.Marketplace { public class AvailableAddOnResource : Resource { private static Request BuildFetchRequest(FetchAvailableAddOnOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/marketplace/AvailableAddOns/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch an instance of an Add-on currently available to be installed. /// </summary> /// <param name="options"> Fetch AvailableAddOn parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AvailableAddOn </returns> public static AvailableAddOnResource Fetch(FetchAvailableAddOnOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch an instance of an Add-on currently available to be installed. /// </summary> /// <param name="options"> Fetch AvailableAddOn parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AvailableAddOn </returns> public static async System.Threading.Tasks.Task<AvailableAddOnResource> FetchAsync(FetchAvailableAddOnOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch an instance of an Add-on currently available to be installed. /// </summary> /// <param name="pathSid"> The SID of the AvailableAddOn resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AvailableAddOn </returns> public static AvailableAddOnResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchAvailableAddOnOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch an instance of an Add-on currently available to be installed. /// </summary> /// <param name="pathSid"> The SID of the AvailableAddOn resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AvailableAddOn </returns> public static async System.Threading.Tasks.Task<AvailableAddOnResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchAvailableAddOnOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadAvailableAddOnOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/marketplace/AvailableAddOns", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of Add-ons currently available to be installed. /// </summary> /// <param name="options"> Read AvailableAddOn parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AvailableAddOn </returns> public static ResourceSet<AvailableAddOnResource> Read(ReadAvailableAddOnOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<AvailableAddOnResource>.FromJson("available_add_ons", response.Content); return new ResourceSet<AvailableAddOnResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of Add-ons currently available to be installed. /// </summary> /// <param name="options"> Read AvailableAddOn parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AvailableAddOn </returns> public static async System.Threading.Tasks.Task<ResourceSet<AvailableAddOnResource>> ReadAsync(ReadAvailableAddOnOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<AvailableAddOnResource>.FromJson("available_add_ons", response.Content); return new ResourceSet<AvailableAddOnResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of Add-ons currently available to be installed. /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AvailableAddOn </returns> public static ResourceSet<AvailableAddOnResource> Read(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAvailableAddOnOptions(){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of Add-ons currently available to be installed. /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AvailableAddOn </returns> public static async System.Threading.Tasks.Task<ResourceSet<AvailableAddOnResource>> ReadAsync(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAvailableAddOnOptions(){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<AvailableAddOnResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<AvailableAddOnResource>.FromJson("available_add_ons", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<AvailableAddOnResource> NextPage(Page<AvailableAddOnResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<AvailableAddOnResource>.FromJson("available_add_ons", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<AvailableAddOnResource> PreviousPage(Page<AvailableAddOnResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<AvailableAddOnResource>.FromJson("available_add_ons", response.Content); } /// <summary> /// Converts a JSON string into a AvailableAddOnResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> AvailableAddOnResource object represented by the provided JSON </returns> public static AvailableAddOnResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<AvailableAddOnResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// A short description of the Add-on's functionality /// </summary> [JsonProperty("description")] public string Description { get; private set; } /// <summary> /// How customers are charged for using this Add-on /// </summary> [JsonProperty("pricing_type")] public string PricingType { get; private set; } /// <summary> /// The JSON object with the configuration that must be provided when installing a given Add-on /// </summary> [JsonProperty("configuration_schema")] public object ConfigurationSchema { get; private set; } /// <summary> /// The absolute URL of the resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The URLs of related resources /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private AvailableAddOnResource() { } } }
public static class GlobalMembersGdimageopenpolygon3 { #if __cplusplus #endif #define GD_H #define GD_MAJOR_VERSION #define GD_MINOR_VERSION #define GD_RELEASE_VERSION #define GD_EXTRA_VERSION //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext #define GDXXX_VERSION_STR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s) #define GDXXX_STR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s #define GDXXX_SSTR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION #define GD_VERSION_STRING #if _WIN32 || CYGWIN || _WIN32_WCE #if BGDWIN32 #if NONDLL #define BGD_EXPORT_DATA_PROT #else #if __GNUC__ #define BGD_EXPORT_DATA_PROT #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport) #define BGD_EXPORT_DATA_PROT #endif #endif #else #if __GNUC__ #define BGD_EXPORT_DATA_PROT #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport) #define BGD_EXPORT_DATA_PROT #endif #endif //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_STDCALL __stdcall #define BGD_STDCALL #define BGD_EXPORT_DATA_IMPL #else #if HAVE_VISIBILITY #define BGD_EXPORT_DATA_PROT #define BGD_EXPORT_DATA_IMPL #else #define BGD_EXPORT_DATA_PROT #define BGD_EXPORT_DATA_IMPL #endif #define BGD_STDCALL #endif #if BGD_EXPORT_DATA_PROT_ConditionalDefinition1 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #else #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #endif #if __cplusplus #endif #if __cplusplus #endif #define GD_IO_H #if VMS #endif #if __cplusplus #endif #define gdMaxColors #define gdAlphaMax #define gdAlphaOpaque #define gdAlphaTransparent #define gdRedMax #define gdGreenMax #define gdBlueMax //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24) #define gdTrueColorGetAlpha //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16) #define gdTrueColorGetRed //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8) #define gdTrueColorGetGreen //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF) #define gdTrueColorGetBlue #define gdEffectReplace #define gdEffectAlphaBlend #define gdEffectNormal #define gdEffectOverlay #define GD_TRUE #define GD_FALSE #define GD_EPSILON #define M_PI #define gdDashSize #define gdStyled #define gdBrushed #define gdStyledBrushed #define gdTiled #define gdTransparent #define gdAntiAliased //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate #define gdImageCreatePalette #define gdFTEX_LINESPACE #define gdFTEX_CHARMAP #define gdFTEX_RESOLUTION #define gdFTEX_DISABLE_KERNING #define gdFTEX_XSHOW #define gdFTEX_FONTPATHNAME #define gdFTEX_FONTCONFIG #define gdFTEX_RETURNFONTPATHNAME #define gdFTEX_Unicode #define gdFTEX_Shift_JIS #define gdFTEX_Big5 #define gdFTEX_Adobe_Custom //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b)) #define gdTrueColor //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b)) #define gdTrueColorAlpha #define gdArc //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gdPie gdArc #define gdPie #define gdChord #define gdNoFill #define gdEdged //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor) #define gdImageTrueColor //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx) #define gdImageSX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy) #define gdImageSY //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal) #define gdImageColorsTotal //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)]) #define gdImageRed //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)]) #define gdImageGreen //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)]) #define gdImageBlue //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)]) #define gdImageAlpha //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent) #define gdImageGetTransparent //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace) #define gdImageGetInterlaced //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)] #define gdImagePalettePixel //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)] #define gdImageTrueColorPixel //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x #define gdImageResolutionX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y #define gdImageResolutionY #define GD2_CHUNKSIZE #define GD2_CHUNKSIZE_MIN #define GD2_CHUNKSIZE_MAX #define GD2_VERS #define GD2_ID #define GD2_FMT_RAW #define GD2_FMT_COMPRESSED #define GD_FLIP_HORINZONTAL #define GD_FLIP_VERTICAL #define GD_FLIP_BOTH #define GD_CMP_IMAGE #define GD_CMP_NUM_COLORS #define GD_CMP_COLOR #define GD_CMP_SIZE_X #define GD_CMP_SIZE_Y #define GD_CMP_TRANSPARENT #define GD_CMP_BACKGROUND #define GD_CMP_INTERLACE #define GD_CMP_TRUECOLOR #define GD_RESOLUTION #if __cplusplus #endif #if __cplusplus #endif #define GDFX_H #if __cplusplus #endif #if __cplusplus #endif #if __cplusplus #endif #define GDHELPERS_H #if ! _WIN32_WCE #else #endif #if _WIN32 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) CRITICAL_SECTION x #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) InitializeCriticalSection(&x) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) DeleteCriticalSection(&x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) EnterCriticalSection(&x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) LeaveCriticalSection(&x) #define gdMutexUnlock #elif HAVE_PTHREAD //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) pthread_mutex_t x #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) pthread_mutex_init(&x, 0) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) pthread_mutex_destroy(&x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) pthread_mutex_lock(&x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) pthread_mutex_unlock(&x) #define gdMutexUnlock #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) #define gdMutexUnlock #endif //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPCM2DPI(dpcm) (unsigned int)((dpcm)*2.54 + 0.5) #define DPCM2DPI //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPM2DPI(dpm) (unsigned int)((dpm)*0.0254 + 0.5) #define DPM2DPI //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPI2DPCM(dpi) (unsigned int)((dpi)/2.54 + 0.5) #define DPI2DPCM //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPI2DPM(dpi) (unsigned int)((dpi)/0.0254 + 0.5) #define DPI2DPM #if __cplusplus #endif #define GDTEST_TOP_DIR #define GDTEST_STRING_MAX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac)) #define gdAssertImageEqualsToFile //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac)) #define gdAssertImageFileEqualsMsg //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac)) #define gdAssertImageEquals //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac)) #define gdAssertImageEqualsMsg //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond)) #define gdTestAssert //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__) #define gdTestErrorMsg static int Main() { gdImageStruct im; int white; int black; int r; gdPoint points; im = gd.gdImageCreate(100, 100); if (im == null) Environment.Exit(1); white = gd.gdImageColorAllocate(im, 0xff, 0xff, 0xff); black = gd.gdImageColorAllocate(im, 0, 0, 0); gd.gdImageFilledRectangle(im, 0, 0, 99, 99, white); //C++ TO C# CONVERTER TODO TASK: The memory management function 'calloc' has no equivalent in C#: points = (gdPoint)calloc(3, sizeof(gdPoint)); if (points == null) { gd.gdImageDestroy(im); Environment.Exit(1); } points[0].x = 10; points[0].y = 10; points[1].x = 50; points[1].y = 70; points[2].x = 90; points[2].y = 30; gd.gdImageOpenPolygon(im, points, 3, black); //C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro: r = GlobalMembersGdtest.gd.gdTestImageCompareToFile(__FILE__, __LINE__, null, (DefineConstants.GDTEST_TOP_DIR "/gdimageopenpolygon/gdimageopenpolygon3.png"), (im)); //C++ TO C# CONVERTER TODO TASK: The memory management function 'free' has no equivalent in C#: free(points); gd.gdImageDestroy(im); if (r == 0) Environment.Exit(1); return EXIT_SUCCESS; } }
using System; using System.Collections.Generic; using System.IO; using UnityEngine; using DarkMultiPlayerCommon; using System.Reflection; using Contracts; namespace DarkMultiPlayer { public class ScenarioWorker { public bool workerEnabled = false; private Dictionary<string, string> checkData = new Dictionary<string, string>(); private Queue<ScenarioEntry> scenarioQueue = new Queue<ScenarioEntry>(); private bool blockScenarioDataSends = false; private float lastScenarioSendTime = 0f; private const float SEND_SCENARIO_DATA_INTERVAL = 30f; //ScenarioType list to check. private Dictionary<string, Type> allScenarioTypesInAssemblies; //System.Reflection hackiness for loading kerbals into the crew roster: private delegate bool AddCrewMemberToRosterDelegate(ProtoCrewMember pcm); // Game hooks private bool registered; //Services private DMPGame dmpGame; private VesselWorker vesselWorker; private ConfigNodeSerializer configNodeSerializer; private NetworkWorker networkWorker; public ScenarioWorker(DMPGame dmpGame, VesselWorker vesselWorker, ConfigNodeSerializer configNodeSerializer, NetworkWorker networkWorker) { this.dmpGame = dmpGame; this.vesselWorker = vesselWorker; this.configNodeSerializer = configNodeSerializer; this.networkWorker = networkWorker; dmpGame.updateEvent.Add(Update); } private void RegisterGameHooks() { registered = true; GameEvents.Contract.onAccepted.Add(OnContractAccepted); GameEvents.Contract.onOffered.Add(OnContractOffered); } private void UnregisterGameHooks() { registered = false; GameEvents.Contract.onAccepted.Remove(OnContractAccepted); GameEvents.Contract.onOffered.Remove(OnContractOffered); } private void OnContractAccepted(Contract contract) { DarkLog.Debug("Contract accepted, state: " + contract.ContractState); ConfigNode contractNode = new ConfigNode(); contract.Save(contractNode); if (contractNode.GetValue("type") == "RecoverAsset") { string kerbalName = contractNode.GetValue("kerbalName").Trim(); uint partID = uint.Parse(contractNode.GetValue("partID")); if (!string.IsNullOrEmpty(kerbalName)) { ProtoCrewMember rescueKerbal = null; if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName)) { DarkLog.Debug("Generating missing kerbal " + kerbalName + " for rescue contract"); int kerbalGender = int.Parse(contractNode.GetValue("gender")); rescueKerbal = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned); rescueKerbal.ChangeName(kerbalName); rescueKerbal.gender = (ProtoCrewMember.Gender)kerbalGender; rescueKerbal.rosterStatus = ProtoCrewMember.RosterStatus.Assigned; } else { rescueKerbal = HighLogic.CurrentGame.CrewRoster[kerbalName]; DarkLog.Debug("Kerbal " + kerbalName + " already exists, skipping respawn"); } if (rescueKerbal != null) vesselWorker.SendKerbalIfDifferent(rescueKerbal); } if (partID != 0) { Vessel contractVessel = FinePrint.Utilities.VesselUtilities.FindVesselWithPartIDs(new List<uint> { partID }); if (contractVessel != null) vesselWorker.SendVesselUpdateIfNeeded(contractVessel); } } else if (contractNode.GetValue("type") == "TourismContract") { string tourists = contractNode.GetValue("tourists"); if (tourists != null) { string[] touristsNames = tourists.Split(new char[] { '|' }); foreach (string touristName in touristsNames) { ProtoCrewMember pcm = null; if (!HighLogic.CurrentGame.CrewRoster.Exists(touristName)) { DarkLog.Debug("Spawning missing tourist " + touristName + " for tourism contract"); pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Tourist); pcm.rosterStatus = ProtoCrewMember.RosterStatus.Available; pcm.ChangeName(touristName); } else { DarkLog.Debug("Skipped respawn of existing tourist " + touristName); pcm = HighLogic.CurrentGame.CrewRoster[touristName]; } if (pcm != null) vesselWorker.SendKerbalIfDifferent(pcm); } } } } private void OnContractOffered(Contract contract) { ConfigNode contractNode = new ConfigNode(); contract.Save(contractNode); if (contractNode.GetValue("type") == "RecoverAsset") { string kerbalName = contractNode.GetValue("kerbalName"); vesselWorker.SendKerbalIfDifferent(HighLogic.CurrentGame.CrewRoster[kerbalName]); } } private void Update() { if (workerEnabled) { if (!registered) RegisterGameHooks(); if (!blockScenarioDataSends) { if ((Client.realtimeSinceStartup - lastScenarioSendTime) > SEND_SCENARIO_DATA_INTERVAL) { lastScenarioSendTime = Client.realtimeSinceStartup; SendScenarioModules(false); } } } else { if (registered) UnregisterGameHooks(); } } private void LoadScenarioTypes() { allScenarioTypesInAssemblies = new Dictionary<string, Type>(); foreach (AssemblyLoader.LoadedAssembly something in AssemblyLoader.loadedAssemblies) { foreach (Type scenarioType in something.assembly.GetTypes()) { if (scenarioType.IsSubclassOf(typeof(ScenarioModule))) { if (!allScenarioTypesInAssemblies.ContainsKey(scenarioType.Name)) { allScenarioTypesInAssemblies.Add(scenarioType.Name, scenarioType); } } } } } private bool IsScenarioModuleAllowed(string scenarioName) { if (scenarioName == null) { return false; } //Blacklist asteroid module from every game mode if (scenarioName == "DiscoverableObjects") { //We hijack this and enable / disable it if we need to. return false; } if (allScenarioTypesInAssemblies == null) { //Load type dictionary on first use LoadScenarioTypes(); } if (!allScenarioTypesInAssemblies.ContainsKey(scenarioName)) { //Module missing return false; } Type scenarioType = allScenarioTypesInAssemblies[scenarioName]; KSPScenario[] scenarioAttributes = (KSPScenario[])scenarioType.GetCustomAttributes(typeof(KSPScenario), true); if (scenarioAttributes.Length > 0) { KSPScenario attribute = scenarioAttributes[0]; bool protoAllowed = false; if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER) { protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToExistingCareerGames); protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToNewCareerGames); } if (HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX) { protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToExistingScienceSandboxGames); protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToNewScienceSandboxGames); } if (HighLogic.CurrentGame.Mode == Game.Modes.SANDBOX) { protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToExistingSandboxGames); protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToNewSandboxGames); } return protoAllowed; } //Scenario is not marked with KSPScenario - let's load it anyway. return true; } public void SendScenarioModules(bool highPriority) { List<string> scenarioName = new List<string>(); List<byte[]> scenarioData = new List<byte[]>(); foreach (ScenarioModule sm in ScenarioRunner.GetLoadedModules()) { string scenarioType = sm.GetType().Name; if (!IsScenarioModuleAllowed(scenarioType)) { continue; } ConfigNode scenarioNode = new ConfigNode(); sm.Save(scenarioNode); byte[] scenarioBytes = configNodeSerializer.Serialize(scenarioNode); string scenarioHash = Common.CalculateSHA256Hash(scenarioBytes); if (scenarioBytes.Length == 0) { DarkLog.Debug("Error writing scenario data for " + scenarioType); continue; } if (checkData.ContainsKey(scenarioType) ? (checkData[scenarioType] == scenarioHash) : false) { //Data is the same since last time - Skip it. continue; } else { checkData[scenarioType] = scenarioHash; } if (scenarioBytes != null) { scenarioName.Add(scenarioType); scenarioData.Add(scenarioBytes); } } if (scenarioName.Count > 0) { if (highPriority) { networkWorker.SendScenarioModuleDataHighPriority(scenarioName.ToArray(), scenarioData.ToArray()); } else { networkWorker.SendScenarioModuleData(scenarioName.ToArray(), scenarioData.ToArray()); } } } public void LoadScenarioDataIntoGame() { while (scenarioQueue.Count > 0) { ScenarioEntry scenarioEntry = scenarioQueue.Dequeue(); if (scenarioEntry.scenarioName == "ProgressTracking") { CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(scenarioEntry.scenarioNode); } CheckForBlankSceneSoTheGameDoesntBugOut(scenarioEntry); ProtoScenarioModule psm = new ProtoScenarioModule(scenarioEntry.scenarioNode); if (psm != null) { if (IsScenarioModuleAllowed(psm.moduleName)) { DarkLog.Debug("Loading " + psm.moduleName + " scenario data"); HighLogic.CurrentGame.scenarios.Add(psm); } else { DarkLog.Debug("Skipping " + psm.moduleName + " scenario data in " + dmpGame.gameMode + " mode"); } } } } private ConfigNode CreateProcessedPartNode(string part, uint id, params ProtoCrewMember[] crew) { ConfigNode configNode = ProtoVessel.CreatePartNode(part, id, crew); if (part != "kerbalEVA") { ConfigNode[] nodes = configNode.GetNodes("RESOURCE"); for (int i = 0; i < nodes.Length; i++) { ConfigNode configNode2 = nodes[i]; if (configNode2.HasValue("amount")) { configNode2.SetValue("amount", 0.ToString(System.Globalization.CultureInfo.InvariantCulture), false); } } } configNode.SetValue("flag", "Squad/Flags/default", true); return configNode; } //Defends against bug #172 private void CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(ConfigNode progressTrackingNode) { foreach (ConfigNode possibleNode in progressTrackingNode.nodes) { //Recursion (noun): See Recursion. CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(possibleNode); } //The kerbals are kept in a ConfigNode named 'crew', with 'crews' as a comma space delimited array of names. if (progressTrackingNode.name == "crew") { string kerbalNames = progressTrackingNode.GetValue("crews"); if (!String.IsNullOrEmpty(kerbalNames)) { string[] kerbalNamesSplit = kerbalNames.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); foreach (string kerbalName in kerbalNamesSplit) { if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName)) { DarkLog.Debug("Generating missing kerbal from ProgressTracking: " + kerbalName); ProtoCrewMember pcm = CrewGenerator.RandomCrewMemberPrototype(ProtoCrewMember.KerbalType.Crew); pcm.ChangeName(kerbalName); HighLogic.CurrentGame.CrewRoster.AddCrewMember(pcm); //Also send it off to the server vesselWorker.SendKerbalIfDifferent(pcm); } } } } } //If the scene field is blank, KSP will throw an error while starting the game, meaning players will be unable to join the server. private void CheckForBlankSceneSoTheGameDoesntBugOut(ScenarioEntry scenarioEntry) { if (scenarioEntry.scenarioNode.GetValue("scene") == string.Empty) { string nodeName = scenarioEntry.scenarioName; ScreenMessages.PostScreenMessage(nodeName + " is badly behaved!"); DarkLog.Debug(nodeName + " is badly behaved!"); scenarioEntry.scenarioNode.SetValue("scene", "7, 8, 5, 6, 9"); } } public void UpgradeTheAstronautComplexSoTheGameDoesntBugOut() { ProtoScenarioModule sm = HighLogic.CurrentGame.scenarios.Find(psm => psm.moduleName == "ScenarioUpgradeableFacilities"); if (sm != null) { if (ScenarioUpgradeableFacilities.protoUpgradeables.ContainsKey("SpaceCenter/AstronautComplex")) { foreach (Upgradeables.UpgradeableFacility uf in ScenarioUpgradeableFacilities.protoUpgradeables["SpaceCenter/AstronautComplex"].facilityRefs) { DarkLog.Debug("Setting astronaut complex to max level"); uf.SetLevel(uf.MaxLevel); } } } } public void LoadMissingScenarioDataIntoGame() { List<KSPScenarioType> validScenarios = KSPScenarioType.GetAllScenarioTypesInAssemblies(); foreach (KSPScenarioType validScenario in validScenarios) { if (HighLogic.CurrentGame.scenarios.Exists(psm => psm.moduleName == validScenario.ModuleType.Name)) { continue; } bool loadModule = false; if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER) { loadModule = validScenario.ScenarioAttributes.HasCreateOption(ScenarioCreationOptions.AddToNewCareerGames); } if (HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX) { loadModule = validScenario.ScenarioAttributes.HasCreateOption(ScenarioCreationOptions.AddToNewScienceSandboxGames); } if (HighLogic.CurrentGame.Mode == Game.Modes.SANDBOX) { loadModule = validScenario.ScenarioAttributes.HasCreateOption(ScenarioCreationOptions.AddToNewSandboxGames); } if (loadModule) { DarkLog.Debug("Creating new scenario module " + validScenario.ModuleType.Name); HighLogic.CurrentGame.AddProtoScenarioModule(validScenario.ModuleType, validScenario.ScenarioAttributes.TargetScenes); } } } public void LoadScenarioData(ScenarioEntry entry) { if (!IsScenarioModuleAllowed(entry.scenarioName)) { DarkLog.Debug("Skipped '" + entry.scenarioName + "' scenario data in " + dmpGame.gameMode + " mode"); return; } //Load data from DMP if (entry.scenarioNode == null) { DarkLog.Debug(entry.scenarioName + " scenario data failed to create a ConfigNode!"); blockScenarioDataSends = true; return; } //Load data into game bool loaded = false; foreach (ProtoScenarioModule psm in HighLogic.CurrentGame.scenarios) { if (psm.moduleName == entry.scenarioName) { DarkLog.Debug("Loading existing " + entry.scenarioName + " scenario module"); try { if (psm.moduleRef == null) { DarkLog.Debug("Fixing null scenario module!"); psm.moduleRef = new ScenarioModule(); } psm.moduleRef.Load(entry.scenarioNode); } catch (Exception e) { DarkLog.Debug("Error loading " + entry.scenarioName + " scenario module, Exception: " + e); blockScenarioDataSends = true; } loaded = true; } } if (!loaded) { DarkLog.Debug("Loading new " + entry.scenarioName + " scenario module"); LoadNewScenarioData(entry.scenarioNode); } } public void LoadNewScenarioData(ConfigNode newScenarioData) { ProtoScenarioModule newModule = new ProtoScenarioModule(newScenarioData); try { HighLogic.CurrentGame.scenarios.Add(newModule); newModule.Load(ScenarioRunner.Instance); } catch { DarkLog.Debug("Error loading scenario data!"); blockScenarioDataSends = true; } } public void QueueScenarioData(string scenarioName, ConfigNode scenarioData) { ScenarioEntry entry = new ScenarioEntry(); entry.scenarioName = scenarioName; entry.scenarioNode = scenarioData; scenarioQueue.Enqueue(entry); } public void Stop() { workerEnabled = false; dmpGame.updateEvent.Remove(Update); } } public class ScenarioEntry { public string scenarioName; public ConfigNode scenarioNode; } }