context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Versioning; using Microsoft.Internal.Web.Utils; namespace NuGet { public static class PackageExtensions { private const string TagsProperty = "Tags"; private static readonly string[] _packagePropertiesToSearch = new[] { "Id", "Description", TagsProperty }; public static bool IsReleaseVersion(this IPackageMetadata packageMetadata) { return String.IsNullOrEmpty(packageMetadata.Version.SpecialVersion); } public static bool IsListed(this IPackage package) { return package.Listed || package.Published > Constants.Unpublished; } public static IEnumerable<IPackage> FindByVersion(this IEnumerable<IPackage> source, IVersionSpec versionSpec) { if (versionSpec == null) { throw new ArgumentNullException("versionSpec"); } return source.Where(versionSpec.ToDelegate()); } public static IEnumerable<IPackageFile> GetFiles(this IPackage package, string directory) { return package.GetFiles().Where(file => file.Path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)); } public static IEnumerable<IPackageFile> GetContentFiles(this IPackage package) { return package.GetFiles(Constants.ContentDirectory); } public static IEnumerable<PackageIssue> Validate(this IPackage package, IEnumerable<IPackageRule> rules) { if (package == null) { return null; } if (rules == null) { throw new ArgumentNullException("rules"); } return rules.Where(r => r != null).SelectMany(r => r.Validate(package)); } public static string GetHash(this IPackage package, string hashAlgorithm) { return GetHash(package, new CryptoHashProvider(hashAlgorithm)); } public static string GetHash(this IPackage package, IHashProvider hashProvider) { using (Stream stream = package.GetStream()) { byte[] packageBytes = stream.ReadAllBytes(); return Convert.ToBase64String(hashProvider.CalculateHash(packageBytes)); } } /// <summary> /// Returns true if a package has no content that applies to a project. /// </summary> public static bool HasProjectContent(this IPackage package) { return package.FrameworkAssemblies.Any() || package.AssemblyReferences.Any() || package.GetContentFiles().Any(); } public static IEnumerable<FrameworkName> GetSupportedFrameworks(this IPackage package) { return package.FrameworkAssemblies .SelectMany(a => a.SupportedFrameworks) .Concat(package.AssemblyReferences.SelectMany(a => a.SupportedFrameworks)) .Distinct(); } /// <summary> /// Returns true if a package has dependencies but no files. /// </summary> public static bool IsDependencyOnly(this IPackage package) { return !package.GetFiles().Any() && package.Dependencies.Any(); } public static string GetFullName(this IPackageMetadata package) { return package.Id + " " + package.Version; } /// <summary> /// Calculates the canonical list of operations. /// </summary> internal static IEnumerable<PackageOperation> Reduce(this IEnumerable<PackageOperation> operations) { // Convert the list of operations to a dictionary from (Action, Id, Version) -> [Operations] // We keep track of the index so that we preserve the ordering of the operations var operationLookup = operations.Select((o, index) => new { Operation = o, Index = index }) .ToLookup(o => GetOperationKey(o.Operation)) .ToDictionary(g => g.Key, g => g.ToList()); // Given a list of operations we're going to eliminate the ones that have opposites (i.e. // if the list contains +A 1.0 and -A 1.0, then we eliminate them both entries). foreach (var operation in operations) { // We get the opposing operation for the current operation: // if o is +A 1.0 then the opposing key is - A 1.0 Tuple<PackageAction, string, SemanticVersion> opposingKey = GetOpposingOperationKey(operation); // We can't use TryGetValue since the value of the dictionary entry // is a List of an anonymous type. if (operationLookup.ContainsKey(opposingKey)) { // If we find an opposing entry, we remove it from the list of candidates var opposingOperations = operationLookup[opposingKey]; opposingOperations.RemoveAt(0); // Remove the list from the dictionary if nothing is in it if (!opposingOperations.Any()) { operationLookup.Remove(opposingKey); } } } // Create the final list of operations and order them by their original index return operationLookup.SelectMany(o => o.Value) .OrderBy(o => o.Index) .Select(o => o.Operation); } private static Tuple<PackageAction, string, SemanticVersion> GetOperationKey(PackageOperation operation) { return Tuple.Create(operation.Action, operation.Package.Id, operation.Package.Version); } private static Tuple<PackageAction, string, SemanticVersion> GetOpposingOperationKey(PackageOperation operation) { return Tuple.Create(operation.Action == PackageAction.Install ? PackageAction.Uninstall : PackageAction.Install, operation.Package.Id, operation.Package.Version); } /// <summary> /// Returns a distinct set of elements using the comparer specified. This implementation will pick the last occurrence /// of each element instead of picking the first. This method assumes that similar items occur in order. /// </summary> public static IEnumerable<IPackage> AsCollapsed(this IEnumerable<IPackage> source) { return source.DistinctLast(PackageEqualityComparer.Id, PackageComparer.Version); } public static IQueryable<IPackage> FilterByPrerelease(this IQueryable<IPackage> packages, bool allowPrerelease) { if (packages == null) { return null; } if (!allowPrerelease) { packages = packages.Where(p => p.IsReleaseVersion()); } return packages; } /// <summary> /// Returns packages where the search text appears in the default set of properties to search. The default set includes Id, Description and Tags. /// </summary> public static IQueryable<T> Find<T>(this IQueryable<T> packages, string searchText) where T : IPackage { return Find(packages, _packagePropertiesToSearch, searchText); } /// <summary> /// Returns packages where the search text appears in any of the properties to search. /// Note that not all properties can be successfully queried via this method particularly over a OData feed. Verify indepedently if it works for the properties that need to be searched. /// </summary> public static IQueryable<T> Find<T>(this IQueryable<T> packages, IEnumerable<string> propertiesToSearch, string searchText) where T : IPackage { if (propertiesToSearch.IsEmpty()) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "propertiesToSearch"); } if (String.IsNullOrEmpty(searchText)) { return packages; } return Find(packages, propertiesToSearch, searchText.Split()); } private static IQueryable<T> Find<T>(this IQueryable<T> packages, IEnumerable<string> propertiesToSearch, IEnumerable<string> searchTerms) where T : IPackage { if (!searchTerms.Any()) { return packages; } IEnumerable<string> nonNullTerms = searchTerms.Where(s => s != null); if (!nonNullTerms.Any()) { return packages; } return packages.Where(BuildSearchExpression<T>(propertiesToSearch, nonNullTerms)); } /// <summary> /// Constructs an expression to search for individual tokens in a search term in the Id and Description of packages /// </summary> private static Expression<Func<T, bool>> BuildSearchExpression<T>(IEnumerable<string> propertiesToSearch, IEnumerable<string> searchTerms) where T : IPackage { Debug.Assert(searchTerms != null); var parameterExpression = Expression.Parameter(typeof(IPackageMetadata)); // package.Id.ToLower().Contains(term1) || package.Id.ToLower().Contains(term2) ... Expression condition = (from term in searchTerms from property in propertiesToSearch select BuildExpressionForTerm(parameterExpression, term, property)).Aggregate(Expression.OrElse); return Expression.Lambda<Func<T, bool>>(condition, parameterExpression); } [SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "The expression is remoted using Odata which does not support the culture parameter")] private static Expression BuildExpressionForTerm(ParameterExpression packageParameterExpression, string term, string propertyName) { // For tags we want to prepend and append spaces to do an exact match if (propertyName.Equals(TagsProperty, StringComparison.OrdinalIgnoreCase)) { term = " " + term + " "; } MethodInfo stringContains = typeof(String).GetMethod("Contains", new Type[] { typeof(string) }); MethodInfo stringToLower = typeof(String).GetMethod("ToLower", Type.EmptyTypes); // package.Id / package.Description var propertyExpression = Expression.Property(packageParameterExpression, propertyName); // .ToLower() var toLowerExpression = Expression.Call(propertyExpression, stringToLower); // Handle potentially null properties // package.{propertyName} != null && package.{propertyName}.ToLower().Contains(term.ToLower()) return Expression.AndAlso(Expression.NotEqual(propertyExpression, Expression.Constant(null)), Expression.Call(toLowerExpression, stringContains, Expression.Constant(term.ToLower()))); } } }
// 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.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Microsoft.CSharp.RuntimeBinder { internal static class RuntimeBinderExtensions { public static bool IsEquivalentTo(this Type t1, Type t2) { return t1 == t2; } public static bool IsNullableType(this Type type) { return type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } public static TypeCode GetTypeCode(this Type type) { if (type == null) return TypeCode.Empty; else if (type == typeof(bool)) return TypeCode.Boolean; else if (type == typeof(char)) return TypeCode.Char; else if (type == typeof(sbyte)) return TypeCode.SByte; else if (type == typeof(byte)) return TypeCode.Byte; else if (type == typeof(short)) return TypeCode.Int16; else if (type == typeof(ushort)) return TypeCode.UInt16; else if (type == typeof(int)) return TypeCode.Int32; else if (type == typeof(uint)) return TypeCode.UInt32; else if (type == typeof(long)) return TypeCode.Int64; else if (type == typeof(ulong)) return TypeCode.UInt64; else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(decimal)) return TypeCode.Decimal; else if (type == typeof(System.DateTime)) return TypeCode.DateTime; else if (type == typeof(string)) return TypeCode.String; else if (type.GetTypeInfo().IsEnum) return GetTypeCode(Enum.GetUnderlyingType(type)); else return TypeCode.Object; } // This method is intended as a means to detect when MemberInfos are the same, // modulo the fact that they can appear to have different but equivalent local // No-PIA types. It is by the symbol table to determine whether // or not members have been added to an AggSym or not. public static bool IsEquivalentTo(this MemberInfo mi1, MemberInfo mi2) { if (mi1 == null || mi2 == null) { return mi1 == null && mi2 == null; } #if UNSUPPORTEDAPI if (mi1 == mi2 || (mi1.DeclaringType.IsGenericallyEqual(mi2.DeclaringType) && mi1.MetadataToken == mi2.MetadataToken)) #else if (mi1.Equals(mi2)) #endif { return true; } if (mi1 is MethodInfo && mi2 is MethodInfo) { MethodInfo method1 = mi1 as MethodInfo; MethodInfo method2 = mi2 as MethodInfo; ParameterInfo[] pis1; ParameterInfo[] pis2; if (method1.IsGenericMethod != method2.IsGenericMethod) { return false; } if (method1.IsGenericMethod) { method1 = method1.GetGenericMethodDefinition(); method2 = method2.GetGenericMethodDefinition(); if (method1.GetGenericArguments().Length != method2.GetGenericArguments().Length) { return false; // Methods of different arity are not equivalent. } } return method1 != method2 && method1.Name == method2.Name && method1.DeclaringType.IsGenericallyEqual(method2.DeclaringType) && method1.ReturnType.IsGenericallyEquivalentTo(method2.ReturnType, method1, method2) && (pis1 = method1.GetParameters()).Length == (pis2 = method2.GetParameters()).Length && Enumerable.All(Enumerable.Zip(pis1, pis2, (pi1, pi2) => pi1.IsEquivalentTo(pi2, method1, method2)), x => x); } if (mi1 is ConstructorInfo && mi2 is ConstructorInfo) { ConstructorInfo ctor1 = mi1 as ConstructorInfo; ConstructorInfo ctor2 = mi2 as ConstructorInfo; ParameterInfo[] pis1; ParameterInfo[] pis2; return ctor1 != ctor2 && ctor1.DeclaringType.IsGenericallyEqual(ctor2.DeclaringType) && (pis1 = ctor1.GetParameters()).Length == (pis2 = ctor2.GetParameters()).Length && Enumerable.All(Enumerable.Zip(pis1, pis2, (pi1, pi2) => pi1.IsEquivalentTo(pi2, ctor1, ctor2)), x => x); } if (mi1 is PropertyInfo && mi2 is PropertyInfo) { PropertyInfo prop1 = mi1 as PropertyInfo; PropertyInfo prop2 = mi2 as PropertyInfo; return prop1 != prop2 && prop1.Name == prop2.Name && prop1.DeclaringType.IsGenericallyEqual(prop2.DeclaringType) && prop1.PropertyType.IsGenericallyEquivalentTo(prop2.PropertyType, prop1, prop2) && prop1.GetGetMethod(true).IsEquivalentTo(prop2.GetGetMethod(true)) && prop1.GetSetMethod(true).IsEquivalentTo(prop2.GetSetMethod(true)); } return false; } private static bool IsEquivalentTo(this ParameterInfo pi1, ParameterInfo pi2, MethodBase method1, MethodBase method2) { if (pi1 == null || pi2 == null) { return pi1 == null && pi2 == null; } if (pi1.Equals(pi2)) { return true; } return pi1.ParameterType.IsGenericallyEquivalentTo(pi2.ParameterType, method1, method2); } private static bool IsGenericallyEqual(this Type t1, Type t2) { if (t1 == null || t2 == null) { return t1 == null && t2 == null; } if (t1.Equals(t2)) { return true; } if (t1.IsConstructedGenericType || t2.IsConstructedGenericType) { Type t1def = t1.IsConstructedGenericType ? t1.GetGenericTypeDefinition() : t1; Type t2def = t2.IsConstructedGenericType ? t2.GetGenericTypeDefinition() : t2; return t1def.Equals(t2def); } return false; } // Compares two types and calls them equivalent if a type parameter equals a type argument. // i.e if the inputs are (T, int, C<T>, C<int>) then this will return true. private static bool IsGenericallyEquivalentTo(this Type t1, Type t2, MemberInfo member1, MemberInfo member2) { Debug.Assert(!(member1 is MethodBase) || !((MethodBase)member1).IsGenericMethod || (((MethodBase)member1).IsGenericMethodDefinition && ((MethodBase)member2).IsGenericMethodDefinition)); if (t1.Equals(t2)) { return true; } // If one of them is a type param and then the other is a real type, then get the type argument in the member // or it's declaring type that corresponds to the type param and compare that to the other type. if (t1.IsGenericParameter) { if (t2.IsGenericParameter) { // If member's declaring type is not type parameter's declaring type, we assume that it is used as a type argument if (t1.GetTypeInfo().DeclaringMethod == null && member1.DeclaringType.Equals(t1.GetTypeInfo().DeclaringType)) { if (!(t2.GetTypeInfo().DeclaringMethod == null && member2.DeclaringType.Equals(t2.GetTypeInfo().DeclaringType))) { return t1.IsTypeParameterEquivalentToTypeInst(t2, member2); } } else if (t2.GetTypeInfo().DeclaringMethod == null && member2.DeclaringType.Equals(t2.GetTypeInfo().DeclaringType)) { return t2.IsTypeParameterEquivalentToTypeInst(t1, member1); } // If both of these are type params but didn't compare to be equal then one of them is likely bound to another // open type. Simply disallow such cases. return false; } return t1.IsTypeParameterEquivalentToTypeInst(t2, member2); } else if (t2.IsGenericParameter) { return t2.IsTypeParameterEquivalentToTypeInst(t1, member1); } // Recurse in for generic types arrays, byref and pointer types. if (t1.GetTypeInfo().IsGenericType && t2.GetTypeInfo().IsGenericType) { var args1 = t1.GetGenericArguments(); var args2 = t2.GetGenericArguments(); if (args1.Length == args2.Length) { return t1.IsGenericallyEqual(t2) && Enumerable.All(Enumerable.Zip(args1, args2, (ta1, ta2) => ta1.IsGenericallyEquivalentTo(ta2, member1, member2)), x => x); } } if (t1.IsArray && t2.IsArray) { return t1.GetArrayRank() == t2.GetArrayRank() && t1.GetElementType().IsGenericallyEquivalentTo(t2.GetElementType(), member1, member2); } if ((t1.IsByRef && t2.IsByRef) || (t1.IsPointer && t2.IsPointer)) { return t1.GetElementType().IsGenericallyEquivalentTo(t2.GetElementType(), member1, member2); } return false; } private static bool IsTypeParameterEquivalentToTypeInst(this Type typeParam, Type typeInst, MemberInfo member) { Debug.Assert(typeParam.IsGenericParameter); if (typeParam.GetTypeInfo().DeclaringMethod != null) { // The type param is from a generic method. Since only methods can be generic, anything else // here means they are not equivalent. if (!(member is MethodBase)) { return false; } MethodBase method = (MethodBase)member; int position = typeParam.GetTypeInfo().GenericParameterPosition; Type[] args = method.IsGenericMethod ? method.GetGenericArguments() : null; return args != null && args.Length > position && args[position].Equals(typeInst); } else { return member.DeclaringType.GetGenericArguments()[typeParam.GetTypeInfo().GenericParameterPosition].Equals(typeInst); } } // s_MemberEquivalence will replace itself with one version or another // depending on what works at run time private static Func<MemberInfo, MemberInfo, bool> s_MemberEquivalence = (m1, m2) => { try { // See if MetadataToken property is available. Type memberInfo = typeof(MemberInfo); PropertyInfo property = memberInfo.GetProperty("MetadataToken", typeof(int), Array.Empty<Type>()); if ((object)property != null && property.CanRead) { // (parameter1, parameter2) => parameter1.MetadataToken == parameter2.MetadataToken var parameter1 = Expression.Parameter(memberInfo); var parameter2 = Expression.Parameter(memberInfo); var memberEquivalence = Expression.Lambda<Func<MemberInfo, MemberInfo, bool>>( Expression.Equal( Expression.Property(parameter1, property), Expression.Property(parameter2, property)), new[] { parameter1, parameter2 }).Compile(); var result = memberEquivalence(m1, m2); // it worked, so publish it s_MemberEquivalence = memberEquivalence; return result; } } catch { // Platform might not allow access to the property } // MetadataToken is not available in some contexts. Looks like this is one of those cases. // fallback to "IsEquivalentTo" Func<MemberInfo, MemberInfo, bool> fallbackMemberEquivalence = (m1param, m2param) => m1param.IsEquivalentTo(m2param); // fallback must work s_MemberEquivalence = fallbackMemberEquivalence; return fallbackMemberEquivalence(m1, m2); }; public static bool HasSameMetadataDefinitionAs(this MemberInfo mi1, MemberInfo mi2) { #if UNSUPPORTEDAPI return (mi1.MetadataToken == mi2.MetadataToken) && (mi1.Module == mi2.Module)); #else return mi1.Module.Equals(mi2.Module) && s_MemberEquivalence(mi1, mi2); #endif } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Globalization; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class is an external representation of engine communication with the TEM or child nodes. /// </summary> internal class EngineCallback : IEngineCallback { #region Constructors /// <summary> /// Creates a callback class. There should only be one callback per engine under normal /// circumstances. /// </summary> internal EngineCallback(Engine parentEngine) { this.parentEngine = parentEngine; } #endregion #region Methods for accessing engine internals from the node /// <summary> /// This method is called by the node to request evaluation of a target that was /// requested by a task via IBuildEngine interface. It posts the /// request into a queue in the engine /// </summary> /// <param name="buildRequests"></param> public void PostBuildRequestsToHost(BuildRequest[] buildRequests) { if (buildRequests.Length > 0) { // We can safely assume that all requests need to be routed to the same engine because // they originated from the same task for(int i = 0; i < buildRequests.Length; i++) { ProcessBuildRequest(buildRequests[i]); } parentEngine.PostBuildRequests(buildRequests); } } /// <summary> /// Called on the main node only. /// </summary> public Exception PostCacheEntriesToHost(int nodeId, CacheEntry[] entries, string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType) { try { parentEngine.CacheManager.SetCacheEntries(entries, scopeName, scopeProperties, scopeToolsVersion, cacheContentType); } catch (InvalidOperationException e) { return e; } return null; } /// <summary> /// Called on the main node only. /// </summary> public CacheEntry[] GetCachedEntriesFromHost(int nodeId, string[] names, string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType) { return parentEngine.CacheManager.GetCacheEntries(names, scopeName, scopeProperties, scopeToolsVersion, cacheContentType); } private void ProcessBuildRequest(BuildRequest buildRequest) { ExecutionContext executionContext = GetExecutionContextFromHandleId(buildRequest.HandleId); // Restore the requests non-serialized data to the correct state buildRequest.RestoreNonSerializedDefaults(); buildRequest.NodeIndex = executionContext.NodeIndex; ErrorUtilities.VerifyThrow(buildRequest.ParentBuildEventContext != null, "Should not have a null parentBuildEventContext"); ErrorUtilities.VerifyThrow(buildRequest.IsGeneratedRequest, "Should not be sending a non generated request from the child node to the parent node"); // For buildRequests originating from the TEM - additional initialization is necessary TaskExecutionContext taskExecutionContext = executionContext as TaskExecutionContext; if (taskExecutionContext != null) { Project parentProject = taskExecutionContext.ParentProject; buildRequest.ParentHandleId = taskExecutionContext.TriggeringBuildRequest.HandleId; buildRequest.ParentRequestId = taskExecutionContext.TriggeringBuildRequest.RequestId; if (buildRequest.ToolsetVersion == null && parentProject.OverridingToolsVersion) { // If the MSBuild task (or whatever) didn't give us a specific tools version, // but the parent project is using an overridden tools version, then use that one buildRequest.ToolsetVersion = parentProject.ToolsVersion; } try { if (buildRequest.GlobalProperties == null) { try { // Make sure we have a blank global properties because if there is a problem merging them we wont have a crash when we try and cache the build result. buildRequest.GlobalProperties = new BuildPropertyGroup(); buildRequest.GlobalProperties = parentEngine.MergeGlobalProperties(parentProject.GlobalProperties, null, buildRequest.ProjectFileName, buildRequest.GlobalPropertiesPassedByTask); } catch (ArgumentException e) { ConvertToInvalidProjectException(buildRequest, parentProject, e); } catch (InvalidOperationException e) { ConvertToInvalidProjectException(buildRequest, parentProject, e); } } // We need to figure out which project object this request is refering to if (buildRequest.ProjectFileName == null) { ErrorUtilities.VerifyThrow(parentProject != null, "Parent project must be non-null"); // This means the caller (the MSBuild task) wants us to use the same project as the calling // project. This allows people to avoid passing in the Projects parameter on the MSBuild task. Project projectToBuild = parentProject; // If the parent project (the calling project) already has the same set of global properties // as what is being requested, just re-use it. Otherwise, we need to instantiate a new // project object that has the same project contents but different global properties. if (!projectToBuild.GlobalProperties.IsEquivalent(buildRequest.GlobalProperties) && (String.Equals(parentProject.ToolsVersion, buildRequest.ToolsetVersion, StringComparison.OrdinalIgnoreCase))) { projectToBuild = parentEngine.GetMatchingProject(parentProject, parentProject.FullFileName, buildRequest.GlobalProperties, buildRequest.ToolsetVersion, buildRequest.TargetNames, buildRequest.ParentBuildEventContext, buildRequest.ToolsVersionPeekedFromProjectFile); } buildRequest.ProjectToBuild = projectToBuild; buildRequest.ProjectFileName = projectToBuild.FullFileName; buildRequest.FireProjectStartedFinishedEvents = false; } } catch (InvalidProjectFileException e) { buildRequest.BuildCompleted = true; // Store message so it can be logged by the engine build loop buildRequest.BuildException = e; } } else { RequestRoutingContext requestRoutingContext = executionContext as RequestRoutingContext; buildRequest.ParentHandleId = requestRoutingContext.ParentHandleId; buildRequest.ParentRequestId = requestRoutingContext.ParentRequestId; } } /// <summary> /// If there is an exception in process build request we will wrap it in an invalid project file exception as any exceptions caught here are really problems with a project file /// this exception will be handled in the engine and logged /// </summary> private static void ConvertToInvalidProjectException(BuildRequest buildRequest, Project parentProject, Exception e) { BuildEventFileInfo fileInfo = new BuildEventFileInfo(buildRequest.ProjectFileName); throw new InvalidProjectFileException(parentProject.FullFileName, fileInfo.Line, fileInfo.Column, fileInfo.EndLine, fileInfo.EndColumn, e.Message, null, null, null); } /// <summary> /// This method is used by the node to post the task outputs to the engine. /// Items and properties output by the task return to the engine thread via the Lookup the /// TaskEngine was passed, not via posting to the queue here. /// </summary> internal void PostTaskOutputs ( int handleId, bool taskExecutedSuccessfully, Exception thrownException, long executionTime ) { TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId); // Set the outputs on the context executionContext.SetTaskOutputs(taskExecutedSuccessfully, thrownException, executionTime); // Submit it to the queue parentEngine.PostTaskOutputUpdates(executionContext); } /// <summary> /// This method is used by the child node to post results of a build request back to the /// parent node. The parent node then decides if need to re-route the results to another node /// that requested the evaluation or if it will consume the result locally /// </summary> /// <param name="buildResult"></param> public void PostBuildResultToHost(BuildResult buildResult) { RequestRoutingContext routingContext = GetRoutingContextFromHandleId(buildResult.HandleId); ErrorUtilities.VerifyThrow(routingContext.CacheScope != null, "Cache scope should be created for this context"); // Cache the results routingContext.CacheScope.AddCacheEntryForBuildResults(buildResult); if (Engine.debugMode) { Console.WriteLine("Received result for HandleId " + buildResult.HandleId + ":" + buildResult.RequestId + " mapped to " + routingContext.ParentHandleId + ":" + routingContext.ParentRequestId); } // Update the results with the original handle id and request id, so that buildResult.HandleId = routingContext.ParentHandleId; // If the build result is created from a generated build request a done notice should be posted as other targets could be waiting for this target to finish if (buildResult.HandleId != invalidEngineHandle) { buildResult.RequestId = routingContext.ParentRequestId; parentEngine.Router.PostDoneNotice(routingContext.ParentNodeIndex, buildResult); } else // The build results need to be stored into the build request so they can be sent back to the host that requested the build { routingContext.TriggeringBuildRequest.OutputsByTarget = buildResult.OutputsByTarget; routingContext.TriggeringBuildRequest.BuildSucceeded = buildResult.EvaluationResult; routingContext.TriggeringBuildRequest.BuildCompleted = true; parentEngine.PostEngineCommand(new HostBuildRequestCompletionEngineCommand()); } // At this point the execution context we created for the execution of this build request can be deleted lock (freedContexts) { freedContexts.Add(routingContext); } } /// <summary> /// Called either on the main or child node. This is the routing method for setting cache entries. /// </summary> public void SetCacheEntries ( int handleId, CacheEntry[] entries, string cacheScope, string cacheKey, string cacheVersion, CacheContentType cacheContentType, bool localNodeOnly ) { TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId); BuildPropertyGroup scopeProperties; if (cacheKey == null) { Project parentProject = executionContext.ParentProject; scopeProperties = parentProject.GlobalProperties; } else { // Property values are compared using case sensitive comparisons because the case of property values do have meaning. // In this case we are using properties in a manner where we do not want case sensitive comparisons. // There is not enough benefit for this one special case to add case insensitive // comparisons to build properties. We instead uppercase all of the keys for both get and set CachedEntries. scopeProperties = new BuildPropertyGroup(); scopeProperties.SetProperty("CacheKey", cacheKey.ToUpper(CultureInfo.InvariantCulture)); } if (cacheScope == null) { cacheScope = executionContext.ParentProject.FullFileName; } if (cacheVersion == null) { cacheVersion = executionContext.ParentProject.ToolsVersion; } parentEngine.CacheManager.SetCacheEntries(entries, cacheScope, scopeProperties, cacheVersion, cacheContentType); // Also send these to the parent if we're allowed to if (parentEngine.Router.ChildMode && !localNodeOnly) { Exception exception = parentEngine.Router.ParentNode.PostCacheEntriesToHost(entries, cacheScope, scopeProperties, cacheVersion, cacheContentType); // If we had problems on the parent node, rethrow the exception here if (exception != null) { throw exception; } } } /// <summary> /// Called either on the main or child node. This is the routing method for getting cache entries. /// </summary> public CacheEntry[] GetCacheEntries ( int handleId, string[] names, string cacheScope, string cacheKey, string cacheVersion, CacheContentType cacheContentType, bool localNodeOnly ) { TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId); BuildPropertyGroup scopeProperties; if (cacheKey == null) { Project parentProject = executionContext.ParentProject; scopeProperties = parentProject.GlobalProperties; } else { // Property values are compared using case sensitive comparisons because the case of property values do have meaning. // In this case we are using properties in a manner where we do not want case sensitive comparisons. // There is not enough benefit for this one special case to add case insensitive // comparisons to build properties. We instead uppercase all of the keys for both get and set CachedEntries. scopeProperties = new BuildPropertyGroup(); scopeProperties.SetProperty("CacheKey", cacheKey.ToUpper(CultureInfo.InvariantCulture)); } if (cacheScope == null) { cacheScope = executionContext.ParentProject.FullFileName; } if (cacheVersion == null) { cacheVersion = executionContext.ParentProject.ToolsVersion; } CacheEntry[] result = parentEngine.CacheManager.GetCacheEntries(names, cacheScope, scopeProperties, cacheVersion, cacheContentType); bool haveCompleteResult = (result.Length == names.Length); if (haveCompleteResult) { for (int i = 0; i < result.Length; i++) { if (result[i] == null) { haveCompleteResult = false; break; } } } // If we didn't have the complete result locally, check with the parent if allowed. if (!haveCompleteResult && parentEngine.Router.ChildMode && !localNodeOnly) { result = parentEngine.Router.ParentNode.GetCachedEntriesFromHost(names, cacheScope, scopeProperties, cacheVersion, cacheContentType); parentEngine.CacheManager.SetCacheEntries(result, cacheScope, scopeProperties, cacheVersion, cacheContentType); } return result; } /// <summary> /// Submit the logging message to the engine queue. Note that we are currently not utilizing the /// handleId, but plan to do so in the future to fill out the data structure passed to the engine /// </summary> public void PostLoggingMessagesToHost(int nodeId, NodeLoggingEvent[] nodeLoggingEventArray) { // We can safely assume that all messages need to be routed to the same engine because // they originated from the same task. This is true as long as we don't allow multiple engines within // a single process to utilize external nodes. if (nodeLoggingEventArray.Length > 0) { parentEngine.LoggingServices.PostLoggingEvents(nodeLoggingEventArray); } } /// <summary> /// Figure out the line and column number of the task XML node in the original /// project context /// </summary> internal void GetLineColumnOfXmlNode(int handleId, out int lineNumber, out int columnNumber) { TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId); XmlSearcher.GetLineColumnByNode(executionContext.TaskNode, out lineNumber, out columnNumber); } /// <summary> /// Gets the default engine task registry. If the TEM runs out-of proc with the engine we should send the task declarations for all the default tasks parsed out of the *.tasks XML instead. /// </summary> /// <returns>The default engine task registry.</returns> internal ITaskRegistry GetEngineTaskRegistry(int handleId) { TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId); return parentEngine.GetTaskRegistry(executionContext.BuildEventContext, executionContext.ParentProject.ToolsVersion); } /// <summary> /// Gets the project task registry. If the TEM runs out-of proc with the engine we should send the task declarations for all the using tasks parsed out of project XML instead. /// </summary> /// <returns>The default engine task registry.</returns> internal ITaskRegistry GetProjectTaskRegistry(int handleId) { TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId); return executionContext.ParentProject.TaskRegistry; } /// <summary> /// Get the version of the toolset used by the project /// </summary> /// <param name="handleId"></param> /// <returns></returns> internal string GetToolsPath(int handleId) { TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId); return parentEngine.ToolsetStateMap[executionContext.ParentProject.ToolsVersion].ToolsPath; } /// <summary> /// This method is called to post the status of the node /// </summary> public void PostStatus(int nodeId, NodeStatus nodeStatus, bool blockUntilSent) { parentEngine.PostNodeStatus(nodeId, nodeStatus); } /// <summary> /// This method is only used in by the inproc node /// </summary> internal Engine GetParentEngine() { return parentEngine; } /// <summary> /// This method converts a list handles to inprogress contexts into a list of target objects /// </summary> internal Target[] GetListOfTargets(int[] handleIds) { Target[] targets = new Target[handleIds.Length]; for (int i = 0; i < handleIds.Length; i++) { TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleIds[i]); if (executionContext != null) { targets[i] = executionContext.ParentTarget; } else { targets[i] = null; } } return targets; } #endregion #region Methods for managing execution contexts /// <summary> /// Given a handleId, this method returns the corresponding ExecutionContext. This /// context contains only value type data and can be used from any domain. /// </summary> internal ExecutionContext GetExecutionContextFromHandleId(int handleId) { // We don't need to lock the hashtable because it is thread safe for multiple readers return (ExecutionContext)executionContexts[handleId]; } /// <summary> /// Given a handleId, this method returns the corresponding RequestRoutingContext. This context /// contains some data (such as parent projet or parent target) which should only be accessed from /// within the engine domain. /// </summary> internal TaskExecutionContext GetTaskContextFromHandleId(int handleId) { // We don't need to lock the hashtable because it is thread safe for multiple readers return (TaskExecutionContext)executionContexts[handleId]; } /// <summary> /// Given a handleId, this method returns the corresponding RequestRoutingContext. This /// context contains only value type data and can be used from any domain /// </summary> internal RequestRoutingContext GetRoutingContextFromHandleId(int handleId) { // We don't need to lock the hashtable because it is thread safe for multiple readers return (RequestRoutingContext)executionContexts[handleId]; } /// <summary> /// This method creates a new TaskExecutionContext and return a integer token that maps to it. /// This method is not thread safe and must be called only from the engine thread. /// </summary> internal int CreateTaskContext ( Project parentProject, Target parentTarget, ProjectBuildState buildContext, XmlElement taskNode, int nodeIndex, BuildEventContext taskContext ) { int handleId = nextContextId; nextContextId++; TaskExecutionContext executionContext = new TaskExecutionContext(parentProject, parentTarget, taskNode, buildContext, handleId, nodeIndex, taskContext); executionContexts.Add(handleId, executionContext); return handleId; } /// <summary> /// This method creates a new routing context. This method is not thread safe and must be called /// only from the engine thread. /// </summary> internal int CreateRoutingContext ( int nodeIndex, int parentHandleId, int parentNodeIndex, int parentRequestId, CacheScope cacheScope, BuildRequest triggeringBuildRequest, BuildEventContext buildEventContext ) { int handleId = nextContextId; nextContextId++; RequestRoutingContext executionContext = new RequestRoutingContext(handleId, nodeIndex, parentHandleId, parentNodeIndex, parentRequestId, cacheScope, triggeringBuildRequest, buildEventContext); executionContexts.Add(handleId, executionContext); return handleId; } /// <summary> /// This method maps the given handleId to null. The entry will be later removed by the engine thread. /// </summary> internal void ClearContextState(int handleId) { if (handleId != invalidEngineHandle) { ErrorUtilities.VerifyThrow(executionContexts.ContainsKey(handleId), "The table must contain this entry"); executionContexts.Remove(handleId); } // Check if there are freed contexts waiting to be deleted if (freedContexts.Count > freeListThreshold) { lock (freedContexts) { foreach (ExecutionContext executionContext in freedContexts) { executionContexts.Remove(executionContext.HandleId); } freedContexts.Clear(); } } } #endregion #region Constants /// <summary> /// Number assigned to an invalid engine handle, This handleId is used by Buildrequests /// to show they are a routing context /// </summary> internal const int invalidEngineHandle = -1; /// <summary> /// NodeId for an inproc node /// </summary> internal const int inProcNode = 0; /// <summary> /// NodeId for the parent node /// </summary> internal const int parentNode = -1; /// <summary> /// Invalid NodeId /// </summary> internal const int invalidNode = -2; #endregion #region Data /// <summary> /// This hashtable contains the all the executionContexts for the current process /// </summary> private Hashtable executionContexts = new Hashtable(); /// <summary> /// List of contexts that should be removed from the hashtable by the engine thread /// </summary> private List<ExecutionContext> freedContexts = new List<ExecutionContext>(2*freeListThreshold); /// <summary> /// The counter used to generate unique identifiers for each context /// </summary> private int nextContextId = 0; /// <summary> /// The pointer to the engine to which this callback class corresponds /// </summary> private Engine parentEngine; /// <summary> /// The count of objects on the free list which triggers a deletion /// </summary> private const int freeListThreshold = 10; #endregion } }
using System; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Steamworks.Data; namespace Steamworks { internal unsafe class ISteamUserStats : SteamInterface { internal ISteamUserStats( bool IsGameServer ) { SetupInterface( IsGameServer ); } [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamUserStats_v012", CallingConvention = Platform.CC)] internal static extern IntPtr SteamAPI_SteamUserStats_v012(); public override IntPtr GetUserInterfacePointer() => SteamAPI_SteamUserStats_v012(); #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_RequestCurrentStats", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _RequestCurrentStats( IntPtr self ); #endregion internal bool RequestCurrentStats() { var returnValue = _RequestCurrentStats( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetStatInt32", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetStat( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref int pData ); #endregion internal bool GetStat( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref int pData ) { var returnValue = _GetStat( Self, pchName, ref pData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetStatFloat", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetStat( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref float pData ); #endregion internal bool GetStat( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref float pData ) { var returnValue = _GetStat( Self, pchName, ref pData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_SetStatInt32", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetStat( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, int nData ); #endregion internal bool SetStat( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, int nData ) { var returnValue = _SetStat( Self, pchName, nData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_SetStatFloat", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetStat( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, float fData ); #endregion internal bool SetStat( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, float fData ) { var returnValue = _SetStat( Self, pchName, fData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_UpdateAvgRateStat", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _UpdateAvgRateStat( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, float flCountThisSession, double dSessionLength ); #endregion internal bool UpdateAvgRateStat( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, float flCountThisSession, double dSessionLength ) { var returnValue = _UpdateAvgRateStat( Self, pchName, flCountThisSession, dSessionLength ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetAchievement", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetAchievement( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved ); #endregion internal bool GetAchievement( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved ) { var returnValue = _GetAchievement( Self, pchName, ref pbAchieved ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_SetAchievement", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _SetAchievement( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName ); #endregion internal bool SetAchievement( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName ) { var returnValue = _SetAchievement( Self, pchName ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_ClearAchievement", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _ClearAchievement( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName ); #endregion internal bool ClearAchievement( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName ) { var returnValue = _ClearAchievement( Self, pchName ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetAchievementAndUnlockTime", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetAchievementAndUnlockTime( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved, ref uint punUnlockTime ); #endregion internal bool GetAchievementAndUnlockTime( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved, ref uint punUnlockTime ) { var returnValue = _GetAchievementAndUnlockTime( Self, pchName, ref pbAchieved, ref punUnlockTime ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_StoreStats", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _StoreStats( IntPtr self ); #endregion internal bool StoreStats() { var returnValue = _StoreStats( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetAchievementIcon", CallingConvention = Platform.CC)] private static extern int _GetAchievementIcon( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName ); #endregion internal int GetAchievementIcon( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName ) { var returnValue = _GetAchievementIcon( Self, pchName ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetAchievementDisplayAttribute", CallingConvention = Platform.CC)] private static extern Utf8StringPointer _GetAchievementDisplayAttribute( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey ); #endregion internal string GetAchievementDisplayAttribute( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey ) { var returnValue = _GetAchievementDisplayAttribute( Self, pchName, pchKey ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_IndicateAchievementProgress", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _IndicateAchievementProgress( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, uint nCurProgress, uint nMaxProgress ); #endregion internal bool IndicateAchievementProgress( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, uint nCurProgress, uint nMaxProgress ) { var returnValue = _IndicateAchievementProgress( Self, pchName, nCurProgress, nMaxProgress ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetNumAchievements", CallingConvention = Platform.CC)] private static extern uint _GetNumAchievements( IntPtr self ); #endregion internal uint GetNumAchievements() { var returnValue = _GetNumAchievements( Self ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetAchievementName", CallingConvention = Platform.CC)] private static extern Utf8StringPointer _GetAchievementName( IntPtr self, uint iAchievement ); #endregion internal string GetAchievementName( uint iAchievement ) { var returnValue = _GetAchievementName( Self, iAchievement ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_RequestUserStats", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _RequestUserStats( IntPtr self, SteamId steamIDUser ); #endregion internal CallResult<UserStatsReceived_t> RequestUserStats( SteamId steamIDUser ) { var returnValue = _RequestUserStats( Self, steamIDUser ); return new CallResult<UserStatsReceived_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetUserStatInt32", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetUserStat( IntPtr self, SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref int pData ); #endregion internal bool GetUserStat( SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref int pData ) { var returnValue = _GetUserStat( Self, steamIDUser, pchName, ref pData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetUserStatFloat", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetUserStat( IntPtr self, SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref float pData ); #endregion internal bool GetUserStat( SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref float pData ) { var returnValue = _GetUserStat( Self, steamIDUser, pchName, ref pData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetUserAchievement", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetUserAchievement( IntPtr self, SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved ); #endregion internal bool GetUserAchievement( SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved ) { var returnValue = _GetUserAchievement( Self, steamIDUser, pchName, ref pbAchieved ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetUserAchievementAndUnlockTime", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetUserAchievementAndUnlockTime( IntPtr self, SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved, ref uint punUnlockTime ); #endregion internal bool GetUserAchievementAndUnlockTime( SteamId steamIDUser, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved, ref uint punUnlockTime ) { var returnValue = _GetUserAchievementAndUnlockTime( Self, steamIDUser, pchName, ref pbAchieved, ref punUnlockTime ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_ResetAllStats", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _ResetAllStats( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bAchievementsToo ); #endregion internal bool ResetAllStats( [MarshalAs( UnmanagedType.U1 )] bool bAchievementsToo ) { var returnValue = _ResetAllStats( Self, bAchievementsToo ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_FindOrCreateLeaderboard", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _FindOrCreateLeaderboard( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLeaderboardName, LeaderboardSort eLeaderboardSortMethod, LeaderboardDisplay eLeaderboardDisplayType ); #endregion internal CallResult<LeaderboardFindResult_t> FindOrCreateLeaderboard( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLeaderboardName, LeaderboardSort eLeaderboardSortMethod, LeaderboardDisplay eLeaderboardDisplayType ) { var returnValue = _FindOrCreateLeaderboard( Self, pchLeaderboardName, eLeaderboardSortMethod, eLeaderboardDisplayType ); return new CallResult<LeaderboardFindResult_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_FindLeaderboard", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _FindLeaderboard( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLeaderboardName ); #endregion internal CallResult<LeaderboardFindResult_t> FindLeaderboard( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchLeaderboardName ) { var returnValue = _FindLeaderboard( Self, pchLeaderboardName ); return new CallResult<LeaderboardFindResult_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetLeaderboardName", CallingConvention = Platform.CC)] private static extern Utf8StringPointer _GetLeaderboardName( IntPtr self, SteamLeaderboard_t hSteamLeaderboard ); #endregion internal string GetLeaderboardName( SteamLeaderboard_t hSteamLeaderboard ) { var returnValue = _GetLeaderboardName( Self, hSteamLeaderboard ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetLeaderboardEntryCount", CallingConvention = Platform.CC)] private static extern int _GetLeaderboardEntryCount( IntPtr self, SteamLeaderboard_t hSteamLeaderboard ); #endregion internal int GetLeaderboardEntryCount( SteamLeaderboard_t hSteamLeaderboard ) { var returnValue = _GetLeaderboardEntryCount( Self, hSteamLeaderboard ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetLeaderboardSortMethod", CallingConvention = Platform.CC)] private static extern LeaderboardSort _GetLeaderboardSortMethod( IntPtr self, SteamLeaderboard_t hSteamLeaderboard ); #endregion internal LeaderboardSort GetLeaderboardSortMethod( SteamLeaderboard_t hSteamLeaderboard ) { var returnValue = _GetLeaderboardSortMethod( Self, hSteamLeaderboard ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetLeaderboardDisplayType", CallingConvention = Platform.CC)] private static extern LeaderboardDisplay _GetLeaderboardDisplayType( IntPtr self, SteamLeaderboard_t hSteamLeaderboard ); #endregion internal LeaderboardDisplay GetLeaderboardDisplayType( SteamLeaderboard_t hSteamLeaderboard ) { var returnValue = _GetLeaderboardDisplayType( Self, hSteamLeaderboard ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_DownloadLeaderboardEntries", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _DownloadLeaderboardEntries( IntPtr self, SteamLeaderboard_t hSteamLeaderboard, LeaderboardDataRequest eLeaderboardDataRequest, int nRangeStart, int nRangeEnd ); #endregion internal CallResult<LeaderboardScoresDownloaded_t> DownloadLeaderboardEntries( SteamLeaderboard_t hSteamLeaderboard, LeaderboardDataRequest eLeaderboardDataRequest, int nRangeStart, int nRangeEnd ) { var returnValue = _DownloadLeaderboardEntries( Self, hSteamLeaderboard, eLeaderboardDataRequest, nRangeStart, nRangeEnd ); return new CallResult<LeaderboardScoresDownloaded_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_DownloadLeaderboardEntriesForUsers", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _DownloadLeaderboardEntriesForUsers( IntPtr self, SteamLeaderboard_t hSteamLeaderboard, [In,Out] SteamId[] prgUsers, int cUsers ); #endregion internal CallResult<LeaderboardScoresDownloaded_t> DownloadLeaderboardEntriesForUsers( SteamLeaderboard_t hSteamLeaderboard, [In,Out] SteamId[] prgUsers, int cUsers ) { var returnValue = _DownloadLeaderboardEntriesForUsers( Self, hSteamLeaderboard, prgUsers, cUsers ); return new CallResult<LeaderboardScoresDownloaded_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetDownloadedLeaderboardEntry", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetDownloadedLeaderboardEntry( IntPtr self, SteamLeaderboardEntries_t hSteamLeaderboardEntries, int index, ref LeaderboardEntry_t pLeaderboardEntry, [In,Out] int[] pDetails, int cDetailsMax ); #endregion internal bool GetDownloadedLeaderboardEntry( SteamLeaderboardEntries_t hSteamLeaderboardEntries, int index, ref LeaderboardEntry_t pLeaderboardEntry, [In,Out] int[] pDetails, int cDetailsMax ) { var returnValue = _GetDownloadedLeaderboardEntry( Self, hSteamLeaderboardEntries, index, ref pLeaderboardEntry, pDetails, cDetailsMax ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_UploadLeaderboardScore", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _UploadLeaderboardScore( IntPtr self, SteamLeaderboard_t hSteamLeaderboard, LeaderboardUploadScoreMethod eLeaderboardUploadScoreMethod, int nScore, [In,Out] int[] pScoreDetails, int cScoreDetailsCount ); #endregion internal CallResult<LeaderboardScoreUploaded_t> UploadLeaderboardScore( SteamLeaderboard_t hSteamLeaderboard, LeaderboardUploadScoreMethod eLeaderboardUploadScoreMethod, int nScore, [In,Out] int[] pScoreDetails, int cScoreDetailsCount ) { var returnValue = _UploadLeaderboardScore( Self, hSteamLeaderboard, eLeaderboardUploadScoreMethod, nScore, pScoreDetails, cScoreDetailsCount ); return new CallResult<LeaderboardScoreUploaded_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_AttachLeaderboardUGC", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _AttachLeaderboardUGC( IntPtr self, SteamLeaderboard_t hSteamLeaderboard, UGCHandle_t hUGC ); #endregion internal CallResult<LeaderboardUGCSet_t> AttachLeaderboardUGC( SteamLeaderboard_t hSteamLeaderboard, UGCHandle_t hUGC ) { var returnValue = _AttachLeaderboardUGC( Self, hSteamLeaderboard, hUGC ); return new CallResult<LeaderboardUGCSet_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetNumberOfCurrentPlayers", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _GetNumberOfCurrentPlayers( IntPtr self ); #endregion internal CallResult<NumberOfCurrentPlayers_t> GetNumberOfCurrentPlayers() { var returnValue = _GetNumberOfCurrentPlayers( Self ); return new CallResult<NumberOfCurrentPlayers_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_RequestGlobalAchievementPercentages", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _RequestGlobalAchievementPercentages( IntPtr self ); #endregion internal CallResult<GlobalAchievementPercentagesReady_t> RequestGlobalAchievementPercentages() { var returnValue = _RequestGlobalAchievementPercentages( Self ); return new CallResult<GlobalAchievementPercentagesReady_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetMostAchievedAchievementInfo", CallingConvention = Platform.CC)] private static extern int _GetMostAchievedAchievementInfo( IntPtr self, IntPtr pchName, uint unNameBufLen, ref float pflPercent, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved ); #endregion internal int GetMostAchievedAchievementInfo( out string pchName, ref float pflPercent, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved ) { using var mempchName = Helpers.TakeMemory(); var returnValue = _GetMostAchievedAchievementInfo( Self, mempchName, (1024 * 32), ref pflPercent, ref pbAchieved ); pchName = Helpers.MemoryToString( mempchName ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetNextMostAchievedAchievementInfo", CallingConvention = Platform.CC)] private static extern int _GetNextMostAchievedAchievementInfo( IntPtr self, int iIteratorPrevious, IntPtr pchName, uint unNameBufLen, ref float pflPercent, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved ); #endregion internal int GetNextMostAchievedAchievementInfo( int iIteratorPrevious, out string pchName, ref float pflPercent, [MarshalAs( UnmanagedType.U1 )] ref bool pbAchieved ) { using var mempchName = Helpers.TakeMemory(); var returnValue = _GetNextMostAchievedAchievementInfo( Self, iIteratorPrevious, mempchName, (1024 * 32), ref pflPercent, ref pbAchieved ); pchName = Helpers.MemoryToString( mempchName ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetAchievementAchievedPercent", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetAchievementAchievedPercent( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref float pflPercent ); #endregion internal bool GetAchievementAchievedPercent( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref float pflPercent ) { var returnValue = _GetAchievementAchievedPercent( Self, pchName, ref pflPercent ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_RequestGlobalStats", CallingConvention = Platform.CC)] private static extern SteamAPICall_t _RequestGlobalStats( IntPtr self, int nHistoryDays ); #endregion internal CallResult<GlobalStatsReceived_t> RequestGlobalStats( int nHistoryDays ) { var returnValue = _RequestGlobalStats( Self, nHistoryDays ); return new CallResult<GlobalStatsReceived_t>( returnValue, IsServer ); } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetGlobalStatInt64", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetGlobalStat( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchStatName, ref long pData ); #endregion internal bool GetGlobalStat( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchStatName, ref long pData ) { var returnValue = _GetGlobalStat( Self, pchStatName, ref pData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetGlobalStatDouble", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetGlobalStat( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchStatName, ref double pData ); #endregion internal bool GetGlobalStat( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchStatName, ref double pData ) { var returnValue = _GetGlobalStat( Self, pchStatName, ref pData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetGlobalStatHistoryInt64", CallingConvention = Platform.CC)] private static extern int _GetGlobalStatHistory( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchStatName, [In,Out] long[] pData, uint cubData ); #endregion internal int GetGlobalStatHistory( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchStatName, [In,Out] long[] pData, uint cubData ) { var returnValue = _GetGlobalStatHistory( Self, pchStatName, pData, cubData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetGlobalStatHistoryDouble", CallingConvention = Platform.CC)] private static extern int _GetGlobalStatHistory( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchStatName, [In,Out] double[] pData, uint cubData ); #endregion internal int GetGlobalStatHistory( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchStatName, [In,Out] double[] pData, uint cubData ) { var returnValue = _GetGlobalStatHistory( Self, pchStatName, pData, cubData ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetAchievementProgressLimitsInt32", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetAchievementProgressLimits( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref int pnMinProgress, ref int pnMaxProgress ); #endregion internal bool GetAchievementProgressLimits( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref int pnMinProgress, ref int pnMaxProgress ) { var returnValue = _GetAchievementProgressLimits( Self, pchName, ref pnMinProgress, ref pnMaxProgress ); return returnValue; } #region FunctionMeta [DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUserStats_GetAchievementProgressLimitsFloat", CallingConvention = Platform.CC)] [return: MarshalAs( UnmanagedType.I1 )] private static extern bool _GetAchievementProgressLimits( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref float pfMinProgress, ref float pfMaxProgress ); #endregion internal bool GetAchievementProgressLimits( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName, ref float pfMinProgress, ref float pfMaxProgress ) { var returnValue = _GetAchievementProgressLimits( Self, pchName, ref pfMinProgress, ref pfMaxProgress ); return returnValue; } } }
#region File Description //----------------------------------------------------------------------------- // AnimationPlayer.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; #endregion namespace SkinnedModel { /// <summary> /// The animation player is in charge of decoding bone position /// matrices from an animation clip. /// </summary> public class AnimationPlayer { #region Fields // Information about the currently playing animation clip. AnimationClip currentClipValue; TimeSpan currentTimeValue; int currentKeyframe; // Current animation transform matrices. Matrix[] boneTransforms; Matrix[] worldTransforms; Matrix[] skinTransforms; // Backlink to the bind pose and skeleton hierarchy data. SkinningData skinningDataValue; #endregion /// <summary> /// Constructs a new animation player. /// </summary> public AnimationPlayer(SkinningData skinningData) { if (skinningData == null) throw new ArgumentNullException("skinningData"); skinningDataValue = skinningData; boneTransforms = new Matrix[skinningData.BindPose.Count]; worldTransforms = new Matrix[skinningData.BindPose.Count]; skinTransforms = new Matrix[skinningData.BindPose.Count]; } /// <summary> /// Starts decoding the specified animation clip. /// </summary> public void StartClip(AnimationClip clip) { if (clip == null) throw new ArgumentNullException("clip"); currentClipValue = clip; currentTimeValue = TimeSpan.Zero; currentKeyframe = 0; // Initialize bone transforms to the bind pose. skinningDataValue.BindPose.CopyTo(boneTransforms, 0); } /// <summary> /// Advances the current animation position. /// </summary> public void Update(TimeSpan time, bool relativeToCurrentTime, Matrix rootTransform) { UpdateBoneTransforms(time, relativeToCurrentTime); UpdateWorldTransforms(rootTransform, boneTransforms); UpdateSkinTransforms(); } /// <summary> /// Helper used by the Update method to refresh the BoneTransforms data. /// </summary> public void UpdateBoneTransforms(TimeSpan time, bool relativeToCurrentTime) { if (currentClipValue == null) throw new InvalidOperationException( "AnimationPlayer.Update was called before StartClip"); // Update the animation position. if (relativeToCurrentTime) { time += currentTimeValue; // If we reached the end, loop back to the start. while (time >= currentClipValue.Duration) time -= currentClipValue.Duration; } if ((time < TimeSpan.Zero) || (time >= currentClipValue.Duration)) throw new ArgumentOutOfRangeException("time"); // If the position moved backwards, reset the keyframe index. if (time < currentTimeValue) { currentKeyframe = 0; skinningDataValue.BindPose.CopyTo(boneTransforms, 0); } currentTimeValue = time; // Read keyframe matrices. IList<Keyframe> keyframes = currentClipValue.Keyframes; while (currentKeyframe < keyframes.Count) { Keyframe keyframe = keyframes[currentKeyframe]; // Stop when we've read up to the current time position. if (keyframe.Time > currentTimeValue) break; // Use this keyframe. boneTransforms[keyframe.Bone] = keyframe.Transform; currentKeyframe++; } } /// <summary> /// Helper used by the Update method to refresh the WorldTransforms data. /// </summary> public void UpdateWorldTransforms(Matrix rootTransform, Matrix[] boneTransforms) { // Root bone. worldTransforms[0] = boneTransforms[0] * rootTransform; // Child bones. for (int bone = 1; bone < worldTransforms.Length; bone++) { int parentBone = skinningDataValue.SkeletonHierarchy[bone]; worldTransforms[bone] = boneTransforms[bone] * worldTransforms[parentBone]; } } /// <summary> /// Helper used by the Update method to refresh the SkinTransforms data. /// </summary> public void UpdateSkinTransforms() { for (int bone = 0; bone < skinTransforms.Length; bone++) { skinTransforms[bone] = skinningDataValue.InverseBindPose[bone] * worldTransforms[bone]; } } /// <summary> /// Gets the current bone transform matrices, relative to their parent bones. /// </summary> public Matrix[] GetBoneTransforms() { return boneTransforms; } /// <summary> /// Gets the current bone transform matrices, in absolute format. /// </summary> public Matrix[] GetWorldTransforms() { return worldTransforms; } /// <summary> /// Gets the current bone transform matrices, /// relative to the skinning bind pose. /// </summary> public Matrix[] GetSkinTransforms() { return skinTransforms; } /// <summary> /// Gets the clip currently being decoded. /// </summary> public AnimationClip CurrentClip { get { return currentClipValue; } } /// <summary> /// Gets the current play position. /// </summary> public TimeSpan CurrentTime { get { return currentTimeValue; } } } }
/*! Achordeon - MIT License Copyright (c) 2017 tiamatix / Wolf Robben Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. !*/ using System; using System.Linq; namespace Achordeon.Lib.Chords { public class CommonChordLibrary { public ChordList Chords { get; } = new ChordList(); public Chord FindChord(string AName) { return Chords.FirstOrDefault(AChord => StringComparer.OrdinalIgnoreCase.Equals(AChord.Name, AName)); } private void LearnBuildinChords() { const int N = -1; Chords.LearnChord("Ab", 1, 3, 3, 2, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ab+", N, N, 2, 1, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ab4", N, N, 1, 1, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ab7", N, N, 1, 1, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ab11", 1, 3, 1, 3, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Absus", N, N, 1, 1, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Absus4", N, N, 1, 1, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Abdim", N, N, 0, 1, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Abmaj", 1, 3, 3, 2, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Abmaj7", N, N, 1, 1, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Abm", 1, 3, 3, 1, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Abmin", 1, 3, 3, 1, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Abm7", N, N, 1, 1, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A", N, 0, 2, 2, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("A+", N, 0, 3, 2, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A4", 0, 0, 2, 2, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A6", N, N, 2, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A7", N, 0, 2, 0, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("A7+", N, N, 3, 2, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A7(9+)", N, 2, 2, 2, 2, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A9", N, 0, 2, 1, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A11", N, 4, 2, 4, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A13", N, 0, 1, 2, 3, 1, 5, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A7sus4", 0, 0, 2, 0, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A9sus", N, 0, 2, 1, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Asus", N, N, 2, 2, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Asus2", 0, 0, 2, 2, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Asus4", N, N, 2, 2, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Adim", N, N, 1, 2, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Amaj", N, 0, 2, 2, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Amaj7", N, 0, 2, 1, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Am", N, 0, 2, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Amin", N, 0, 2, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("A/D", N, N, 0, 0, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A/F#", 2, 0, 2, 2, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A/G#", 4, 0, 2, 2, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Am#7", N, N, 2, 1, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Am(7#)", N, 0, 2, 2, 1, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Am6", N, 0, 2, 2, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Am7", N, 0, 2, 2, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Am7sus4", 0, 0, 0, 0, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Am9", N, 0, 1, 1, 1, 3, 5, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Am/G", 3, 0, 2, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Amadd9", 0, 2, 2, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Am(add9)", 0, 2, 2, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#", N, 1, 3, 3, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#+", N, N, 0, 3, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#4", N, N, 3, 3, 4, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#7", N, N, 1, 1, 1, 2, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#sus", N, N, 3, 3, 4, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#sus4", N, N, 3, 3, 4, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#maj", N, 1, 3, 3, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#maj7", N, 1, 3, 2, 3, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#dim", N, N, 2, 3, 2, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#m", N, 1, 3, 3, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#min", N, 1, 3, 3, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("A#m7", N, 1, 3, 1, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bb", N, 1, 3, 3, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Bb+", N, N, 0, 3, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bb4", N, N, 3, 3, 4, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bb6", N, N, 3, 3, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bb7", N, N, 1, 1, 1, 2, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bb9", 1, 3, 1, 2, 1, 3, 6, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bb11", 1, 3, 1, 3, 4, 1, 6, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bbsus", N, N, 3, 3, 4, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bbsus4", N, N, 3, 3, 4, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bbmaj", N, 1, 3, 3, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bbmaj7", N, 1, 3, 2, 3, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bbdim", N, N, 2, 3, 2, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bbm", N, 1, 3, 3, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bbmin", N, 1, 3, 3, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bbm7", N, 1, 3, 1, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bbm9", N, N, N, 1, 1, 3, 6, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B", N, 2, 4, 4, 4, 2, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("B+", N, N, 1, 0, 0, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B4", N, N, 3, 3, 4, 1, 2, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B7", 0, 2, 1, 2, 0, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B7+", N, 2, 1, 2, 0, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B7+5", N, 2, 1, 2, 0, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B7#9", N, 2, 1, 2, 3, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B7(#9)", N, 2, 1, 2, 3, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B9", 1, 3, 1, 2, 1, 3, 7, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B11", 1, 3, 3, 2, 0, 0, 7, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B11/13", N, 1, 1, 1, 1, 3, 2, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B13", N, 2, 1, 2, 0, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bsus", N, N, 3, 3, 4, 1, 2, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bsus4", N, N, 3, 3, 4, 1, 2, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bmaj", N, 2, 4, 3, 4, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bmaj7", N, 2, 4, 3, 4, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bdim", N, N, 0, 1, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bm", N, 2, 4, 4, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bmin", N, 2, 4, 4, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B/F#", 0, 2, 2, 2, 0, 0, 2, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("BaddE", N, 2, 4, 4, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("B(addE)", N, 2, 4, 4, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("BaddE/F#", 2, N, 4, 4, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bm6", N, N, 4, 4, 3, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bm7", N, 1, 3, 1, 2, 1, 2, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Bmmaj7", N, 1, 4, 4, 3, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bm(maj7)", N, 1, 4, 4, 3, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bmsus9", N, N, 4, 4, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bm(sus9)", N, N, 4, 4, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Bm7b5", 1, 2, 4, 2, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C", N, 3, 2, 0, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("C+", N, N, 2, 1, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C4", N, N, 3, 0, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C6", N, 0, 2, 2, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C7", 0, 3, 2, 3, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("C9", 1, 3, 1, 2, 1, 3, 8, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C9(11)", N, 3, 3, 3, 3, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C11", N, 1, 3, 1, 4, 1, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Csus", N, N, 3, 0, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Csus2", N, 3, 0, 0, 1, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Csus4", N, N, 3, 0, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Csus9", N, N, 4, 1, 2, 4, 7, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Cmaj", 0, 3, 2, 0, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Cmaj7", N, 3, 2, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Cm", N, 1, 3, 3, 2, 1, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Cmin", N, 1, 3, 3, 2, 1, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Cdim", N, N, 1, 2, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C/B", N, 2, 2, 0, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Cadd2/B", N, 2, 0, 0, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("CaddD", N, 3, 2, 0, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C(addD)", N, 3, 2, 0, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Cadd9", N, 3, 2, 0, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C(add9)", N, 3, 2, 0, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C3", N, 1, 3, 3, 2, 1, 3, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Cm7", N, 1, 3, 1, 2, 1, 3, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Cm11", N, 1, 3, 1, 4, N, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#", N, N, 3, 1, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#+", N, N, 3, 2, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#4", N, N, 3, 3, 4, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#7", N, N, 3, 4, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#7(b5)", N, 2, 1, 2, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#sus", N, N, 3, 3, 4, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#sus4", N, N, 3, 3, 4, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#maj", N, 4, 3, 1, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#maj7", N, 4, 3, 1, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#dim", N, N, 2, 3, 2, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#m", N, N, 2, 1, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#min", N, N, 2, 1, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#add9", N, 1, 3, 3, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#(add9)", N, 1, 3, 3, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("C#m7", N, N, 2, 4, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Db", N, N, 3, 1, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Db+", N, N, 3, 2, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Db7", N, N, 3, 4, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dbsus", N, N, 3, 3, 4, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dbsus4", N, N, 3, 3, 4, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dbmaj", N, N, 3, 1, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dbmaj7", N, 4, 3, 1, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dbdim", N, N, 2, 3, 2, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dbm", N, N, 2, 1, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dbmin", N, N, 2, 1, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dbm7", N, N, 2, 4, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D", N, N, 0, 2, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("D+", N, N, 0, 3, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D4", N, N, 0, 2, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D6", N, 0, 0, 2, 0, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D7", N, N, 0, 2, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("D7#9", N, 2, 1, 2, 3, 3, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D7(#9)", N, 2, 1, 2, 3, 3, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D9", 1, 3, 1, 2, 1, 3, 10, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D11", 3, 0, 0, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dsus", N, N, 0, 2, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dsus2", 0, 0, 0, 2, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dsus4", N, N, 0, 2, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D7sus2", N, 0, 0, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D7sus4", N, 0, 0, 2, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dmaj", N, N, 0, 2, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dmaj7", N, N, 0, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ddim", N, N, 0, 1, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm", N, N, 0, 2, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Dmin", N, N, 0, 2, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("D/A", N, 0, 0, 2, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D/B", N, 2, 0, 2, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D/C", N, 3, 0, 2, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D/C#", N, 4, 0, 2, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D/E", N, 1, 1, 1, 1, N, 7, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D/G", 3, N, 0, 2, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D5/E", 0, 1, 1, 1, N, N, 7, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dadd9", 0, 0, 0, 2, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D(add9)", 0, 0, 0, 2, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D9add6", 1, 3, 3, 2, 0, 0, 10, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D9(add6)", 1, 3, 3, 2, 0, 0, 10, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm6(5b)", N, N, 0, 1, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm7", N, N, 0, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Dm#5", N, N, 0, 3, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm(#5)", N, N, 0, 3, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm#7", N, N, 0, 2, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm(#7)", N, N, 0, 2, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm/A", N, 0, 0, 2, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm/B", N, 2, 0, 2, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm/C", N, 3, 0, 2, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm/C#", N, 4, 0, 2, 3, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Dm9", N, N, 3, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#", N, N, 3, 1, 2, 1, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#+", N, N, 1, 0, 0, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#4", N, N, 1, 3, 4, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#7", N, N, 1, 3, 2, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#sus", N, N, 1, 3, 4, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#sus4", N, N, 1, 3, 4, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#maj", N, N, 3, 1, 2, 1, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#maj7", N, N, 1, 3, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#dim", N, N, 1, 2, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#m", N, N, 4, 3, 4, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#min", N, N, 4, 3, 4, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("D#m7", N, N, 1, 3, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Eb", N, N, 3, 1, 2, 1, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Eb+", N, N, 1, 0, 0, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Eb4", N, N, 1, 3, 4, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Eb7", N, N, 1, 3, 2, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ebsus", N, N, 1, 3, 4, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ebsus4", N, N, 1, 3, 4, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ebmaj", N, N, 1, 3, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ebmaj7", N, N, 1, 3, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ebdim", N, N, 1, 2, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ebadd9", N, 1, 1, 3, 4, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Eb(add9)", N, 1, 1, 3, 4, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ebm", N, N, 4, 3, 4, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ebmin", N, N, 4, 3, 4, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Ebm7", N, N, 1, 3, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E", 0, 2, 2, 1, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("E+", N, N, 2, 1, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E5", 0, 1, 3, 3, N, N, 7, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E6", N, N, 3, 3, 3, 3, 9, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E7", 0, 2, 2, 1, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("E7#9", 0, 2, 2, 1, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E7(#9)", 0, 2, 2, 1, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E7(5b)", N, 1, 0, 1, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E7b9", 0, 2, 0, 1, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E7(b9)", 0, 2, 0, 1, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E7(11)", 0, 2, 2, 2, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E9", 1, 3, 1, 2, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("E11", 1, 1, 1, 1, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Esus", 0, 2, 2, 2, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Esus4", 0, 2, 2, 2, 0, 0, 0, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Emaj", 0, 2, 2, 1, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Emaj7", 0, 2, 1, 1, 0, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Edim", N, N, 2, 3, 2, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Em", 0, 2, 2, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Emin", 0, 2, 2, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Em6", 0, 2, 2, 0, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Em7", 0, 2, 2, 0, 3, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Em/B", N, 2, 2, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Em/D", N, N, 0, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Em7/D", N, N, 0, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Emsus4", 0, 0, 2, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Em(sus4)", 0, 0, 2, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Emadd9", 0, 2, 4, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Em(add9)", 0, 2, 4, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F", 1, 3, 3, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("F+", N, N, 3, 2, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F+7+11", 1, 3, 3, 2, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F4", N, N, 3, 3, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F6", N, 3, 3, 2, 3, N, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F7", 1, 3, 1, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("F9", 2, 4, 2, 3, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F11", 1, 3, 1, 3, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fsus", N, N, 3, 3, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fsus4", N, N, 3, 3, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fmaj", 1, 3, 3, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fmaj7", N, 3, 3, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fdim", N, N, 0, 1, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fm", 1, 3, 3, 1, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Fmin", 1, 3, 3, 1, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("F/A", N, 0, 3, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F/C", N, N, 3, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F/D", N, N, 0, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F/G", 3, 3, 3, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F7/A", N, 0, 3, 0, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fmaj7/A", N, 0, 3, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fmaj7/C", N, 3, 3, 2, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fmaj7(+5)", N, N, 3, 2, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fadd9", 3, 0, 3, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F(add9)", 3, 0, 3, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("FaddG", 1, N, 3, 2, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("FaddG", 1, N, 3, 2, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fm6", N, N, 0, 1, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Fm7", 1, 3, 1, 1, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Fmmaj7", N, 3, 3, 1, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#", 2, 4, 4, 3, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("F#+", N, N, 4, 3, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#7", N, N, 4, 3, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("F#9", N, 1, 2, 1, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#11", 2, 4, 2, 4, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#sus", N, N, 4, 4, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#sus4", N, N, 4, 4, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#maj", 2, 4, 4, 3, 2, 2, 0, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#maj7", N, N, 4, 3, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#dim", N, N, 1, 2, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#m", 2, 4, 4, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("F#min", 2, 4, 4, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("F#/E", 0, 4, 4, 3, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#4", N, N, 4, 4, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#m6", N, N, 1, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#m7", N, N, 2, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("F#m7-5", 1, 0, 2, 3, 3, 3, 2, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("F#m/C#m", N, N, 4, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gb", 2, 4, 4, 3, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Gb+", N, N, 4, 3, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gb7", N, N, 4, 3, 2, 0, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Gb9", N, 1, 2, 1, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gbsus", N, N, 4, 4, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gbsus4", N, N, 4, 4, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gbmaj", 2, 4, 4, 3, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gbmaj7", N, N, 4, 3, 2, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gbdim", N, N, 1, 2, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gbm", 2, 4, 4, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gbmin", 2, 4, 4, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gbm7", N, N, 2, 2, 2, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G", 3, 2, 0, 0, 0, 3, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("G+", N, N, 1, 0, 0, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G4", N, N, 0, 0, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G6", 3, N, 0, 0, 0, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G7", 3, 2, 0, 0, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("G7+", N, N, 4, 3, 3, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G7b9", N, N, 0, 1, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G7(b9)", N, N, 0, 1, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G7#9", 1, 3, N, 2, 4, 4, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G7(#9)", 1, 3, N, 2, 4, 4, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G9", 3, N, 0, 2, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G9(11)", 1, 3, 1, 3, 1, 3, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G11", 3, N, 0, 2, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gsus", N, N, 0, 0, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gsus4", N, N, 0, 0, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G6sus4", 0, 2, 0, 0, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G6(sus4)", 0, 2, 0, 0, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G7sus4", 3, 3, 0, 0, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G7(sus4)", 3, 3, 0, 0, 1, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gmaj", 3, 2, 0, 0, 0, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gmaj7", N, N, 4, 3, 2, 1, 2, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gmaj7sus4", N, N, 0, 0, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gmaj9", 1, 1, 4, 1, 2, 1, 2, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gm", 1, 3, 3, 1, 1, 1, 3, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Gmin", 1, 3, 3, 1, 1, 1, 3, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Gdim", N, N, 2, 3, 2, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gadd9", 1, 3, N, 2, 1, 3, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G(add9)", 1, 3, N, 2, 1, 3, 3, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G/A", N, 0, 0, 0, 0, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G/B", N, 2, 0, 0, 0, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G/D", N, 2, 2, 1, 0, 0, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G/F#", 2, 2, 0, 0, 0, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gm6", N, N, 2, 3, 3, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("Gm7", 1, 3, 1, 1, 1, 1, 3, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("Gm/Bb", 3, 2, 2, 1, N, N, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#", 1, 3, 3, 2, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("G#+", N, N, 2, 1, 1, 0, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#4", 1, 3, 3, 1, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#7", N, N, 1, 1, 1, 2, 1, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("G#sus", N, N, 1, 1, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#sus4", N, N, 1, 1, 2, 4, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#maj", 1, 3, 3, 2, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#maj7", N, N, 1, 1, 1, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#dim", N, N, 0, 1, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#m", 1, 3, 3, 1, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#min", 1, 3, 3, 1, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#m6", N, N, 1, 1, 0, 1, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#m7", N, N, 1, 1, 1, 1, 4, ChordOrigin.BuildIn, Difficulty.Easy); Chords.LearnChord("G#m9maj7", N, N, 1, 3, 0, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); Chords.LearnChord("G#m9(maj7)", N, N, 1, 3, 0, 3, 1, ChordOrigin.BuildIn, Difficulty.Hard); } public CommonChordLibrary() { LearnBuildinChords(); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.IdentityModel { using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IdentityModel.Tokens; using System.IdentityModel.Selectors; using System.Security.Cryptography; using System.Text; using System.Xml; sealed class SignedXml : ISignatureValueSecurityElement { internal const string DefaultPrefix = XmlSignatureStrings.Prefix; SecurityTokenSerializer tokenSerializer; readonly Signature signature; TransformFactory transformFactory; DictionaryManager dictionaryManager; public SignedXml(DictionaryManager dictionaryManager, SecurityTokenSerializer tokenSerializer) : this(new StandardSignedInfo(dictionaryManager), dictionaryManager, tokenSerializer) { } internal SignedXml(SignedInfo signedInfo, DictionaryManager dictionaryManager, SecurityTokenSerializer tokenSerializer) { if (signedInfo == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("signedInfo")); } if (dictionaryManager == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dictionaryManager"); } if (tokenSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenSerializer"); } this.transformFactory = StandardTransformFactory.Instance; this.tokenSerializer = tokenSerializer; this.signature = new Signature(this, signedInfo); this.dictionaryManager = dictionaryManager; } public bool HasId { get { return true; } } public string Id { get { return this.signature.Id; } set { this.signature.Id = value; } } public SecurityTokenSerializer SecurityTokenSerializer { get { return this.tokenSerializer; } } public Signature Signature { get { return this.signature; } } public TransformFactory TransformFactory { get { return this.transformFactory; } set { this.transformFactory = value; } } void ComputeSignature(HashAlgorithm hash, AsymmetricSignatureFormatter formatter, string signatureMethod) { this.Signature.SignedInfo.ComputeReferenceDigests(); this.Signature.SignedInfo.ComputeHash(hash); byte[] signature; if (SecurityUtils.RequiresFipsCompliance && signatureMethod == SecurityAlgorithms.RsaSha256Signature) { // This is to avoid the RSAPKCS1SignatureFormatter.CreateSignature from using SHA256Managed (non-FIPS-Compliant). // Hence we precompute the hash using SHA256CSP (FIPS compliant) and pass it to method. // NOTE: RSAPKCS1SignatureFormatter does not understand SHA256CSP inherently and hence this workaround. formatter.SetHashAlgorithm("SHA256"); signature = formatter.CreateSignature(hash.Hash); } else { signature = formatter.CreateSignature(hash); } this.Signature.SetSignatureValue(signature); } void ComputeSignature(KeyedHashAlgorithm hash) { this.Signature.SignedInfo.ComputeReferenceDigests(); this.Signature.SignedInfo.ComputeHash(hash); byte[] signature = hash.Hash; this.Signature.SetSignatureValue(signature); } public void ComputeSignature(SecurityKey signingKey) { string signatureMethod = this.Signature.SignedInfo.SignatureMethod; SymmetricSecurityKey symmetricKey = signingKey as SymmetricSecurityKey; if (symmetricKey != null) { using (KeyedHashAlgorithm algorithm = symmetricKey.GetKeyedHashAlgorithm(signatureMethod)) { if (algorithm == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.UnableToCreateKeyedHashAlgorithm, symmetricKey, signatureMethod))); } ComputeSignature(algorithm); } } else { AsymmetricSecurityKey asymmetricKey = signingKey as AsymmetricSecurityKey; if (asymmetricKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.UnknownICryptoType, signingKey))); } using (HashAlgorithm hash = asymmetricKey.GetHashAlgorithmForSignature(signatureMethod)) { if (hash == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.UnableToCreateHashAlgorithmFromAsymmetricCrypto, signatureMethod, asymmetricKey))); } AsymmetricSignatureFormatter formatter = asymmetricKey.GetSignatureFormatter(signatureMethod); if (formatter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.UnableToCreateSignatureFormatterFromAsymmetricCrypto, signatureMethod, asymmetricKey))); } ComputeSignature(hash, formatter, signatureMethod); } } } public void CompleteSignatureVerification() { this.Signature.SignedInfo.EnsureAllReferencesVerified(); } public void EnsureDigestValidity(string id, object resolvedXmlSource) { this.Signature.SignedInfo.EnsureDigestValidity(id, resolvedXmlSource); } public byte[] GetSignatureValue() { return this.Signature.GetSignatureBytes(); } public void ReadFrom(XmlReader reader) { ReadFrom(XmlDictionaryReader.CreateDictionaryReader(reader)); } public void ReadFrom(XmlDictionaryReader reader) { this.signature.ReadFrom(reader, this.dictionaryManager); } void VerifySignature(KeyedHashAlgorithm hash) { this.Signature.SignedInfo.ComputeHash(hash); if (!CryptoHelper.IsEqual(hash.Hash, GetSignatureValue())) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.SignatureVerificationFailed))); } } void VerifySignature(HashAlgorithm hash, AsymmetricSignatureDeformatter deformatter, string signatureMethod) { this.Signature.SignedInfo.ComputeHash(hash); bool result; if (SecurityUtils.RequiresFipsCompliance && signatureMethod == SecurityAlgorithms.RsaSha256Signature) { // This is to avoid the RSAPKCS1SignatureFormatter.VerifySignature from using SHA256Managed (non-FIPS-Compliant). // Hence we precompute the hash using SHA256CSP (FIPS compliant) and pass it to method. // NOTE: RSAPKCS1SignatureFormatter does not understand SHA256CSP inherently and hence this workaround. deformatter.SetHashAlgorithm("SHA256"); result = deformatter.VerifySignature(hash.Hash, GetSignatureValue()); } else { result = deformatter.VerifySignature(hash, GetSignatureValue()); } if (!result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.SignatureVerificationFailed))); } } public void StartSignatureVerification(SecurityKey verificationKey) { string signatureMethod = this.Signature.SignedInfo.SignatureMethod; SymmetricSecurityKey symmetricKey = verificationKey as SymmetricSecurityKey; if (symmetricKey != null) { using (KeyedHashAlgorithm hash = symmetricKey.GetKeyedHashAlgorithm(signatureMethod)) { if (hash == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException( SR.GetString(SR.UnableToCreateKeyedHashAlgorithmFromSymmetricCrypto, signatureMethod, symmetricKey))); } VerifySignature(hash); } } else { AsymmetricSecurityKey asymmetricKey = verificationKey as AsymmetricSecurityKey; if (asymmetricKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UnknownICryptoType, verificationKey))); } using (HashAlgorithm hash = asymmetricKey.GetHashAlgorithmForSignature(signatureMethod)) { if (hash == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException( SR.GetString(SR.UnableToCreateHashAlgorithmFromAsymmetricCrypto, signatureMethod, asymmetricKey))); } AsymmetricSignatureDeformatter deformatter = asymmetricKey.GetSignatureDeformatter(signatureMethod); if (deformatter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException( SR.GetString(SR.UnableToCreateSignatureDeformatterFromAsymmetricCrypto, signatureMethod, asymmetricKey))); } VerifySignature(hash, deformatter, signatureMethod); } } } public void WriteTo(XmlDictionaryWriter writer) { this.WriteTo(writer, this.dictionaryManager); } public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { this.signature.WriteTo(writer, dictionaryManager); } } sealed class Signature { SignedXml signedXml; string id; SecurityKeyIdentifier keyIdentifier; string prefix = SignedXml.DefaultPrefix; readonly SignatureValueElement signatureValueElement = new SignatureValueElement(); readonly SignedInfo signedInfo; public Signature(SignedXml signedXml, SignedInfo signedInfo) { this.signedXml = signedXml; this.signedInfo = signedInfo; } public string Id { get { return this.id; } set { this.id = value; } } public SecurityKeyIdentifier KeyIdentifier { get { return this.keyIdentifier; } set { this.keyIdentifier = value; } } public SignedInfo SignedInfo { get { return this.signedInfo; } } public ISignatureValueSecurityElement SignatureValue { get { return this.signatureValueElement; } } public byte[] GetSignatureBytes() { return this.signatureValueElement.Value; } public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager) { reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.Signature, dictionaryManager.XmlSignatureDictionary.Namespace); this.prefix = reader.Prefix; this.Id = reader.GetAttribute(dictionaryManager.UtilityDictionary.IdAttribute, null); reader.Read(); this.signedInfo.ReadFrom(reader, signedXml.TransformFactory, dictionaryManager); this.signatureValueElement.ReadFrom(reader, dictionaryManager); if (signedXml.SecurityTokenSerializer.CanReadKeyIdentifier(reader)) { this.keyIdentifier = signedXml.SecurityTokenSerializer.ReadKeyIdentifier(reader); } reader.ReadEndElement(); // Signature } public void SetSignatureValue(byte[] signatureValue) { this.signatureValueElement.Value = signatureValue; } public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.Signature, dictionaryManager.XmlSignatureDictionary.Namespace); if (this.id != null) { writer.WriteAttributeString(dictionaryManager.UtilityDictionary.IdAttribute, null, this.id); } this.signedInfo.WriteTo(writer, dictionaryManager); this.signatureValueElement.WriteTo(writer, dictionaryManager); if (this.keyIdentifier != null) { this.signedXml.SecurityTokenSerializer.WriteKeyIdentifier(writer, this.keyIdentifier); } writer.WriteEndElement(); // Signature } sealed class SignatureValueElement : ISignatureValueSecurityElement { string id; string prefix = SignedXml.DefaultPrefix; byte[] signatureValue; string signatureText; public bool HasId { get { return true; } } public string Id { get { return this.id; } set { this.id = value; } } internal byte[] Value { get { return this.signatureValue; } set { this.signatureValue = value; this.signatureText = null; } } public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager) { reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.SignatureValue, dictionaryManager.XmlSignatureDictionary.Namespace); this.prefix = reader.Prefix; this.Id = reader.GetAttribute(UtilityStrings.IdAttribute, null); reader.Read(); this.signatureText = reader.ReadString(); this.signatureValue = System.Convert.FromBase64String(signatureText.Trim()); reader.ReadEndElement(); // SignatureValue } public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.SignatureValue, dictionaryManager.XmlSignatureDictionary.Namespace); if (this.id != null) { writer.WriteAttributeString(dictionaryManager.UtilityDictionary.IdAttribute, null, this.id); } if (this.signatureText != null) { writer.WriteString(this.signatureText); } else { writer.WriteBase64(this.signatureValue, 0, this.signatureValue.Length); } writer.WriteEndElement(); // SignatureValue } byte[] ISignatureValueSecurityElement.GetSignatureValue() { return this.Value; } } } internal interface ISignatureReaderProvider { XmlDictionaryReader GetReader(object callbackContext); } abstract class SignedInfo : ISecurityElement { readonly ExclusiveCanonicalizationTransform canonicalizationMethodElement = new ExclusiveCanonicalizationTransform(true); string id; ElementWithAlgorithmAttribute signatureMethodElement; SignatureResourcePool resourcePool; DictionaryManager dictionaryManager; MemoryStream canonicalStream; ISignatureReaderProvider readerProvider; object signatureReaderProviderCallbackContext; bool sendSide = true; protected SignedInfo(DictionaryManager dictionaryManager) { if (dictionaryManager == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dictionaryManager"); this.signatureMethodElement = new ElementWithAlgorithmAttribute(dictionaryManager.XmlSignatureDictionary.SignatureMethod); this.dictionaryManager = dictionaryManager; } protected DictionaryManager DictionaryManager { get { return this.dictionaryManager; } } protected MemoryStream CanonicalStream { get { return this.canonicalStream; } set { this.canonicalStream = value; } } protected bool SendSide { get { return this.sendSide; } set { this.sendSide = value; } } public ISignatureReaderProvider ReaderProvider { get { return this.readerProvider; } set { this.readerProvider = value; } } public object SignatureReaderProviderCallbackContext { get { return this.signatureReaderProviderCallbackContext; } set { this.signatureReaderProviderCallbackContext = value; } } public string CanonicalizationMethod { get { return this.canonicalizationMethodElement.Algorithm; } set { if (value != this.canonicalizationMethodElement.Algorithm) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedTransformAlgorithm))); } } } public XmlDictionaryString CanonicalizationMethodDictionaryString { set { if (value != null && value.Value != this.canonicalizationMethodElement.Algorithm) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedTransformAlgorithm))); } } } public bool HasId { get { return true; } } public string Id { get { return this.id; } set { this.id = value; } } public abstract int ReferenceCount { get; } public string SignatureMethod { get { return this.signatureMethodElement.Algorithm; } set { this.signatureMethodElement.Algorithm = value; } } public XmlDictionaryString SignatureMethodDictionaryString { get { return this.signatureMethodElement.AlgorithmDictionaryString; } set { this.signatureMethodElement.AlgorithmDictionaryString = value; } } public SignatureResourcePool ResourcePool { get { if (this.resourcePool == null) { this.resourcePool = new SignatureResourcePool(); } return this.resourcePool; } set { this.resourcePool = value; } } public void ComputeHash(HashAlgorithm algorithm) { if ((this.CanonicalizationMethod != SecurityAlgorithms.ExclusiveC14n) && (this.CanonicalizationMethod != SecurityAlgorithms.ExclusiveC14nWithComments)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.UnsupportedTransformAlgorithm))); } HashStream hashStream = this.ResourcePool.TakeHashStream(algorithm); ComputeHash(hashStream); hashStream.FlushHash(); } protected virtual void ComputeHash(HashStream hashStream) { if (this.sendSide) { XmlDictionaryWriter utf8Writer = this.ResourcePool.TakeUtf8Writer(); utf8Writer.StartCanonicalization(hashStream, false, null); WriteTo(utf8Writer, this.dictionaryManager); utf8Writer.EndCanonicalization(); } else if (this.canonicalStream != null) { this.canonicalStream.WriteTo(hashStream); } else { if (this.readerProvider == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.InclusiveNamespacePrefixRequiresSignatureReader))); XmlDictionaryReader signatureReader = this.readerProvider.GetReader(this.signatureReaderProviderCallbackContext); DiagnosticUtility.DebugAssert(signatureReader != null, "Require a Signature reader to validate signature."); if (!signatureReader.CanCanonicalize) { MemoryStream stream = new MemoryStream(); XmlDictionaryWriter bufferingWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, this.DictionaryManager.ParentDictionary); string[] inclusivePrefix = GetInclusivePrefixes(); if (inclusivePrefix != null) { bufferingWriter.WriteStartElement("a"); for (int i = 0; i < inclusivePrefix.Length; ++i) { string ns = GetNamespaceForInclusivePrefix(inclusivePrefix[i]); if (ns != null) { bufferingWriter.WriteXmlnsAttribute(inclusivePrefix[i], ns); } } } signatureReader.MoveToContent(); bufferingWriter.WriteNode(signatureReader, false); if (inclusivePrefix != null) bufferingWriter.WriteEndElement(); bufferingWriter.Flush(); byte[] buffer = stream.ToArray(); int bufferLength = (int)stream.Length; bufferingWriter.Close(); signatureReader.Close(); // Create a reader around the buffering Stream. signatureReader = XmlDictionaryReader.CreateBinaryReader(buffer, 0, bufferLength, this.DictionaryManager.ParentDictionary, XmlDictionaryReaderQuotas.Max); if (inclusivePrefix != null) signatureReader.ReadStartElement("a"); } signatureReader.ReadStartElement(dictionaryManager.XmlSignatureDictionary.Signature, dictionaryManager.XmlSignatureDictionary.Namespace); signatureReader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.SignedInfo, dictionaryManager.XmlSignatureDictionary.Namespace); signatureReader.StartCanonicalization(hashStream, false, GetInclusivePrefixes()); signatureReader.Skip(); signatureReader.EndCanonicalization(); signatureReader.Close(); } } public abstract void ComputeReferenceDigests(); protected string[] GetInclusivePrefixes() { return this.canonicalizationMethodElement.GetInclusivePrefixes(); } protected virtual string GetNamespaceForInclusivePrefix(string prefix) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public abstract void EnsureAllReferencesVerified(); public void EnsureDigestValidity(string id, object resolvedXmlSource) { if (!EnsureDigestValidityIfIdMatches(id, resolvedXmlSource)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException( SR.GetString(SR.RequiredTargetNotSigned, id))); } } public abstract bool EnsureDigestValidityIfIdMatches(string id, object resolvedXmlSource); public virtual bool HasUnverifiedReference(string id) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } protected void ReadCanonicalizationMethod(XmlDictionaryReader reader, DictionaryManager dictionaryManager) { // we will ignore any comments in the SignedInfo elemnt when verifying signature this.canonicalizationMethodElement.ReadFrom(reader, dictionaryManager, false); } public abstract void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager); protected void ReadSignatureMethod(XmlDictionaryReader reader, DictionaryManager dictionaryManager) { this.signatureMethodElement.ReadFrom(reader, dictionaryManager); } protected void WriteCanonicalizationMethod(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { this.canonicalizationMethodElement.WriteTo(writer, dictionaryManager); } protected void WriteSignatureMethod(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { this.signatureMethodElement.WriteTo(writer, dictionaryManager); } public abstract void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager); } // whitespace preservation convention: ws1 immediately inside open tag; ws2 immediately after end tag. class StandardSignedInfo : SignedInfo { string prefix = SignedXml.DefaultPrefix; List<Reference> references; Dictionary<string, string> context; public StandardSignedInfo(DictionaryManager dictionaryManager) : base(dictionaryManager) { this.references = new List<Reference>(); } public override int ReferenceCount { get { return this.references.Count; } } public Reference this[int index] { get { return this.references[index]; } } public void AddReference(Reference reference) { reference.ResourcePool = this.ResourcePool; this.references.Add(reference); } public override void EnsureAllReferencesVerified() { for (int i = 0; i < this.references.Count; i++) { if (!this.references[i].Verified) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CryptographicException(SR.GetString(SR.UnableToResolveReferenceUriForSignature, this.references[i].Uri))); } } } public override bool EnsureDigestValidityIfIdMatches(string id, object resolvedXmlSource) { for (int i = 0; i < this.references.Count; i++) { if (this.references[i].EnsureDigestValidityIfIdMatches(id, resolvedXmlSource)) { return true; } } return false; } public override bool HasUnverifiedReference(string id) { for (int i = 0; i < this.references.Count; i++) { if (!this.references[i].Verified && this.references[i].ExtractReferredId() == id) { return true; } } return false; } public override void ComputeReferenceDigests() { if (this.references.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.AtLeastOneReferenceRequired))); } for (int i = 0; i < this.references.Count; i++) { this.references[i].ComputeAndSetDigest(); } } public override void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager) { this.SendSide = false; if (reader.CanCanonicalize) { this.CanonicalStream = new MemoryStream(); reader.StartCanonicalization(this.CanonicalStream, false, null); } reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.SignedInfo, dictionaryManager.XmlSignatureDictionary.Namespace); this.prefix = reader.Prefix; this.Id = reader.GetAttribute(dictionaryManager.UtilityDictionary.IdAttribute, null); reader.Read(); ReadCanonicalizationMethod(reader, dictionaryManager); ReadSignatureMethod(reader, dictionaryManager); while (reader.IsStartElement(dictionaryManager.XmlSignatureDictionary.Reference, dictionaryManager.XmlSignatureDictionary.Namespace)) { Reference reference = new Reference(dictionaryManager); reference.ReadFrom(reader, transformFactory, dictionaryManager); AddReference(reference); } reader.ReadEndElement(); // SignedInfo if (reader.CanCanonicalize) reader.EndCanonicalization(); string[] inclusivePrefixes = GetInclusivePrefixes(); if (inclusivePrefixes != null) { // Clear the canonicalized stream. We cannot use this while inclusive prefixes are // specified. this.CanonicalStream = null; this.context = new Dictionary<string, string>(inclusivePrefixes.Length); for (int i = 0; i < inclusivePrefixes.Length; i++) { this.context.Add(inclusivePrefixes[i], reader.LookupNamespace(inclusivePrefixes[i])); } } } public override void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.SignedInfo, dictionaryManager.XmlSignatureDictionary.Namespace); if (this.Id != null) { writer.WriteAttributeString(dictionaryManager.UtilityDictionary.IdAttribute, null, this.Id); } WriteCanonicalizationMethod(writer, dictionaryManager); WriteSignatureMethod(writer, dictionaryManager); for (int i = 0; i < this.references.Count; i++) { this.references[i].WriteTo(writer, dictionaryManager); } writer.WriteEndElement(); // SignedInfo } protected override string GetNamespaceForInclusivePrefix(string prefix) { if (this.context == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); if (prefix == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("prefix"); return context[prefix]; } protected string Prefix { get { return prefix; } set { prefix = value; } } protected Dictionary<string, string> Context { get { return context; } set { context = value; } } } sealed class WifSignedInfo : StandardSignedInfo, IDisposable { MemoryStream _bufferedStream; string _defaultNamespace = String.Empty; bool _disposed; public WifSignedInfo(DictionaryManager dictionaryManager) : base(dictionaryManager) { } ~WifSignedInfo() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { // // Free all of our managed resources // if (_bufferedStream != null) { _bufferedStream.Close(); _bufferedStream = null; } } // Free native resources, if any. _disposed = true; } protected override void ComputeHash(HashStream hashStream) { if (SendSide) { using (XmlDictionaryWriter utf8Writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null, Encoding.UTF8, false)) { utf8Writer.StartCanonicalization(hashStream, false, null); WriteTo(utf8Writer, DictionaryManager); utf8Writer.EndCanonicalization(); } } else if (CanonicalStream != null) { CanonicalStream.WriteTo(hashStream); } else { _bufferedStream.Position = 0; // We are creating a XmlDictionaryReader with a hard-coded Max XmlDictionaryReaderQuotas. This is a reader that we // are creating over an already buffered content. The content was initially read off user provided XmlDictionaryReader // with the correct quotas and hence we know the data is valid. // Note: signedinfoReader will close _bufferedStream on Dispose. using (XmlDictionaryReader signedinfoReader = XmlDictionaryReader.CreateTextReader(_bufferedStream, XmlDictionaryReaderQuotas.Max)) { signedinfoReader.MoveToContent(); using (XmlDictionaryWriter bufferingWriter = XmlDictionaryWriter.CreateTextWriter(Stream.Null, Encoding.UTF8, false)) { bufferingWriter.WriteStartElement("a", _defaultNamespace); string[] inclusivePrefix = GetInclusivePrefixes(); for (int i = 0; i < inclusivePrefix.Length; ++i) { string ns = GetNamespaceForInclusivePrefix(inclusivePrefix[i]); if (ns != null) { bufferingWriter.WriteXmlnsAttribute(inclusivePrefix[i], ns); } } bufferingWriter.StartCanonicalization(hashStream, false, inclusivePrefix); bufferingWriter.WriteNode(signedinfoReader, false); bufferingWriter.EndCanonicalization(); bufferingWriter.WriteEndElement(); } } } } public override void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager) { reader.MoveToStartElement(XmlSignatureConstants.Elements.SignedInfo, XmlSignatureConstants.Namespace); SendSide = false; _defaultNamespace = reader.LookupNamespace(String.Empty); _bufferedStream = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.NewLineHandling = NewLineHandling.None; using (XmlWriter bufferWriter = XmlTextWriter.Create(_bufferedStream, settings)) { bufferWriter.WriteNode(reader, true); bufferWriter.Flush(); } _bufferedStream.Position = 0; // // We are creating a XmlDictionaryReader with a hard-coded Max XmlDictionaryReaderQuotas. This is a reader that we // are creating over an already buffered content. The content was initially read off user provided XmlDictionaryReader // with the correct quotas and hence we know the data is valid. // Note: effectiveReader will close _bufferedStream on Dispose. // using (XmlDictionaryReader effectiveReader = XmlDictionaryReader.CreateTextReader(_bufferedStream, XmlDictionaryReaderQuotas.Max)) { CanonicalStream = new MemoryStream(); effectiveReader.StartCanonicalization(CanonicalStream, false, null); effectiveReader.MoveToStartElement(XmlSignatureConstants.Elements.SignedInfo, XmlSignatureConstants.Namespace); Prefix = effectiveReader.Prefix; Id = effectiveReader.GetAttribute(WSSecurityUtilityConstants.Attributes.Id, null); effectiveReader.Read(); ReadCanonicalizationMethod(effectiveReader, DictionaryManager); ReadSignatureMethod(effectiveReader, DictionaryManager); while (effectiveReader.IsStartElement(XmlSignatureConstants.Elements.Reference, XmlSignatureConstants.Namespace)) { Reference reference = new Reference(DictionaryManager); reference.ReadFrom(effectiveReader, transformFactory, DictionaryManager); AddReference(reference); } effectiveReader.ReadEndElement(); effectiveReader.EndCanonicalization(); } string[] inclusivePrefixes = GetInclusivePrefixes(); if (inclusivePrefixes != null) { // Clear the canonicalized stream. We cannot use this while inclusive prefixes are // specified. CanonicalStream = null; Context = new Dictionary<string, string>(inclusivePrefixes.Length); for (int i = 0; i < inclusivePrefixes.Length; i++) { Context.Add(inclusivePrefixes[i], reader.LookupNamespace(inclusivePrefixes[i])); } } } } sealed class Reference { ElementWithAlgorithmAttribute digestMethodElement; DigestValueElement digestValueElement = new DigestValueElement(); string id; string prefix = SignedXml.DefaultPrefix; object resolvedXmlSource; readonly TransformChain transformChain = new TransformChain(); string type; string uri; SignatureResourcePool resourcePool; bool verified; string referredId; DictionaryManager dictionaryManager; public Reference(DictionaryManager dictionaryManager) : this(dictionaryManager, null) { } public Reference(DictionaryManager dictionaryManager, string uri) : this(dictionaryManager, uri, null) { } public Reference(DictionaryManager dictionaryManager, string uri, object resolvedXmlSource) { if (dictionaryManager == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dictionaryManager"); this.dictionaryManager = dictionaryManager; this.digestMethodElement = new ElementWithAlgorithmAttribute(dictionaryManager.XmlSignatureDictionary.DigestMethod); this.uri = uri; this.resolvedXmlSource = resolvedXmlSource; } public string DigestMethod { get { return this.digestMethodElement.Algorithm; } set { this.digestMethodElement.Algorithm = value; } } public XmlDictionaryString DigestMethodDictionaryString { get { return this.digestMethodElement.AlgorithmDictionaryString; } set { this.digestMethodElement.AlgorithmDictionaryString = value; } } public string Id { get { return this.id; } set { this.id = value; } } public SignatureResourcePool ResourcePool { get { return this.resourcePool; } set { this.resourcePool = value; } } public TransformChain TransformChain { get { return this.transformChain; } } public int TransformCount { get { return this.transformChain.TransformCount; } } public string Type { get { return this.type; } set { this.type = value; } } public string Uri { get { return this.uri; } set { this.uri = value; } } public bool Verified { get { return this.verified; } } public void AddTransform(Transform transform) { this.transformChain.Add(transform); } public void EnsureDigestValidity(string id, byte[] computedDigest) { if (!EnsureDigestValidityIfIdMatches(id, computedDigest)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException( SR.GetString(SR.RequiredTargetNotSigned, id))); } } public void EnsureDigestValidity(string id, object resolvedXmlSource) { if (!EnsureDigestValidityIfIdMatches(id, resolvedXmlSource)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException( SR.GetString(SR.RequiredTargetNotSigned, id))); } } public bool EnsureDigestValidityIfIdMatches(string id, byte[] computedDigest) { if (this.verified || id != ExtractReferredId()) { return false; } if (!CryptoHelper.IsEqual(computedDigest, GetDigestValue())) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CryptographicException(SR.GetString(SR.DigestVerificationFailedForReference, this.uri))); } this.verified = true; return true; } public bool EnsureDigestValidityIfIdMatches(string id, object resolvedXmlSource) { if (this.verified) { return false; } // During StrTransform the extractedReferredId on the reference will point to STR and hence will not be // equal to the referred element ie security token Id. if (id != ExtractReferredId() && !this.IsStrTranform()) { return false; } this.resolvedXmlSource = resolvedXmlSource; if (!CheckDigest()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CryptographicException(SR.GetString(SR.DigestVerificationFailedForReference, this.uri))); } this.verified = true; return true; } public bool IsStrTranform() { return this.TransformChain.TransformCount == 1 && this.TransformChain[0].Algorithm == SecurityAlgorithms.StrTransform; } public string ExtractReferredId() { if (this.referredId == null) { if (StringComparer.OrdinalIgnoreCase.Equals(uri, String.Empty)) { return String.Empty; } if (this.uri == null || this.uri.Length < 2 || this.uri[0] != '#') { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CryptographicException(SR.GetString(SR.UnableToResolveReferenceUriForSignature, this.uri))); } this.referredId = this.uri.Substring(1); } return this.referredId; } /// <summary> /// We look at the URI reference to decide if we should preserve comments while canonicalization. /// Only when the reference is xpointer(/) or xpointer(id(SomeId)) do we preserve comments during canonicalization /// of the reference element for computing the digest. /// </summary> /// <param name="uri">The Uri reference </param> /// <returns>true if comments should be preserved.</returns> private static bool ShouldPreserveComments(string uri) { bool preserveComments = false; if (!String.IsNullOrEmpty(uri)) { //removes the hash string idref = uri.Substring(1); if (idref == "xpointer(/)") { preserveComments = true; } else if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal) && (idref.IndexOf(")", StringComparison.Ordinal) > 0)) { // Dealing with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional preserveComments = true; } } return preserveComments; } public bool CheckDigest() { byte[] computedDigest = ComputeDigest(); bool result = CryptoHelper.IsEqual(computedDigest, GetDigestValue()); #if LOG_DIGESTS Console.WriteLine(">>> Checking digest for reference '{0}', result {1}", uri, result); Console.WriteLine(" Computed digest {0}", Convert.ToBase64String(computedDigest)); Console.WriteLine(" Received digest {0}", Convert.ToBase64String(GetDigestValue())); #endif return result; } public void ComputeAndSetDigest() { this.digestValueElement.Value = ComputeDigest(); } public byte[] ComputeDigest() { if (this.transformChain.TransformCount == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.EmptyTransformChainNotSupported))); } if (this.resolvedXmlSource == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException( SR.GetString(SR.UnableToResolveReferenceUriForSignature, this.uri))); } return this.transformChain.TransformToDigest(this.resolvedXmlSource, this.ResourcePool, this.DigestMethod, this.dictionaryManager); } public byte[] GetDigestValue() { return this.digestValueElement.Value; } public void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager) { reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.Reference, dictionaryManager.XmlSignatureDictionary.Namespace); this.prefix = reader.Prefix; this.Id = reader.GetAttribute(UtilityStrings.IdAttribute, null); this.Uri = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.URI, null); this.Type = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Type, null); reader.Read(); if (reader.IsStartElement(dictionaryManager.XmlSignatureDictionary.Transforms, dictionaryManager.XmlSignatureDictionary.Namespace)) { this.transformChain.ReadFrom(reader, transformFactory, dictionaryManager, ShouldPreserveComments(this.Uri)); } this.digestMethodElement.ReadFrom(reader, dictionaryManager); this.digestValueElement.ReadFrom(reader, dictionaryManager); reader.MoveToContent(); reader.ReadEndElement(); // Reference } public void SetResolvedXmlSource(object resolvedXmlSource) { this.resolvedXmlSource = resolvedXmlSource; } public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.Reference, dictionaryManager.XmlSignatureDictionary.Namespace); if (this.id != null) { writer.WriteAttributeString(dictionaryManager.UtilityDictionary.IdAttribute, null, this.id); } if (this.uri != null) { writer.WriteAttributeString(dictionaryManager.XmlSignatureDictionary.URI, null, this.uri); } if (this.type != null) { writer.WriteAttributeString(dictionaryManager.XmlSignatureDictionary.Type, null, this.type); } if (this.transformChain.TransformCount > 0) { this.transformChain.WriteTo(writer, dictionaryManager); } this.digestMethodElement.WriteTo(writer, dictionaryManager); this.digestValueElement.WriteTo(writer, dictionaryManager); writer.WriteEndElement(); // Reference } struct DigestValueElement { byte[] digestValue; string digestText; string prefix; internal byte[] Value { get { return this.digestValue; } set { this.digestValue = value; this.digestText = null; } } public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager) { reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.DigestValue, dictionaryManager.XmlSignatureDictionary.Namespace); this.prefix = reader.Prefix; reader.Read(); reader.MoveToContent(); this.digestText = reader.ReadString(); this.digestValue = System.Convert.FromBase64String(digestText.Trim()); reader.MoveToContent(); reader.ReadEndElement(); // DigestValue } public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { writer.WriteStartElement(this.prefix ?? XmlSignatureStrings.Prefix, dictionaryManager.XmlSignatureDictionary.DigestValue, dictionaryManager.XmlSignatureDictionary.Namespace); if (this.digestText != null) { writer.WriteString(this.digestText); } else { writer.WriteBase64(this.digestValue, 0, this.digestValue.Length); } writer.WriteEndElement(); // DigestValue } } } sealed class TransformChain { string prefix = SignedXml.DefaultPrefix; MostlySingletonList<Transform> transforms; public TransformChain() { } public int TransformCount { get { return this.transforms.Count; } } public Transform this[int index] { get { return this.transforms[index]; } } public bool NeedsInclusiveContext { get { for (int i = 0; i < this.TransformCount; i++) { if (this[i].NeedsInclusiveContext) { return true; } } return false; } } public void Add(Transform transform) { this.transforms.Add(transform); } public void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager, bool preserveComments) { reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.Transforms, dictionaryManager.XmlSignatureDictionary.Namespace); this.prefix = reader.Prefix; reader.Read(); while (reader.IsStartElement(dictionaryManager.XmlSignatureDictionary.Transform, dictionaryManager.XmlSignatureDictionary.Namespace)) { string transformAlgorithmUri = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null); Transform transform = transformFactory.CreateTransform(transformAlgorithmUri); transform.ReadFrom(reader, dictionaryManager, preserveComments); Add(transform); } reader.MoveToContent(); reader.ReadEndElement(); // Transforms if (this.TransformCount == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.AtLeastOneTransformRequired))); } } public byte[] TransformToDigest(object data, SignatureResourcePool resourcePool, string digestMethod, DictionaryManager dictionaryManager) { DiagnosticUtility.DebugAssert(TransformCount > 0, ""); for (int i = 0; i < this.TransformCount - 1; i++) { data = this[i].Process(data, resourcePool, dictionaryManager); } return this[this.TransformCount - 1].ProcessAndDigest(data, resourcePool, digestMethod, dictionaryManager); } public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.Transforms, dictionaryManager.XmlSignatureDictionary.Namespace); for (int i = 0; i < this.TransformCount; i++) { this[i].WriteTo(writer, dictionaryManager); } writer.WriteEndElement(); // Transforms } } struct ElementWithAlgorithmAttribute { readonly XmlDictionaryString elementName; string algorithm; XmlDictionaryString algorithmDictionaryString; string prefix; public ElementWithAlgorithmAttribute(XmlDictionaryString elementName) { if (elementName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("elementName")); } this.elementName = elementName; this.algorithm = null; this.algorithmDictionaryString = null; this.prefix = SignedXml.DefaultPrefix; } public string Algorithm { get { return this.algorithm; } set { this.algorithm = value; } } public XmlDictionaryString AlgorithmDictionaryString { get { return this.algorithmDictionaryString; } set { this.algorithmDictionaryString = value; } } public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager) { reader.MoveToStartElement(this.elementName, dictionaryManager.XmlSignatureDictionary.Namespace); this.prefix = reader.Prefix; bool isEmptyElement = reader.IsEmptyElement; this.algorithm = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null); if (this.algorithm == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException( SR.GetString(SR.RequiredAttributeMissing, dictionaryManager.XmlSignatureDictionary.Algorithm, this.elementName))); } reader.Read(); reader.MoveToContent(); if (!isEmptyElement) { reader.MoveToContent(); reader.ReadEndElement(); } } public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { writer.WriteStartElement(this.prefix, this.elementName, dictionaryManager.XmlSignatureDictionary.Namespace); writer.WriteStartAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null); if (this.algorithmDictionaryString != null) { writer.WriteString(this.algorithmDictionaryString); } else { writer.WriteString(this.algorithm); } writer.WriteEndAttribute(); writer.WriteEndElement(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // define TRACE_LEAKS to get additional diagnostics that can lead to the leak sources. note: it will // make everything about 2-3x slower // // #define TRACE_LEAKS // define DETECT_LEAKS to detect possible leaks // #if DEBUG // #define DETECT_LEAKS //for now always enable DETECT_LEAKS in debug. // #endif using System; using System.Diagnostics; using System.Threading; #if DETECT_LEAKS using System.Runtime.CompilerServices; #endif namespace Jint.Pooling { /// <summary> /// Generic implementation of object pooling pattern with predefined pool size limit. The main /// purpose is that limited number of frequently used objects can be kept in the pool for /// further recycling. /// /// Notes: /// 1) it is not the goal to keep all returned objects. Pool is not meant for storage. If there /// is no space in the pool, extra returned objects will be dropped. /// /// 2) it is implied that if object was obtained from a pool, the caller will return it back in /// a relatively short time. Keeping checked out objects for long durations is ok, but /// reduces usefulness of pooling. Just new up your own. /// /// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice. /// Rationale: /// If there is no intent for reusing the object, do not use pool - just use "new". /// </summary> internal sealed class ConcurrentObjectPool<T> where T : class { [DebuggerDisplay("{Value,nq}")] private struct Element { internal T Value; } /// <remarks> /// Not using System.Func{T} because this file is linked into the (debugger) Formatter, /// which does not have that type (since it compiles against .NET 2.0). /// </remarks> internal delegate T Factory(); // Storage for the pool objects. The first item is stored in a dedicated field because we // expect to be able to satisfy most requests from it. private T _firstItem; private readonly Element[] _items; // factory is stored for the lifetime of the pool. We will call this only when pool needs to // expand. compared to "new T()", Func gives more flexibility to implementers and faster // than "new T()". private readonly Factory _factory; #if DETECT_LEAKS private static readonly ConditionalWeakTable<T, LeakTracker> leakTrackers = new ConditionalWeakTable<T, LeakTracker>(); private class LeakTracker : IDisposable { private volatile bool disposed; #if TRACE_LEAKS internal volatile object Trace = null; #endif public void Dispose() { disposed = true; GC.SuppressFinalize(this); } private string GetTrace() { #if TRACE_LEAKS return Trace == null ? "" : Trace.ToString(); #else return "Leak tracing information is disabled. Define TRACE_LEAKS on ObjectPool`1.cs to get more info \n"; #endif } ~LeakTracker() { if (!this.disposed && !Environment.HasShutdownStarted) { var trace = GetTrace(); // If you are seeing this message it means that object has been allocated from the pool // and has not been returned back. This is not critical, but turns pool into rather // inefficient kind of "new". Debug.WriteLine($"TRACEOBJECTPOOLLEAKS_BEGIN\nPool detected potential leaking of {typeof(T)}. \n Location of the leak: \n {GetTrace()} TRACEOBJECTPOOLLEAKS_END"); } } } #endif internal ConcurrentObjectPool(Factory factory) : this(factory, Environment.ProcessorCount * 2) { } internal ConcurrentObjectPool(Factory factory, int size) { Debug.Assert(size >= 1); _factory = factory; _items = new Element[size - 1]; } private T CreateInstance() { var inst = _factory(); return inst; } /// <summary> /// Produces an instance. /// </summary> /// <remarks> /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. /// Note that Free will try to store recycled objects close to the start thus statistically /// reducing how far we will typically search. /// </remarks> internal T Allocate() { // PERF: Examine the first element. If that fails, AllocateSlow will look at the remaining elements. // Note that the initial read is optimistically not synchronized. That is intentional. // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. T inst = _firstItem; if (inst == null || inst != Interlocked.CompareExchange(ref _firstItem, null, inst)) { inst = AllocateSlow(); } #if DETECT_LEAKS var tracker = new LeakTracker(); leakTrackers.Add(inst, tracker); #if TRACE_LEAKS var frame = CaptureStackTrace(); tracker.Trace = frame; #endif #endif return inst; } private T AllocateSlow() { var items = _items; for (int i = 0; i < items.Length; i++) { // Note that the initial read is optimistically not synchronized. That is intentional. // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. T inst = items[i].Value; if (inst != null) { if (inst == Interlocked.CompareExchange(ref items[i].Value, null, inst)) { return inst; } } } return CreateInstance(); } /// <summary> /// Returns objects to the pool. /// </summary> /// <remarks> /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. /// Note that Free will try to store recycled objects close to the start thus statistically /// reducing how far we will typically search in Allocate. /// </remarks> internal void Free(T obj) { Validate(obj); ForgetTrackedObject(obj); if (_firstItem == null) { // Intentionally not using interlocked here. // In a worst case scenario two objects may be stored into same slot. // It is very unlikely to happen and will only mean that one of the objects will get collected. _firstItem = obj; } else { FreeSlow(obj); } } private void FreeSlow(T obj) { var items = _items; for (int i = 0; i < items.Length; i++) { if (items[i].Value == null) { // Intentionally not using interlocked here. // In a worst case scenario two objects may be stored into same slot. // It is very unlikely to happen and will only mean that one of the objects will get collected. items[i].Value = obj; break; } } } /// <summary> /// Removes an object from leak tracking. /// /// This is called when an object is returned to the pool. It may also be explicitly /// called if an object allocated from the pool is intentionally not being returned /// to the pool. This can be of use with pooled arrays if the consumer wants to /// return a larger array to the pool than was originally allocated. /// </summary> [Conditional("DEBUG")] internal void ForgetTrackedObject(T old, T replacement = null) { #if DETECT_LEAKS LeakTracker tracker; if (leakTrackers.TryGetValue(old, out tracker)) { tracker.Dispose(); leakTrackers.Remove(old); } else { var trace = CaptureStackTrace(); Debug.WriteLine($"TRACEOBJECTPOOLLEAKS_BEGIN\nObject of type {typeof(T)} was freed, but was not from pool. \n Callstack: \n {trace} TRACEOBJECTPOOLLEAKS_END"); } if (replacement != null) { tracker = new LeakTracker(); leakTrackers.Add(replacement, tracker); } #endif } #if DETECT_LEAKS private static Lazy<Type> _stackTraceType = new Lazy<Type>(() => Type.GetType("System.Diagnostics.StackTrace")); private static object CaptureStackTrace() { return Activator.CreateInstance(_stackTraceType.Value); } #endif [Conditional("DEBUG")] private void Validate(object obj) { Debug.Assert(obj != null, "freeing null?"); Debug.Assert(_firstItem != obj, "freeing twice?"); var items = _items; for (int i = 0; i < items.Length; i++) { var value = items[i].Value; if (value == null) { return; } Debug.Assert(value != obj, "freeing twice?"); } } }}
// /* // SharpNative - C# to D Transpiler // (C) 2014 Irio Systems // */ #region Imports using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; #endregion namespace SharpNative.Compiler { public static class RoslynExtensions { public static bool IsSubclassOf(this ITypeSymbol type, ITypeSymbol baseTypeSymbol) { if (type == null || type.BaseType == null) return false; if (type.BaseType == baseTypeSymbol || type.AllInterfaces.Contains(baseTypeSymbol)) return true; return IsSubclassOf(type.BaseType, baseTypeSymbol); } // public static string GetFullName(this INamespaceSymbol namespaceSymbol) { string result = namespaceSymbol.MetadataName; if (!namespaceSymbol.IsGlobalNamespace && !namespaceSymbol.ContainingNamespace.IsGlobalNamespace) { result = Context.Instance.SymbolNames[ namespaceSymbol.ContainingNamespace, namespaceSymbol.ContainingNamespace.GetFullName()] + "." + result; } return result; } // public static string GetFullName(this ITypeSymbol type) // { // if (type.IsAnonymousType) // { // return type.GetTypeName(); // } // if (type is IArrayTypeSymbol) // { // var arrayType = (IArrayTypeSymbol)type; // return arrayType.ElementType.GetFullName() + "[]"; // } // // var typeParameter = type as ITypeParameterSymbol; // if (typeParameter != null) // { // return typeParameter.Name; // } // else // { // string result = type.MetadataName; // if (type.ContainingType != null) // result = type.ContainingType.GetFullName() + "." + result; // else if (!type.ContainingNamespace.IsGlobalNamespace) // result = type.ContainingNamespace.GetFullName() + "." + result; // return result; // } // } public static bool IsAssignableFrom(this ITypeSymbol baseType, ITypeSymbol type) { if (IsImplicitNumericCast(baseType, type)) return true; var current = type; while (current != null) { if (Equals(current, baseType)) return true; current = current.BaseType; } foreach (var intf in type.AllInterfaces) { if (Equals(intf, baseType)) return true; } return false; } private static bool IsImplicitNumericCast(ITypeSymbol baseType, ITypeSymbol type) { if (type.SpecialType == SpecialType.System_SByte) { switch (baseType.SpecialType) { case SpecialType.System_SByte: // Safety precaution? case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Char) { switch (baseType.SpecialType) { case SpecialType.System_Char: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Byte) { switch (baseType.SpecialType) { case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Int16) { switch (baseType.SpecialType) { case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_UInt16) { switch (baseType.SpecialType) { case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Int32) { switch (baseType.SpecialType) { case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_UInt32) { switch (baseType.SpecialType) { case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Int64) { switch (baseType.SpecialType) { case SpecialType.System_Int64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_Single) { switch (baseType.SpecialType) { case SpecialType.System_Single: case SpecialType.System_Double: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } if (type.SpecialType == SpecialType.System_UInt64) { switch (baseType.SpecialType) { case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: // TODO: Need to work on decimal, its treated as a normal int ... should we use D's 80-bit type ? return true; } } return false; } public static ITypeSymbol GetGenericArgument(this ITypeSymbol type, ITypeSymbol unconstructedType, int argumentIndex) { var current = type; while (current != null) { if (Equals(current.OriginalDefinition, unconstructedType)) return ((INamedTypeSymbol) current).TypeArguments[argumentIndex]; current = current.BaseType; } if (type is INamedTypeSymbol) { var namedTypeSymbol = (INamedTypeSymbol) type; foreach (var intf in namedTypeSymbol.AllInterfaces) { if (Equals(intf.OriginalDefinition, unconstructedType)) return intf.TypeArguments[argumentIndex]; } } return null; } public static T GetAttributeValue<T>(this ISymbol type, INamedTypeSymbol attributeType, string propertyName, T defaultValue = default(T)) { var jsAttribute = type.GetAttributes().SingleOrDefault(x => Equals(x.AttributeClass, attributeType)); if (jsAttribute != null) { // If the type is inlined, all the methods of the class will be written // at the same (root) level as the class declaration would have. This is useful // for creating Javascript-Global functions. var isInlinedArgument = jsAttribute.NamedArguments.SingleOrDefault(x => x.Key == propertyName); if (isInlinedArgument.Value.Value != null) return (T) isInlinedArgument.Value.Value; } return defaultValue; } public static ISymbol[] GetAllMembers(this INamedTypeSymbol type, string name) { if (type.BaseType != null) return type.BaseType.GetAllMembers(name).Concat(type.GetMembers(name).ToArray()).ToArray(); return type.GetMembers(name).ToArray(); } public static ISymbol[] GetAllMembers(this INamedTypeSymbol type) { if (type.BaseType != null) return type.BaseType.GetAllMembers().Concat(type.GetMembers().ToArray()).ToArray(); return type.GetMembers().ToArray(); } public static ITypeSymbol GetContainingType(this SyntaxNode node) { var classDeclaration = node.FirstAncestorOrSelf<ClassDeclarationSyntax>(x => true); if (classDeclaration == null) return null; return Context.Compilation.GetSemanticModel(classDeclaration.SyntaxTree).GetDeclaredSymbol(classDeclaration); } public static IMethodSymbol GetContainingMethod(this SyntaxNode node) { var method = node.FirstAncestorOrSelf<SyntaxNode>( x => x is ConstructorDeclarationSyntax || x is MethodDeclarationSyntax); if (method == null) return null; if (method is ConstructorDeclarationSyntax) { return Context.Compilation.GetSemanticModel(method.SyntaxTree) .GetDeclaredSymbol((ConstructorDeclarationSyntax) method); } return Context.Compilation.GetSemanticModel(method.SyntaxTree) .GetDeclaredSymbol((MethodDeclarationSyntax) method); } public static IMethodSymbol GetRootOverride(this IMethodSymbol method) { if (method.OverriddenMethod == null) return method; return method.OverriddenMethod.GetRootOverride(); } public static IPropertySymbol GetRootOverride(this IPropertySymbol property) { if (property.OverriddenProperty == null) return property; return property.OverriddenProperty.GetRootOverride(); } public static bool HasOrIsEnclosedInGenericParameters(this INamedTypeSymbol type) { return type.TypeParameters.Any() || (type.ContainingType != null && type.ContainingType.HasOrIsEnclosedInGenericParameters()); } /* public static bool HasOrIsEnclosedInUnconstructedType(this NamedTypeSymbol type) { return (type.TypeParameters.Count > 0 && type.TypeArguments.Any(x => IsUnconstructedType(x))) || (type.ContainingType != null && type.ContainingType.HasOrIsEnclosedInGenericParameters()); } */ public static bool IsUnconstructedType(this ITypeSymbol type) { var namedTypeSymbol = type as INamedTypeSymbol; if (type is ITypeParameterSymbol) return true; if (namedTypeSymbol != null) { return (namedTypeSymbol.TypeParameters.Any() && namedTypeSymbol.TypeArguments.Any(x => IsUnconstructedType(x))) || (type.ContainingType != null && type.ContainingType.IsUnconstructedType()); } return false; // namedTypeSymbol.ConstructedFrom.ToString() != namedTypeSymbol.ToString() && namedTypeSymbol.ConstructedFrom.ConstructedFrom.ToString() == namedTypeSymbol.ConstructedFrom.ToString() && namedTypeSymbol.HasOrIsEnclosedInGenericParameters() } public static ParameterSyntax[] GetParameters(this ExpressionSyntax lambda) { if (lambda is SimpleLambdaExpressionSyntax) return new[] {((SimpleLambdaExpressionSyntax) lambda).Parameter}; if (lambda is ParenthesizedLambdaExpressionSyntax) return ((ParenthesizedLambdaExpressionSyntax) lambda).ParameterList.Parameters.ToArray(); throw new Exception(); } public static CSharpSyntaxNode GetBody(this ExpressionSyntax lambda) { if (lambda is SimpleLambdaExpressionSyntax) return ((SimpleLambdaExpressionSyntax) lambda).Body; if (lambda is ParenthesizedLambdaExpressionSyntax) return ((ParenthesizedLambdaExpressionSyntax) lambda).Body; throw new Exception(); } /* public static bool IsAssignment(this SyntaxKind type) { switch (type) { case SyntaxKind.AssignExpression: case SyntaxKind.AddAssignExpression: case SyntaxKind.AndAssignExpression: case SyntaxKind.DivideAssignExpression: case SyntaxKind.ExclusiveOrAssignExpression: case SyntaxKind.LeftShiftAssignExpression: case SyntaxKind.RightShiftAssignExpression: case SyntaxKind.ModuloAssignExpression: case SyntaxKind.MultiplyAssignExpression: case SyntaxKind.OrAssignExpression: case SyntaxKind.SubtractAssignExpression: return true; default: return false; } } */ public static StatementSyntax GetNextStatement(this StatementSyntax statement) { if (statement.Parent is BlockSyntax) { var block = (BlockSyntax) statement.Parent; var indexOfStatement = block.Statements.IndexOf(statement); if (indexOfStatement == -1) throw new Exception(); if (indexOfStatement < block.Statements.Count - 1) return block.Statements[indexOfStatement + 1]; return null; } if (statement.Parent is SwitchSectionSyntax) { var section = (SwitchSectionSyntax) statement.Parent; var indexOfStatement = section.Statements.IndexOf(statement); if (indexOfStatement == -1) throw new Exception(); if (indexOfStatement < section.Statements.Count - 1) return section.Statements[indexOfStatement + 1]; return null; } return null; } public static IMethodSymbol GetMethodByName(this INamedTypeSymbol type, string name) { return type.GetMembers(name).OfType<IMethodSymbol>().Single(); } public static IMethodSymbol GetMethod(this INamedTypeSymbol type, string name, params ITypeSymbol[] parameterTypes) { IMethodSymbol method; if (!TryGetMethod(type, name, out method, parameterTypes)) throw new Exception(); return method; } public static bool TryGetMethod(this INamedTypeSymbol type, string name, out IMethodSymbol method, params ITypeSymbol[] parameterTypes) { var candidates = type.GetMembers(name).OfType<IMethodSymbol>().ToArray(); if (candidates.Length == 1) { method = candidates[0]; return true; } foreach (var candidate in candidates) { if (candidate.Parameters.Count() != parameterTypes.Length) continue; bool valid = true; foreach ( var item in parameterTypes.Zip(candidate.Parameters.Select(x => x.Type), (x, y) => new {ParameterType = x, Candidate = y})) { if (!Equals(item.Candidate, item.ParameterType)) { valid = false; break; } } if (valid) { method = candidate; return true; } } method = null; return false; } public static TypeSyntax ToTypeSyntax(this ITypeSymbol symbol) { return SyntaxFactory.ParseTypeName(symbol.ToDisplayString()); } public static InvocationExpressionSyntax Invoke(this IMethodSymbol method, params ExpressionSyntax[] arguments) { var methodTarget = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, method.ContainingType.ToTypeSyntax(), SyntaxFactory.IdentifierName(method.Name)); return arguments.Any() ? SyntaxFactory.InvocationExpression(methodTarget, SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList(arguments.Select(x => SyntaxFactory.Argument(x)), arguments.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken))))) : SyntaxFactory.InvocationExpression(methodTarget); } public static bool IsTrue(this ExpressionSyntax expression) { var literal = (LiteralExpressionSyntax) expression; return literal.Token.IsKind(SyntaxKind.TrueKeyword); } public static Compilation Recompile(this Compilation compilation, CompilationUnitSyntax compilationUnit) { var document = Context.Instance.Project.GetDocument(compilationUnit.SyntaxTree); document = document.WithSyntaxRoot(compilationUnit); SyntaxTree syntaxTree; document.TryGetSyntaxTree(out syntaxTree); compilation = compilation.ReplaceSyntaxTree(compilationUnit.SyntaxTree, syntaxTree); return compilation; } public static Compilation Recompile(this Compilation compilation, SyntaxNode oldNode, SyntaxNode newNode) { while (oldNode != null) { var oldParent = oldNode.Parent; var newParent = oldParent.ReplaceNode(oldNode, newNode); oldNode = oldParent; newNode = newParent; if (oldNode is CompilationUnitSyntax) break; } return compilation.Recompile((CompilationUnitSyntax) newNode); } public static INamedTypeSymbol FindType(this Compilation compilation, string fullName) { var result = compilation.GetTypeByMetadataName(fullName); if (result == null) { foreach ( var assembly in Context.Instance.Project.MetadataReferences.Select(compilation.GetAssemblyOrModuleSymbol) .Cast<IAssemblySymbol>()) { result = assembly.GetTypeByMetadataName(fullName); if (result != null) break; } } return result; } public static IEnumerable<ITypeSymbol> GetAllInnerTypes(this ITypeSymbol type) { foreach (var innerType in type.GetMembers().OfType<ITypeSymbol>()) { yield return innerType; foreach (var inner in innerType.GetAllInnerTypes()) yield return inner; } } public static void ReportError(this SyntaxNode node, string message) { var fileName = node.SyntaxTree.FilePath; var text = node.SyntaxTree.GetText(); var span = node.GetLocation().SourceSpan; var startLine = text.Lines.GetLinePosition(span.Start); var endLine = text.Lines.GetLinePosition(span.End); Console.WriteLine("{0} ({1},{2},{3},{4}): error: {5}", fileName, startLine.Line + 1, startLine.Character + 1, endLine.Line + 1, endLine.Character + 1, message); } public static bool IsPrimitive(this ITypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Decimal: case SpecialType.System_Double: case SpecialType.System_Enum: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Nullable_T: case SpecialType.System_SByte: case SpecialType.System_Single: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: return true; default: return false; } } public static bool IsPrimitiveInteger(this ITypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Decimal: case SpecialType.System_Double: case SpecialType.System_Enum: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_SByte: case SpecialType.System_Single: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: return true; default: return false; } } public static bool IsAsync(this MethodDeclarationSyntax method) { return method.Modifiers.Any(x => x.IsKind(SyntaxKind.AsyncKeyword)); } public static bool IsPointer(this ITypeSymbol type) { return type != null && type.IsValueType; } } }
using System; using System.Collections; // 13/6/03 namespace NBM.Plugin { #region Conversation enumerator and collection classes /// <summary> /// Enumerates over ConversationListenerCollection items /// </summary> internal class ConversationListenerEnumerator : IEnumerator, IDisposable { private int index = -1; private IList collection; /// <summary> /// /// </summary> /// <param name="collection"></param> public ConversationListenerEnumerator(ConversationListenerCollection collection) { this.collection = ArrayList.Synchronized(collection.Clone()); } /// <summary> /// /// </summary> object IEnumerator.Current { get { return Current; } } /// <summary> /// /// </summary> public IConversationListener Current { get { return (IConversationListener)collection[index]; } } /// <summary> /// /// </summary> public void Reset() { index = -1; } /// <summary> /// /// </summary> /// <returns></returns> public bool MoveNext() { if (index == -1) System.Threading.Monitor.Enter(collection.SyncRoot); return ++index < collection.Count; } /// <summary> /// /// </summary> public void Dispose() { System.Threading.Monitor.Exit(collection.SyncRoot); } } /// <summary> /// Contains type-safe and thread-safe access to a ConversationListener collection. /// </summary> internal class ConversationListenerCollection : IList, ICollection, IEnumerable, ICloneable { private ArrayList arrayList = new ArrayList(); /// <summary> /// /// </summary> /// <returns></returns> object ICloneable.Clone() { return this.Clone(); } /// <summary> /// /// </summary> /// <returns></returns> public ConversationListenerCollection Clone() { ConversationListenerCollection c = new ConversationListenerCollection(); c.arrayList.AddRange(this.arrayList); return c; } /// <summary> /// /// </summary> public ConversationListenerCollection() { } /// <summary> /// /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return new ConversationListenerEnumerator(this); } /// <summary> /// /// </summary> public int Count { get { return this.arrayList.Count; } } /// <summary> /// /// </summary> /// <param name="array"></param> /// <param name="count"></param> public void CopyTo(Array array, int count) { this.arrayList.CopyTo(array, count); } /// <summary> /// /// </summary> public bool IsSynchronized { get { return this.arrayList.IsSynchronized; } } /// <summary> /// /// </summary> public object SyncRoot { get { return this.arrayList.SyncRoot; } } /// <summary> /// /// </summary> public bool IsFixedSize { get { return arrayList.IsFixedSize; } } /// <summary> /// /// </summary> public bool IsReadOnly { get { return arrayList.IsReadOnly; } } /// <summary> /// /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (IConversationListener)value; } } /// <summary> /// /// </summary> public IConversationListener this[int index] { get { return (IConversationListener)this.arrayList[index]; } set { this.arrayList[index] = value; } } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> int IList.Add(object o) { return Add((IConversationListener)o); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> public int Add(IConversationListener o) { return this.arrayList.Add(o); } /// <summary> /// /// </summary> public void Clear() { arrayList.Clear(); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> bool IList.Contains(object o) { return Contains((IConversationListener)o); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> public bool Contains(IConversationListener o) { return this.arrayList.Contains(o); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> int IList.IndexOf(object o) { return IndexOf((IConversationListener)o); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> public int IndexOf(IConversationListener o) { return this.arrayList.IndexOf(o); } /// <summary> /// /// </summary> /// <param name="index"></param> /// <param name="o"></param> void IList.Insert(int index, object o) { Insert(index, (IConversationListener)o); } /// <summary> /// /// </summary> /// <param name="index"></param> /// <param name="o"></param> public void Insert(int index, IConversationListener o) { this.arrayList.Insert(index, o); } /// <summary> /// /// </summary> /// <param name="o"></param> void IList.Remove(object o) { Remove((IConversationListener)o); } /// <summary> /// /// </summary> /// <param name="o"></param> public void Remove(IConversationListener o) { this.arrayList.Remove(o); } /// <summary> /// /// </summary> /// <param name="index"></param> public void RemoveAt(int index) { arrayList.RemoveAt(index); } } #endregion /// <summary> /// Provides an observer for the "server side" - ie the UI side of NBM /// for conversations. This is not used by plugins. /// </summary> public class ConversationServer { private ConversationListenerCollection listenerList = new ConversationListenerCollection(); private ProtocolServer protocolServer; /// <summary> /// Constructs a ConversationServer /// </summary> /// <param name="protocolServer">Protocol server to attach to</param> public ConversationServer(ProtocolServer protocolServer) { this.protocolServer = protocolServer; } #region Server methods /// <summary> /// Occurs when the conversation connects /// </summary> public void OnConnected() { foreach (IConversationListener listener in this.listenerList) { listener.OnConversationConnected(); } } /// <summary> /// Occurs when the conversation disconnects /// </summary> public void OnDisconnected() { foreach (IConversationListener listener in this.listenerList) { listener.OnConversationDisconnected(); } } #endregion #region Conversation control methods /// <summary> /// Add an observer to the conversation server /// </summary> /// <param name="listener"></param> public void AddListener(IConversationListener listener) { if (!this.listenerList.Contains(listener)) listenerList.Add(listener); } /// <summary> /// Remove an observer from the conversation server /// </summary> /// <param name="listener"></param> public void RemoveListener(IConversationListener listener) { listenerList.Remove(listener); } /// <summary> /// A friend in the conversation has just said something /// </summary> /// <param name="username">Friend's username</param> /// <param name="text">Message said</param> public void FriendSay(string username, string text) { Friend friend = this.protocolServer.GetFriend(username); if (friend == null) friend = new Friend(username, OnlineStatus.Online, null); FriendSay(friend, text); } /// <summary> /// A friend in the conversation has just said something /// </summary> /// <param name="friend">Friend</param> /// <param name="text">Message said</param> public void FriendSay(Friend friend, string text) { foreach (IConversationListener listener in this.listenerList) { listener.OnFriendSay(friend, text); } } /// <summary> /// A friend has just joined the conversation /// </summary> /// <param name="username">Username of friend</param> public void FriendJoin(string username) { Friend friend = this.protocolServer.GetFriend(username); if (friend == null) friend = new Friend(username, OnlineStatus.Online, null); FriendJoin(friend); } /// <summary> /// A friend has just joined the conversation /// </summary> /// <param name="friend">Friend</param> public void FriendJoin(Friend friend) { foreach (IConversationListener listener in this.listenerList) { listener.OnFriendJoin(friend); } } /// <summary> /// Friend has just left the conversation /// </summary> /// <param name="username">Username of friend who has left</param> public void FriendLeave(string username) { Friend friend = this.protocolServer.GetFriend(username); if (friend == null) friend = new Friend(username, OnlineStatus.Online, null); FriendLeave(friend); } /// <summary> /// Friend has just left the conversation /// </summary> /// <param name="friend">Friend</param> public void FriendLeave(Friend friend) { foreach (IConversationListener listener in this.listenerList) { listener.OnFriendLeave(friend); } } /// <summary> /// Typing notification received by plugin /// </summary> /// <param name="username">Username of typer</param> public void TypingNotification(string username) { Friend friend = this.protocolServer.GetFriend(username); if (friend == null) friend = new Friend(username, OnlineStatus.Online, null); TypingNotification(friend); } /// <summary> /// Typing notification received by plugin /// </summary> /// <param name="friend">Friend typing</param> public void TypingNotification(Friend friend) { foreach (IConversationListener listener in this.listenerList) { listener.OnTypingNotification(friend); } } /// <summary> /// Creates a proxy connection /// </summary> /// <returns>Connection to use</returns> public Proxy.IConnection CreateConnection() { return this.protocolServer.CreateConnection(); } /// <summary> /// Occurs when the user has said something /// </summary> /// <param name="text">Message to send to conversation</param> public void UserSay(string text) { foreach (IConversationListener listener in this.listenerList) { listener.OnUserSay(text); } } /// <summary> /// When a file invitation is received by another party /// </summary> /// <param name="friend">Friend who's sending the file</param> /// <param name="filename">Filename of file</param> public void FileSendInvitation(Friend friend, string filename) { foreach (IConversationListener listener in this.listenerList) { listener.OnFileSendInvitation(friend, filename); } } /// <summary> /// Call this when a file transfer invitation is received by someone else /// </summary> /// <param name="username">Friend who's sending the file</param> /// <param name="filename">Filename</param> public void FileSendInvitation(string username, string filename) { Friend friend = this.protocolServer.GetFriend(username); if (friend == null) friend = new Friend(username, OnlineStatus.Online, null); FileSendInvitation(friend, filename); } #endregion } }
// // TreeViewBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin 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 MonoMac.AppKit; using MonoMac.Foundation; using Xwt.Backends; using System.Collections.Generic; namespace Xwt.Mac { public class TreeViewBackend: TableViewBackend<NSOutlineView,ITreeViewEventSink>, ITreeViewBackend { ITreeDataSource source; TreeSource tsource; class TreeDelegate: NSOutlineViewDelegate { public TreeViewBackend Backend; public override void ItemDidExpand (NSNotification notification) { Backend.EventSink.OnRowExpanded (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override void ItemWillExpand (NSNotification notification) { Backend.EventSink.OnRowExpanding (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override void ItemDidCollapse (NSNotification notification) { Backend.EventSink.OnRowCollapsed (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override void ItemWillCollapse (NSNotification notification) { Backend.EventSink.OnRowCollapsing (((TreeItem)notification.UserInfo["NSObject"]).Position); } } NSOutlineView Tree { get { return (NSOutlineView) Table; } } protected override NSTableView CreateView () { var t = new OutlineViewBackend (EventSink, ApplicationContext); t.Delegate = new TreeDelegate () { Backend = this }; return t; } protected override string SelectionChangeEventName { get { return "NSOutlineViewSelectionDidChangeNotification"; } } public TreePosition CurrentEventRow { get; internal set; } public override NSTableColumn AddColumn (ListViewColumn col) { NSTableColumn tcol = base.AddColumn (col); if (Tree.OutlineTableColumn == null) Tree.OutlineTableColumn = tcol; return tcol; } public void SetSource (ITreeDataSource source, IBackend sourceBackend) { this.source = source; tsource = new TreeSource (source); Tree.DataSource = tsource; source.NodeInserted += (sender, e) => Tree.ReloadItem (tsource.GetItem (source.GetParent(e.Node)), true); source.NodeDeleted += (sender, e) => Tree.ReloadItem (tsource.GetItem (e.Node), true); source.NodeChanged += (sender, e) => Tree.ReloadItem (tsource.GetItem (e.Node), false); source.NodesReordered += (sender, e) => Tree.ReloadItem (tsource.GetItem (e.Node), true); } public override object GetValue (object pos, int nField) { return source.GetValue ((TreePosition)pos, nField); } public override void SetValue (object pos, int nField, object value) { source.SetValue ((TreePosition)pos, nField, value); } public TreePosition[] SelectedRows { get { TreePosition[] res = new TreePosition [Table.SelectedRowCount]; int n = 0; if (Table.SelectedRowCount > 0) { foreach (var i in Table.SelectedRows) { res [n] = ((TreeItem)Tree.ItemAtRow ((int)i)).Position; } } return res; } } public override void SetCurrentEventRow (object pos) { CurrentEventRow = (TreePosition)pos; } public void SelectRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) Table.SelectRow (Tree.RowForItem (it), false); } public void UnselectRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) Table.DeselectRow (Tree.RowForItem (it)); } public bool IsRowSelected (TreePosition pos) { var it = tsource.GetItem (pos); return it != null && Table.IsRowSelected (Tree.RowForItem (it)); } public bool IsRowExpanded (TreePosition pos) { var it = tsource.GetItem (pos); return it != null && Tree.IsItemExpanded (it); } public void ExpandRow (TreePosition pos, bool expandChildren) { var it = tsource.GetItem (pos); if (it != null) Tree.ExpandItem (it, expandChildren); } public void CollapseRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) Tree.CollapseItem (it); } public void ScrollToRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) ScrollToRow (Tree.RowForItem (it)); } public void ExpandToRow (TreePosition pos) { var p = source.GetParent (pos); while (p != null) { var it = tsource.GetItem (p); if (it == null) break; Tree.ExpandItem (it, false); p = source.GetParent (p); } } public bool GetDropTargetRow (double x, double y, out RowDropPosition pos, out TreePosition nodePosition) { // Get row int row = Tree.GetRow(new System.Drawing.PointF ((float)x, (float)y)); pos = RowDropPosition.Into; nodePosition = null; if (row >= 0) { nodePosition = ((TreeItem)Tree.ItemAtRow (row)).Position; } return nodePosition != null; } /* protected override void OnDragOverCheck (NSDraggingInfo di, DragOverCheckEventArgs args) { base.OnDragOverCheck (di, args); var row = Tree.GetRow (new System.Drawing.PointF (di.DraggingLocation.X, di.DraggingLocation.Y)); if (row != -1) { var item = Tree.ItemAtRow (row); Tree.SetDropItem (item, row); } } protected override void OnDragOver (NSDraggingInfo di, DragOverEventArgs args) { base.OnDragOver (di, args); var p = Tree.ConvertPointFromView (di.DraggingLocation, null); var row = Tree.GetRow (p); if (row != -1) { Tree.SetDropRowDropOperation (row, NSTableViewDropOperation.On); var item = Tree.ItemAtRow (row); Tree.SetDropItem (item, 0); } }*/ } class TreeItem: NSObject, ITablePosition { public TreePosition Position; public TreeItem () { } public TreeItem (IntPtr p): base (p) { } object ITablePosition.Position { get { return Position; } } } class TreeSource: NSOutlineViewDataSource { ITreeDataSource source; // TODO: remove unused positions Dictionary<TreePosition,TreeItem> items = new Dictionary<TreePosition, TreeItem> (); public TreeSource (ITreeDataSource source) { this.source = source; source.NodeInserted += (sender, e) => { if (!items.ContainsKey (e.Node)) items.Add (e.Node, new TreeItem { Position = e.Node }); }; } public TreeItem GetItem (TreePosition pos) { if (pos == null) return null; TreeItem it; items.TryGetValue (pos, out it); return it; } public override bool AcceptDrop (NSOutlineView outlineView, NSDraggingInfo info, NSObject item, int index) { return false; } public override string[] FilesDropped (NSOutlineView outlineView, NSUrl dropDestination, NSArray items) { throw new NotImplementedException (); } public override NSObject GetChild (NSOutlineView outlineView, int childIndex, NSObject ofItem) { var item = (TreeItem) ofItem; var pos = source.GetChild (item != null ? item.Position : null, childIndex); if (pos != null) { TreeItem res; if (!items.TryGetValue (pos, out res)) items [pos] = res = new TreeItem () { Position = pos }; return res; } else return null; } public override int GetChildrenCount (NSOutlineView outlineView, NSObject item) { var it = (TreeItem) item; return source.GetChildrenCount (it != null ? it.Position : null); } public override NSObject GetObjectValue (NSOutlineView outlineView, NSTableColumn forTableColumn, NSObject byItem) { return byItem; } public override void SetObjectValue (NSOutlineView outlineView, NSObject theObject, NSTableColumn tableColumn, NSObject item) { } public override bool ItemExpandable (NSOutlineView outlineView, NSObject item) { return GetChildrenCount (outlineView, item) > 0; } public override NSObject ItemForPersistentObject (NSOutlineView outlineView, NSObject theObject) { return null; } public override bool OutlineViewwriteItemstoPasteboard (NSOutlineView outlineView, NSArray items, NSPasteboard pboard) { return false; } public override NSObject PersistentObjectForItem (NSOutlineView outlineView, NSObject item) { return null; } public override void SortDescriptorsChanged (NSOutlineView outlineView, NSSortDescriptor[] oldDescriptors) { } public override NSDragOperation ValidateDrop (NSOutlineView outlineView, NSDraggingInfo info, NSObject item, int index) { return NSDragOperation.None; } protected override void Dispose (bool disposing) { base.Dispose (disposing); } } }
// 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.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Mapping; using System.Windows; using MessageBox = ArcGIS.Desktop.Framework.Dialogs.MessageBox; using ComboBox = ArcGIS.Desktop.Framework.Contracts.ComboBox; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Core.CIM; using ArcGIS.Desktop.Core; namespace Colorizer { /// <summary> /// Represents the Apply Colorizers ComboBox. /// </summary> internal class ApplyAttributes : ComboBox { BasicRasterLayer basicRasterLayer = null; // holds the names of field names in the raster's attribute table private List<string> _fieldList = new List<string>(); /// <summary> /// Combo Box constructor. Make sure the combox box is enabled if raster layer is selected /// and subscribe to the layer selection changed event. /// </summary> public ApplyAttributes() { SelectedLayersChanged(new ArcGIS.Desktop.Mapping.Events.MapViewEventArgs(MapView.Active)); ArcGIS.Desktop.Mapping.Events.TOCSelectionChangedEvent.Subscribe(SelectedLayersChanged); Add(new ComboBoxItem("Msg: Select a Raster in the TOC")); } /// <summary> /// Event handler for layer selection changes. /// </summary> private async void SelectedLayersChanged(ArcGIS.Desktop.Mapping.Events.MapViewEventArgs mapViewArgs) { // Clears the combo box items when layer selection changes. Clear(); // Checks the state of the active pane. // Returns the active pane state if the active pane is not null, else returns null. State state = (FrameworkApplication.Panes.ActivePane != null) ? FrameworkApplication.Panes.ActivePane.State : null; if (state != null && mapViewArgs.MapView != null) { // Gets the selected layers from the current Map. IReadOnlyList<Layer> selectedLayers = mapViewArgs.MapView.GetSelectedLayers(); // The combo box will update only if one layer is selected. if (selectedLayers.Count == 1) { // Gets the selected layer. Layer firstSelectedLayer = selectedLayers.First(); // The combo box will update only if a raster layer is selected. if (firstSelectedLayer != null && (firstSelectedLayer is BasicRasterLayer || firstSelectedLayer is MosaicLayer)) { // Gets the basic raster layer from the selected layer. if (firstSelectedLayer is BasicRasterLayer) basicRasterLayer = (BasicRasterLayer)firstSelectedLayer; else if (firstSelectedLayer is MosaicLayer) basicRasterLayer = ((MosaicLayer)firstSelectedLayer).GetImageLayer() as BasicRasterLayer; // Updates the combo box with the corresponding colorizers for the selected layer. await UpdateCombo(basicRasterLayer); // Sets the combo box to display the first combo box item. SelectedIndex = 0; } } } } /// <summary> /// Destructor. Unsubscribe from the layer selection changed event. /// </summary> ~ApplyAttributes() { ArcGIS.Desktop.Mapping.Events.TOCSelectionChangedEvent.Unsubscribe(SelectedLayersChanged); Clear(); } /// <summary> /// Updates the combo box with the raster's attribute table field names. /// </summary> /// <param name="basicRasterLayer">the selected layer.</param> private async Task UpdateCombo(BasicRasterLayer basicRasterLayer) { try { _fieldList.Clear(); await QueuedTask.Run(() => { var rasterTbl = basicRasterLayer.GetRaster().GetAttributeTable(); if (rasterTbl == null) return; var fields = rasterTbl.GetDefinition().GetFields(); foreach (var field in fields) { _fieldList.Add(field.Name); } }); bool hasRgb = _fieldList.Contains("red", StringComparer.OrdinalIgnoreCase) && _fieldList.Contains("green", StringComparer.OrdinalIgnoreCase) && _fieldList.Contains("blue", StringComparer.OrdinalIgnoreCase); if (_fieldList.Count == 0) { Add(new ComboBoxItem("Msg: Raster has no Attribute table")); return; } foreach (var fieldName in _fieldList) { Add(new ComboBoxItem(fieldName)); } if (hasRgb) { Add(new ComboBoxItem(@"Attribute driven RGB")); } } catch (Exception ex) { MessageBox.Show($@"Exception caught on Update combo box: {ex.Message}", "Exception", MessageBoxButton.OK, MessageBoxImage.Error); } } /// <summary> /// The on comboBox selection change event. /// </summary> /// <param name="item">The newly selected combo box item</param> protected override void OnSelectionChange(ComboBoxItem item) { if (item == null) MessageBox.Show("The combo box item is null.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error); if (item.Text.StartsWith("Msg: ")) return; if (string.IsNullOrEmpty(item.Text)) MessageBox.Show("The combo box item text is null or empty.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error); if (MapView.Active == null) MessageBox.Show("There is no active MapView.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error); try { // Gets the first selected layer in the active MapView. Layer firstSelectedLayer = MapView.Active.GetSelectedLayers().First(); // Gets the BasicRasterLayer from the selected layer. if (firstSelectedLayer is BasicRasterLayer) basicRasterLayer = (BasicRasterLayer)firstSelectedLayer; else if (firstSelectedLayer is MosaicLayer) basicRasterLayer = ((MosaicLayer)firstSelectedLayer).GetImageLayer() as BasicRasterLayer; else MessageBox.Show("The selected layer is not a basic raster layer", "Select Layer Error:", MessageBoxButton.OK, MessageBoxImage.Error); if (basicRasterLayer != null) { switch (item.Text) { case @"Attribute driven RGB": SetRasterColorByRGBAttributeFields(basicRasterLayer as RasterLayer, _fieldList); break; default: var style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == "ArcGIS Colors"); SetRasterColorByAttributeField(basicRasterLayer as RasterLayer, item.Text, style); break; } } } catch (Exception ex) { MessageBox.Show("Exception caught in OnSelectionChange:" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error); } } private static async void SetRasterColorByRGBAttributeFields(RasterLayer raster, List<string>fields) { await QueuedTask.Run(() => { // set fieldName to the first column var fieldName = "n/a"; bool setFieldName = false; foreach (var attributeColumn in fields) { if (attributeColumn.Equals("value", StringComparison.OrdinalIgnoreCase)) setFieldName = true; else { if (setFieldName) { fieldName = attributeColumn; break; } } } var colorizerDef = new UniqueValueColorizerDefinition(fieldName); var colorizer = raster.CreateColorizer(colorizerDef); raster.SetColorizer(colorizer); }); } private static async void SetRasterColorByAttributeField(RasterLayer raster, string fieldName, StyleProjectItem styleProjItem) { await QueuedTask.Run(() => { var ramps = styleProjItem.SearchColorRamps("Green Blues"); CIMColorRamp colorRamp = ramps[0].ColorRamp; var colorizerDef = new UniqueValueColorizerDefinition(fieldName, colorRamp); var colorizer = raster.CreateColorizer(colorizerDef); // fix up colorizer ... due to a problem with getting the values for different attribute table fields: // we use the Raster's attribute table to collect a dictionary with the correct replacement values Dictionary<string, string> landuseToFieldValue = new Dictionary<string, string>(); if (colorizer is CIMRasterUniqueValueColorizer uvrColorizer) { var rasterTbl = raster.GetRaster().GetAttributeTable(); var cursor = rasterTbl.Search(); while (cursor.MoveNext()) { var row = cursor.Current; var correctField = row[fieldName].ToString(); var key = row[uvrColorizer.Groups[0].Heading].ToString(); landuseToFieldValue.Add(key.ToLower(), correctField); } uvrColorizer.Groups[0].Heading = fieldName; for (var idxGrp = 0; idxGrp < uvrColorizer.Groups[0].Classes.Length; idxGrp++) { var grpClass = uvrColorizer.Groups[0].Classes[idxGrp]; var oldValue = grpClass.Values[0].ToLower(); var correctField = landuseToFieldValue[oldValue]; grpClass.Values[0] = correctField; grpClass.Label = $@"{correctField}"; } } raster.SetColorizer(colorizer); }); } } }
using System; using System.Collections.Generic; using System.Text; using Xunit; namespace Microsoft.TemplateEngine.Utils.UnitTests { public class SemanticVersionTests { [Theory(DisplayName = nameof(SemanticVersionParse))] [InlineData("1", true, 1, 0, 0)] [InlineData("1-preview1", true, 1, 0, 0, "preview1")] [InlineData("1+build1", true, 1, 0, 0, null, "build1")] [InlineData("1-preview1+build1", true, 1, 0, 0, "preview1", "build1")] [InlineData("1.2", true, 1, 2, 0)] [InlineData("1.2-preview1", true, 1, 2, 0, "preview1")] [InlineData("1.2+build1", true, 1, 2, 0, null, "build1")] [InlineData("1.2-preview1+build1", true, 1, 2, 0, "preview1", "build1")] [InlineData("1.2.3", true, 1, 2, 3)] [InlineData("1.2.3-preview1", true, 1, 2, 3, "preview1")] [InlineData("1.2.3+build1", true, 1, 2, 3, null, "build1")] [InlineData("1.2.3-preview1+build1", true, 1, 2, 3, "preview1", "build1")] [InlineData("0.0.0", true)] [InlineData("01.0.0", false)] [InlineData("0.01.0", false)] [InlineData("0.0.01", false)] [InlineData("1.0.0-", false)] [InlineData("1.0.0+", false)] [InlineData("1.0.0-+", false)] [InlineData("1.0.0-1.1", true, 1, 0, 0, "1.1")] [InlineData("1.0.0-1!1", false)] [InlineData("1.0.0-00", false)] [InlineData("1.0.0-a.00.b", false)] [InlineData("1.0.0-0", true, 1, 0, 0, "0")] [InlineData("1.0.0+1.1", true, 1, 0, 0, null, "1.1")] [InlineData("1.0.0+1!1", false)] [InlineData("1.0.0+00", true, 1, 0, 0, null, "00")] [InlineData("1.0.0+0", true, 1, 0, 0, null, "0")] [InlineData("1.2.3.4", false)] public void SemanticVersionParse(string source, bool expectValid, int major = 0, int minor = 0, int patch = 0, string prerelease = null, string metadata = null) { SemanticVersion ver; if (expectValid) { Assert.True(SemanticVersion.TryParse(source, out ver), "Expected value to be a valid version, but it was not"); } else { Assert.False(SemanticVersion.TryParse(source, out ver), "Expected value to not be a valid version, but it was"); return; } Assert.Equal(major, ver.Major); Assert.Equal(minor, ver.Minor); Assert.Equal(patch, ver.Patch); Assert.Equal(prerelease, ver.PrereleaseInfo); Assert.Equal(metadata, ver.BuildMetadata); } [Theory(DisplayName = nameof(SemanticVersionCompareTo))] [InlineData("1.0.0", "1.0.0-beta1", true, false)] [InlineData("1.0.0", "1.0.0-beta1", true, true)] [InlineData("1.0.0", "1.0.0-beta1", null, false)] [InlineData("1.0.0-alpha.100", "1.0.0-alpha.99", true, true)] [InlineData("1.0.0-alpha.100", "1.0.0-alpha.99", true, false)] [InlineData("1.0.0-alpha.100", "1.0.0-alpha.99", null, false)] [InlineData("1.0.0-alpha.99.test", "1.0.0-alpha.99", true, true)] [InlineData("1.0.0-alpha.99.test", "1.0.0-alpha.99", true, false)] [InlineData("1.0.0-alpha.99.test", "1.0.0-alpha.99", null, false)] [InlineData("1.0.0-alpha.99", "1.0.0-alpha.test", false, false)] [InlineData("1.0.0-alpha.99", "1.0.0-alpha.test", false, true)] [InlineData("1.0.0-alpha.99", "1.0.0-alpha.test", null, false)] [InlineData("1.0.0-alpha1", "1.0.0-beta1", false, false)] [InlineData("1.0.0-alpha1", "1.0.0-beta1", false, true)] [InlineData("1.0.0-alpha1", "1.0.0-beta1", null, false)] [InlineData("1.0.0-beta1", "1.0.0-alpha1", true, false)] [InlineData("1.0.0-beta1", "1.0.0-alpha1", true, true)] [InlineData("1.0.0-beta1", "1.0.0-alpha1", null, false)] [InlineData("1.0.0-alpha1", "1.0.0-alpha1", true, true)] [InlineData("1.0.0-alpha1", "1.0.0-alpha1", false, true)] [InlineData("1.0.0-alpha1", "1.0.0-alpha1", null, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build42", true, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build42", false, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build42", null, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-beta1+build42", false, false)] [InlineData("1.0.0-alpha1+build42", "1.0.0-beta1+build42", false, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-beta1+build42", null, false)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build43", false, false)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build43", false, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build43", null, false)] // This is expected to differ from the Operators test - as build metada has to be accounted for when performing a comparison sort public void SemanticVersionCompareTo(string ver1, string ver2, bool? greater, bool equal) { Assert.True(SemanticVersion.TryParse(ver1, out SemanticVersion v1)); Assert.True(SemanticVersion.TryParse(ver2, out SemanticVersion v2)); if (equal) { if (!greater.HasValue) { Assert.True(v1.CompareTo(v2) == 0, $"Expected {ver1} CompareTo {ver2} to be equal to 0"); } else if (greater.Value) { Assert.True(v1.CompareTo(v2) >= 0, $"Expected {ver1} CompareTo {ver2} to be greater than or equal to 0"); } else { Assert.True(v1.CompareTo(v2) <= 0, $"Expected {ver1} CompareTo {ver2} to be less than or equal to 0"); } } else if (!greater.HasValue) { Assert.True(v1.CompareTo(v2) != 0, $"Expected {ver1} CompareTo {ver2} to not be equal to 0"); } else if (greater.Value) { Assert.True(v1.CompareTo(v2) > 0, $"Expected {ver1} CompareTo {ver2} to be greater than 0"); } else { Assert.True(v1.CompareTo(v2) < 0, $"Expected {ver1} CompareTo {ver2} to be less than 0"); } } [Theory(DisplayName = nameof(SemanticVersionOperators))] [InlineData("1.0.0", "1.0.0-beta1", true, false)] [InlineData("1.0.0", "1.0.0-beta1", true, true)] [InlineData("1.0.0", "1.0.0-beta1", null, false)] [InlineData("1.0.0-alpha1", "1.0.0-beta1", false, false)] [InlineData("1.0.0-alpha1", "1.0.0-beta1", false, true)] [InlineData("1.0.0-alpha1", "1.0.0-beta1", null, false)] [InlineData("1.0.0-alpha.100", "1.0.0-alpha.99", true, true)] [InlineData("1.0.0-alpha.100", "1.0.0-alpha.99", true, false)] [InlineData("1.0.0-alpha.100", "1.0.0-alpha.99", null, false)] [InlineData("1.0.0-alpha.99.test", "1.0.0-alpha.99", true, true)] [InlineData("1.0.0-alpha.99.test", "1.0.0-alpha.99", true, false)] [InlineData("1.0.0-alpha.99.test", "1.0.0-alpha.99", null, false)] [InlineData("1.0.0-alpha.99", "1.0.0-alpha.test", false, false)] [InlineData("1.0.0-alpha.99", "1.0.0-alpha.test", false, true)] [InlineData("1.0.0-alpha.99", "1.0.0-alpha.test", null, false)] [InlineData("1.0.0-beta1", "1.0.0-alpha1", true, false)] [InlineData("1.0.0-beta1", "1.0.0-alpha1", true, true)] [InlineData("1.0.0-beta1", "1.0.0-alpha1", null, false)] [InlineData("1.0.0-alpha1", "1.0.0-alpha1", true, true)] [InlineData("1.0.0-alpha1", "1.0.0-alpha1", false, true)] [InlineData("1.0.0-alpha1", "1.0.0-alpha1", null, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build42", true, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build42", false, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build42", null, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-beta1+build42", false, false)] [InlineData("1.0.0-alpha1+build42", "1.0.0-beta1+build42", false, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-beta1+build42", null, false)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build43", true, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build43", false, true)] [InlineData("1.0.0-alpha1+build42", "1.0.0-alpha1+build43", null, true)] // This is expected to differ from the CompareTo test - as build metada should be ignored public void SemanticVersionOperators(string ver1, string ver2, bool? greater, bool equal) { Assert.True(SemanticVersion.TryParse(ver1, out SemanticVersion v1)); Assert.True(SemanticVersion.TryParse(ver2, out SemanticVersion v2)); if (equal) { if (!greater.HasValue) { Assert.True(v1 == v2, $"Expected {ver1} == {ver2}"); } else if (greater.Value) { Assert.True(v1 >= v2, $"Expected {ver1} >= {ver2}"); } else { Assert.True(v1 <= v2, $"Expected {ver1} <= {ver2}"); } } else if (!greater.HasValue) { Assert.True(v1 != v2, $"Expected {ver1} != {ver2}"); } else if (greater.Value) { Assert.True(v1 > v2, $"Expected {ver1} > {ver2}"); } else { Assert.True(v1 < v2, $"Expected {ver1} < {ver2}"); } } [Fact(DisplayName = nameof(SemanticVersionObjectEquals))] public void SemanticVersionObjectEquals() { SemanticVersion.TryParse("1.0.0-beta1", out SemanticVersion a); SemanticVersion.TryParse("1.0.0-beta1", out SemanticVersion b); SemanticVersion.TryParse("1.0.0-beta1+build2", out SemanticVersion c); SemanticVersion.TryParse("1.0.0-beta2", out SemanticVersion d); Assert.True(a.Equals((object)b)); Assert.True(a.Equals((object)c)); Assert.False(a.Equals((object)d)); Assert.False(a.Equals(null)); } [Fact(DisplayName = nameof(SemanticVersionObjectEquals))] public void SemanticVersionObjectCompareTo() { SemanticVersion.TryParse("1.0.0-beta1", out SemanticVersion a); SemanticVersion.TryParse("1.0.0-beta1", out SemanticVersion b); SemanticVersion.TryParse("1.0.0-beta1+build2", out SemanticVersion c); SemanticVersion.TryParse("1.0.0-beta2", out SemanticVersion d); Assert.True(a.CompareTo((object)b) == 0); Assert.True(a.CompareTo((object)c) < 0); Assert.True(a.CompareTo((object)d) < 0); Assert.True(a.CompareTo(null) > 0); } [Fact(DisplayName = nameof(SemanticVersionObjectEquals))] public void SemanticVersionOperatorsAnNull() { SemanticVersion.TryParse("1.0.0-beta1", out SemanticVersion a); Assert.True(a > null, $"{a} > null failed"); Assert.True(a >= null, $"{a} >= null failed"); Assert.True(a != null, $"{a} != null failed"); Assert.False(a < null, $"{a} < null failed"); Assert.False(a <= null, $"{a} <= null failed"); Assert.False(a == null, $"{a} == null failed"); Assert.False(null > a, $"null > {a} failed"); Assert.False(null >= a, $"null >= {a} failed"); Assert.True(null != a, $"null != {a} failed"); Assert.True(null < a, $"null < {a} failed"); Assert.True(null <= a, $"null <= {a} failed"); Assert.False(null == a, $"null == {a} failed"); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime; using System.Runtime.Diagnostics; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; using System.Xml; static class MsmqDiagnostics { public static void CannotPeekOnQueue(string formatName, Exception ex) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent( TraceEventType.Warning, TraceCode.MsmqCannotPeekOnQueue, SR.GetString(SR.TraceCodeMsmqCannotPeekOnQueue), new StringTraceRecord("QueueFormatName", formatName), null, ex); } } public static void CannotReadQueues(string host, bool publicQueues, Exception ex) { if (DiagnosticUtility.ShouldTraceWarning) { Dictionary<string, string> dictionary = new Dictionary<string, string>(2); dictionary["Host"] = host; dictionary["PublicQueues"] = Convert.ToString(publicQueues, CultureInfo.InvariantCulture); TraceUtility.TraceEvent( TraceEventType.Warning, TraceCode.MsmqCannotReadQueues, SR.GetString(SR.TraceCodeMsmqCannotReadQueues), new DictionaryTraceRecord(dictionary), null, ex); } } public static ServiceModelActivity StartListenAtActivity(MsmqReceiveHelper receiver) { ServiceModelActivity activity = receiver.Activity; if (DiagnosticUtility.ShouldUseActivity && null == activity) { activity = ServiceModelActivity.CreateActivity(true); if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(activity.Id); } ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityListenAt, receiver.ListenUri.ToString()), ActivityType.ListenAt); } return activity; } public static Activity BoundOpenOperation(MsmqReceiveHelper receiver) { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.TransportListen, SR.GetString(SR.TraceCodeTransportListen, receiver.ListenUri.ToString()), receiver); } return ServiceModelActivity.BoundOperation(receiver.Activity); } public static Activity BoundReceiveOperation(MsmqReceiveHelper receiver) { if (DiagnosticUtility.ShouldUseActivity && null != ServiceModelActivity.Current && ActivityType.ProcessAction != ServiceModelActivity.Current.ActivityType) { return ServiceModelActivity.BoundOperation(receiver.Activity); } else { return null; } } public static ServiceModelActivity BoundDecodeOperation() { ServiceModelActivity activity = null; if (DiagnosticUtility.ShouldUseActivity) { activity = ServiceModelActivity.CreateBoundedActivity(true); ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessingMessage, TraceUtility.RetrieveMessageNumber()), ActivityType.ProcessMessage); } return activity; } public static ServiceModelActivity BoundReceiveBytesOperation() { ServiceModelActivity activity = null; if (DiagnosticUtility.ShouldUseActivity) { activity = ServiceModelActivity.CreateBoundedActivityWithTransferInOnly(Guid.NewGuid()); ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityReceiveBytes, TraceUtility.RetrieveMessageNumber()), ActivityType.ReceiveBytes); } return activity; } public static void TransferFromTransport(Message message) { if (DiagnosticUtility.ShouldUseActivity) { TraceUtility.TransferFromTransport(message); } } public static void ExpectedException(Exception ex) { DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information); } public static void ScanStarted() { if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.TraceEvent( TraceEventType.Verbose, TraceCode.MsmqScanStarted, SR.GetString(SR.TraceCodeMsmqScanStarted), null, null, null); } } public static void MatchedApplicationFound(string host, string queueName, bool isPrivate, string canonicalPath) { if (DiagnosticUtility.ShouldTraceInformation) { Dictionary<string, string> dictionary = new Dictionary<string, string>(4); dictionary["Host"] = host; dictionary["QueueName"] = queueName; dictionary["Private"] = Convert.ToString(isPrivate, CultureInfo.InvariantCulture); dictionary["CanonicalPath"] = canonicalPath; TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MsmqMatchedApplicationFound, SR.GetString(SR.TraceCodeMsmqMatchedApplicationFound), new DictionaryTraceRecord(dictionary), null, null); } } public static void StartingApplication(string application) { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MsmqStartingApplication, SR.GetString(SR.TraceCodeMsmqStartingApplication), new StringTraceRecord("Application", application), null, null); } } public static void StartingService(string host, string name, bool isPrivate, string processedVirtualPath) { if (DiagnosticUtility.ShouldTraceInformation) { Dictionary<string, string> dictionary = new Dictionary<string, string>(4); dictionary["Host"] = host; dictionary["Name"] = name; dictionary["Private"] = Convert.ToString(isPrivate, CultureInfo.InvariantCulture); dictionary["VirtualPath"] = processedVirtualPath; TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MsmqStartingService, SR.GetString(SR.TraceCodeMsmqStartingService), new DictionaryTraceRecord(dictionary), null, null); } } public static void FoundBaseAddress(Uri uri, string virtualPath) { if (DiagnosticUtility.ShouldTraceInformation) { Dictionary<string, string> dictionary = new Dictionary<string, string>(2) { { "Uri", uri.ToString() }, { "VirtualPath", virtualPath } }; TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MsmqFoundBaseAddress, SR.GetString(SR.TraceCodeMsmqFoundBaseAddress), new DictionaryTraceRecord(dictionary), null, null); } } static void DatagramSentOrReceived(NativeMsmqMessage.BufferProperty messageId, Message message, int traceCode, string traceDescription) { if (DiagnosticUtility.ShouldTraceVerbose) { Guid msmqId = MessageIdToGuid(messageId); UniqueId indigoId = message.Headers.MessageId; TraceRecord record = null; if (null == indigoId) { record = new StringTraceRecord("MSMQMessageId", msmqId.ToString()); } else { Dictionary<string, string> dictionary = new Dictionary<string, string>(2) { { "MSMQMessageId", msmqId.ToString() }, { "WCFMessageId", indigoId.ToString() } }; record = new DictionaryTraceRecord(dictionary); } TraceUtility.TraceEvent(TraceEventType.Verbose, traceCode, traceDescription, record, null, null); } } public static void DatagramReceived(NativeMsmqMessage.BufferProperty messageId, Message message) { DatagramSentOrReceived(messageId, message, TraceCode.MsmqDatagramReceived, SR.GetString(SR.TraceCodeMsmqDatagramReceived)); } public static void DatagramSent(NativeMsmqMessage.BufferProperty messageId, Message message) { DatagramSentOrReceived(messageId, message, TraceCode.MsmqDatagramSent, SR.GetString(SR.TraceCodeMsmqDatagramSent)); } static Guid MessageIdToGuid(NativeMsmqMessage.BufferProperty messageId) { if (UnsafeNativeMethods.PROPID_M_MSGID_SIZE != messageId.Buffer.Length) Fx.Assert(String.Format("Unexpected messageId size: {0}", messageId.Buffer.Length)); byte[] buffer = new byte[16]; Buffer.BlockCopy(messageId.Buffer, 4, buffer, 0, 16); return new Guid(buffer); } public static void MessageConsumed(string uri, string messageId, bool rejected) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent( TraceEventType.Warning, rejected ? TraceCode.MsmqMessageRejected : TraceCode.MsmqMessageDropped, rejected ? SR.GetString(SR.TraceCodeMsmqMessageRejected) : SR.GetString(SR.TraceCodeMsmqMessageDropped), new StringTraceRecord("MSMQMessageId", messageId), null, null); } if (PerformanceCounters.PerformanceCountersEnabled) { if (rejected) { PerformanceCounters.MsmqRejectedMessage(uri); } else { PerformanceCounters.MsmqDroppedMessage(uri); } } } public static void MessageLockedUnderTheTransaction(long lookupId) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent( TraceEventType.Warning, TraceCode.MsmqMessageLockedUnderTheTransaction, SR.GetString(SR.TraceCodeMsmqMessageLockedUnderTheTransaction), new StringTraceRecord("MSMQMessageLookupId", Convert.ToString(lookupId, CultureInfo.InvariantCulture)), null, null); } } public static void MoveOrDeleteAttemptFailed(long lookupId) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent( TraceEventType.Warning, TraceCode.MsmqMoveOrDeleteAttemptFailed, SR.GetString(SR.TraceCodeMsmqMoveOrDeleteAttemptFailed), new StringTraceRecord("MSMQMessageLookupId", Convert.ToString(lookupId, CultureInfo.InvariantCulture)), null, null); } } public static void MsmqDetected(Version version) { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MsmqDetected, SR.GetString(SR.TraceCodeMsmqDetected), new StringTraceRecord("MSMQVersion", version.ToString()), null, null); } } public static void PoisonMessageMoved(string messageId, bool poisonQueue, string uri) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent( TraceEventType.Warning, poisonQueue ? TraceCode.MsmqPoisonMessageMovedPoison : TraceCode.MsmqPoisonMessageMovedRetry, poisonQueue ? SR.GetString(SR.TraceCodeMsmqPoisonMessageMovedPoison) : SR.GetString(SR.TraceCodeMsmqPoisonMessageMovedRetry), new StringTraceRecord("MSMQMessageId", messageId), null, null); } if (poisonQueue && PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MsmqPoisonMessage(uri); } } public static void PoisonMessageRejected(string messageId, string uri) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent( TraceEventType.Warning, TraceCode.MsmqPoisonMessageRejected, SR.GetString(SR.TraceCodeMsmqPoisonMessageRejected), new StringTraceRecord("MSMQMessageId", messageId), null, null); } if (PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MsmqPoisonMessage(uri); } } static bool poolFullReported = false; public static void PoolFull(int poolSize) { if (DiagnosticUtility.ShouldTraceInformation && !poolFullReported) { TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MsmqPoolFull, SR.GetString(SR.TraceCodeMsmqPoolFull), null, null, null); poolFullReported = true; } } public static void PotentiallyPoisonMessageDetected(string messageId) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent( TraceEventType.Warning, TraceCode.MsmqPotentiallyPoisonMessageDetected, SR.GetString(SR.TraceCodeMsmqPotentiallyPoisonMessageDetected), new StringTraceRecord("MSMQMessageId", messageId), null, null); } } public static void QueueClosed(string formatName) { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MsmqQueueClosed, SR.GetString(SR.TraceCodeMsmqQueueClosed), new StringTraceRecord("FormatName", formatName), null, null); } } public static void QueueOpened(string formatName) { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.MsmqQueueOpened, SR.GetString(SR.TraceCodeMsmqQueueOpened), new StringTraceRecord("FormatName", formatName), null, null); } } public static void QueueTransactionalStatusUnknown(string formatName) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent( TraceEventType.Warning, TraceCode.MsmqQueueTransactionalStatusUnknown, SR.GetString(SR.TraceCodeMsmqQueueTransactionalStatusUnknown), new StringTraceRecord("FormatName", formatName), null, null); } } public static void SessiongramSent(string sessionId, NativeMsmqMessage.BufferProperty messageId, int numberOfMessages) { if (DiagnosticUtility.ShouldTraceVerbose) { Dictionary<string, string> dictionary = new Dictionary<string, string>(3); dictionary["SessionId"] = sessionId; dictionary["MSMQMessageId"] = MsmqMessageId.ToString(messageId.Buffer); dictionary["NumberOfMessages"] = Convert.ToString(numberOfMessages, CultureInfo.InvariantCulture); TraceUtility.TraceEvent( TraceEventType.Verbose, TraceCode.MsmqSessiongramSent, SR.GetString(SR.TraceCodeMsmqSessiongramSent), new DictionaryTraceRecord(dictionary), null, null); } } public static void SessiongramReceived(string sessionId, NativeMsmqMessage.BufferProperty messageId, int numberOfMessages) { if (DiagnosticUtility.ShouldTraceVerbose) { Dictionary<string, string> dictionary = new Dictionary<string, string>(3); dictionary["SessionId"] = sessionId; dictionary["MSMQMessageId"] = MsmqMessageId.ToString(messageId.Buffer); dictionary["NumberOfMessages"] = Convert.ToString(numberOfMessages, CultureInfo.InvariantCulture); TraceUtility.TraceEvent( TraceEventType.Verbose, TraceCode.MsmqSessiongramReceived, SR.GetString(SR.TraceCodeMsmqSessiongramReceived), new DictionaryTraceRecord(dictionary), null, null); } } public static void UnexpectedAcknowledgment(string messageId, int acknowledgment) { if (DiagnosticUtility.ShouldTraceVerbose) { Dictionary<string, string> dictionary = new Dictionary<string, string>(2); dictionary["MSMQMessageId"] = messageId; dictionary["Acknowledgment"] = Convert.ToString(acknowledgment, CultureInfo.InvariantCulture); TraceUtility.TraceEvent( TraceEventType.Verbose, TraceCode.MsmqUnexpectedAcknowledgment, SR.GetString(SR.TraceCodeMsmqUnexpectedAcknowledgment), new DictionaryTraceRecord(dictionary), null, null); } } } }
# if FALSE // File delete // For StringBuilder using System; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Security.Permissions; using NUnit.Framework; namespace Xsd2Db.Data.SqlClient.Test { internal class Settings { public static SqlConnection Connection; public static string ConnectionString = ((NameValueCollection) ConfigurationSettings.GetConfig("Xsd2Db.Data.SqlClient.Test"))["ConnectionString"]; } /// <summary> /// Tests the database connection. If this test fails, most of other tests will do too /// </summary> [TestFixture] public class SqlDataSchemaAdapterTestConnection { [SetUp] public void Start() { try { Settings.Connection = new SqlConnection(Settings.ConnectionString); Settings.Connection.Open(); // this conneciton will be closed in TeardownTestCreate } catch (Exception ex) { Trace.WriteLine(ex.Message); } } [Test] public void Run() { SqlCommand cmd = new SqlCommand("CREATE DATABASE ConnectionTest", Settings.Connection); cmd.ExecuteNonQuery(); SqlConnection conn = new SqlConnection(Settings.ConnectionString + ";Initial Catalog=ConnectionTest"); conn.Open(); SqlCommand command = new SqlCommand("select name from master.dbo.sysdatabases WHERE name = N'ConnectionTest'", conn); command.ExecuteScalar(); conn.Close(); } [TearDown] public void Stop() { SqlCommand cmd = new SqlCommand("DROP DATABASE ConnectionTest", Settings.Connection); cmd.ExecuteNonQuery(); Settings.Connection.Close(); } } /// <summary> /// Tests passing invalid arguments such as null references, etc. /// </summary> [TestFixture] public class SqlDataSchemaAdapterTestInvalidArguments { [Test] [ExpectedException(typeof (FileNotFoundException))] public void TestFileNotFound() { Settings.Connection = new SqlConnection(Settings.ConnectionString); Settings.Connection.Open(); SqlDataSchemaAdapter adapter = new SqlDataSchemaAdapter(Settings.Connection); adapter.CreateDatabase("file_not_found.xsd"); } [Test] [ExpectedException(typeof (ArgumentException))] public void TestNullConnection() { Settings.Connection = null; SqlDataSchemaAdapter adapter = new SqlDataSchemaAdapter(Settings.Connection); } [Test] [ExpectedException(typeof (ArgumentException))] public void TestInvalidConnection() { Settings.Connection = new SqlConnection(Settings.ConnectionString); SqlDataSchemaAdapter adapter = new SqlDataSchemaAdapter(Settings.Connection); } [Test] [ExpectedException(typeof (InvalidOperationException))] public void TestNoColumns() { // // Check to see if we have a connection to the database // Settings.Connection.Open(); SqlDataSchemaAdapter adapter = new SqlDataSchemaAdapter(Settings.Connection); // // Just making sure that the server doesn't already have a Test-Database // new SqlCommand("IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'Test-Database') DROP DATABASE [Test-Database]", Settings.Connection) .ExecuteNonQuery(); DataSet ds = new DataSet("Test-Database"); DataTable t = ds.Tables.Add(); DataTable t2 = ds.Tables.Add(); ds.WriteXmlSchema("test.xsd"); adapter.CreateDatabase("test.xsd"); } } /// <summary> /// Tests creation of relations such as primary keys and foreign keys /// </summary> [TestFixture] public class SqlDataSchemaAdapterTestRelations { [SetUp] public void SetupTestCreate() { Settings.Connection = new SqlConnection(Settings.ConnectionString); Settings.Connection.Open(); try { // // Just making sure that the server doesn't already have a Test-Database // new SqlCommand("IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'Test-Database') DROP DATABASE [Test-Database]", Settings.Connection) .ExecuteNonQuery(); } catch (Exception ex) { Trace.WriteLine(ex.Message); throw; } } [Test] [ReflectionPermission(SecurityAction.LinkDemand, Unrestricted=true)] public void TestRelations() { // // Setup a simple foreign key relation // DataSet ds = new DataSet("Test-Database"); DataTable master = ds.Tables.Add("Master"); DataColumn mid = master.Columns.Add("MasterID", Type.GetType("System.Guid")); DataColumn[] keys = new DataColumn[1]; keys[0] = mid; master.PrimaryKey = keys; DataColumn uniqueCol = master.Columns.Add("UniqueText", Type.GetType("System.String")); uniqueCol.Unique = true; uniqueCol.AllowDBNull = true; uniqueCol.MaxLength = 80; DataTable detail = ds.Tables.Add("Detail"); DataColumn did = detail.Columns.Add("DetailID", Type.GetType("System.Guid")); DataColumn mid_fk = detail.Columns.Add("MasterID_FK", Type.GetType("System.Guid")); DataColumn[] keys2 = new DataColumn[1]; keys2[0] = did; detail.PrimaryKey = keys2; ds.Relations.Add(mid, mid_fk); // // Write out the XSD // ds.WriteXmlSchema("test.xsd"); // // Create a database // SqlDataSchemaAdapter adapter = new SqlDataSchemaAdapter(Settings.Connection); adapter.CreateDatabase("test.xsd"); // // Check to see if SqlDataSchemaAdapter have created primary relations // SqlCommand insertCommand = new SqlCommand("USE [Test-Database] INSERT Master (MasterID) VALUES ('{37477C57-447D-4077-B96D-FE49D79045AA}')", Settings.Connection); int i = insertCommand.ExecuteNonQuery(); Assertion.Assert("Insert query failed. Expect 1 row affected", i == 1); // Try executing the same insert once again bool raisedSqlException = false; try { insertCommand.ExecuteNonQuery(); } catch (SqlException ex) { Assertion.Assert("Primary key constraint failed. Incompatible SqlException '" + ex.Message + "'", ex.Number == 2627); raisedSqlException = true; } Assertion.Assert("Primary key constraint failed. Expected SqlException", raisedSqlException); // // Check to see if SqlDataSchemaAdapter have created the foreign key relations // insertCommand = new SqlCommand("USE [Test-Database] INSERT Detail (DetailID, MasterID_FK) VALUES ('{37477C58-447D-4077-B96D-FE49D79045AA}', '{37477C57-447D-4077-B96D-FE49D79045AA}')", Settings.Connection); i = insertCommand.ExecuteNonQuery(); Assertion.Assert("Insert query failed. Expect 1 row affected", i == 1); // Try executing the same insert once again raisedSqlException = false; try { insertCommand.CommandText = "USE [Test-Database] INSERT Detail (DetailID, MasterID_FK) VALUES ('{37477C59-447D-4077-B96D-FE49D79045AA}', '{DEADBEEF-447D-4077-B96D-FE49D79045AA}')"; insertCommand.ExecuteNonQuery(); } catch (SqlException ex) { Assertion.Assert("Primary key constraint failed. Incompatible SqlException '" + ex.Message + "'", ex.Number == 547); raisedSqlException = true; } Assertion.Assert("Foreign key constraint failed. Expected SqlException", raisedSqlException); } [TearDown] public void TeardownTestCreate() { File.Delete("test.xsd"); // release connection to avoid locking the database Settings.Connection.Close(); Settings.Connection.Open(); new SqlCommand("DROP DATABASE [Test-Database]", Settings.Connection) .ExecuteNonQuery(); Settings.Connection.Close(); } } /// <summary> /// Test unusual cases of object naming /// </summary> [TestFixture] [ReflectionPermission(SecurityAction.LinkDemand, Unrestricted=true)] public class SqlDataSchemaAdapterTestNaming { [SetUp] public void SetupTestCreate() { try { DataSet ds = new DataSet("Test-Database"); DataTable t = ds.Tables.Add(); t.TableName = "TestTableOrders"; DataColumn pid1 = t.Columns.Add("OrderID", Type.GetType("System.Guid")); DataColumn[] keys = new DataColumn[1]; keys[0] = pid1; t.PrimaryKey = keys; DataColumn id1 = t.Columns.Add("CustomerID_FK", Type.GetType("System.Guid")); DataColumn str = t.Columns.Add("Nameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", Type.GetType("System.String")); str.MaxLength = 256; DataColumn txt = t.Columns.Add("SomeText", Type.GetType("System.String")); DataColumn int16 = t.Columns.Add("Some-Wired_Value--Name", Type.GetType("System.Int16")); int16.AllowDBNull = true; DataTable t2 = ds.Tables.Add(); t2.TableName = "TestTable-Customers"; DataColumn id2 = t2.Columns.Add("CustomerID", Type.GetType("System.Guid")); keys = new DataColumn[1]; keys[0] = id2; t2.PrimaryKey = keys; ds.Relations.Add(id2, id1); ds.WriteXmlSchema("test.xsd"); Settings.Connection = new SqlConnection(Settings.ConnectionString); Settings.Connection.Open(); // this conneciton will be closed in TeardownTestCreate /* * Just making sure that the server doesn't already have a Test-Database */ new SqlCommand("IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'Test-Database') DROP DATABASE [Test-Database]", Settings.Connection) .ExecuteNonQuery(); } catch (Exception ex) { Trace.WriteLine(ex.Message); throw; } } [Test] public void TestCreate() { SqlConnection tempConn = null; try { // Create a listener, which outputs to the console screen, and // add it to the trace listeners. // Trace.Listeners.Add( new TextWriterTraceListener(System.Console.Out) ); /* * Check to see if we have a connection to the database */ SqlDataSchemaAdapter adapter = new SqlDataSchemaAdapter(Settings.Connection); adapter.CreateDatabase("test.xsd"); /* * Assure hte database exists */ tempConn = new SqlConnection(Settings.ConnectionString + ";Initial Catalog=Test-Database"); tempConn.Open(); SqlCommand cmd = new SqlCommand("SELECT count(name) FROM sysobjects where name = 'TestTableOrders'", tempConn); int orders = (int) cmd.ExecuteScalar(); cmd = new SqlCommand("SELECT count(name) FROM sysobjects where name = 'TestTable-Customers'", tempConn); int customers = (int) cmd.ExecuteScalar(); tempConn.Close(); Assertion.Assert("Table 'TestTableOrders' wasn't created", orders == 1); Assertion.Assert("Table 'TestTable-Customers' wasn't created", customers == 1); } catch (Exception ex) { Trace.WriteLine(ex.Message); throw; } finally { if (tempConn != null) tempConn.Close(); } } [TearDown] public void TeardownTestCreate() { File.Delete("test.xsd"); // release connection to avoid locking the database Settings.Connection.Close(); Settings.Connection.Open(); /* * drop the Test_Database database */ new SqlCommand("DROP DATABASE [Test-Database]", Settings.Connection) .ExecuteNonQuery(); } } } #endif
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>SmartCampaignSearchTermView</c> resource.</summary> public sealed partial class SmartCampaignSearchTermViewName : gax::IResourceName, sys::IEquatable<SmartCampaignSearchTermViewName> { /// <summary>The possible contents of <see cref="SmartCampaignSearchTermViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c>. /// </summary> CustomerCampaignQuery = 1, } private static gax::PathTemplate s_customerCampaignQuery = new gax::PathTemplate("customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id_query}"); /// <summary> /// Creates a <see cref="SmartCampaignSearchTermViewName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SmartCampaignSearchTermViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static SmartCampaignSearchTermViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SmartCampaignSearchTermViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SmartCampaignSearchTermViewName"/> with the pattern /// <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="queryId">The <c>Query</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="SmartCampaignSearchTermViewName"/> constructed from the provided ids. /// </returns> public static SmartCampaignSearchTermViewName FromCustomerCampaignQuery(string customerId, string campaignId, string queryId) => new SmartCampaignSearchTermViewName(ResourceNameType.CustomerCampaignQuery, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), queryId: gax::GaxPreconditions.CheckNotNullOrEmpty(queryId, nameof(queryId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SmartCampaignSearchTermViewName"/> with /// pattern <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="queryId">The <c>Query</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SmartCampaignSearchTermViewName"/> with pattern /// <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c>. /// </returns> public static string Format(string customerId, string campaignId, string queryId) => FormatCustomerCampaignQuery(customerId, campaignId, queryId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SmartCampaignSearchTermViewName"/> with /// pattern <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="queryId">The <c>Query</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SmartCampaignSearchTermViewName"/> with pattern /// <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c>. /// </returns> public static string FormatCustomerCampaignQuery(string customerId, string campaignId, string queryId) => s_customerCampaignQuery.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(queryId, nameof(queryId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="SmartCampaignSearchTermViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="smartCampaignSearchTermViewName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="SmartCampaignSearchTermViewName"/> if successful.</returns> public static SmartCampaignSearchTermViewName Parse(string smartCampaignSearchTermViewName) => Parse(smartCampaignSearchTermViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SmartCampaignSearchTermViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="smartCampaignSearchTermViewName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SmartCampaignSearchTermViewName"/> if successful.</returns> public static SmartCampaignSearchTermViewName Parse(string smartCampaignSearchTermViewName, bool allowUnparsed) => TryParse(smartCampaignSearchTermViewName, allowUnparsed, out SmartCampaignSearchTermViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SmartCampaignSearchTermViewName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="smartCampaignSearchTermViewName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SmartCampaignSearchTermViewName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string smartCampaignSearchTermViewName, out SmartCampaignSearchTermViewName result) => TryParse(smartCampaignSearchTermViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SmartCampaignSearchTermViewName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="smartCampaignSearchTermViewName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SmartCampaignSearchTermViewName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string smartCampaignSearchTermViewName, bool allowUnparsed, out SmartCampaignSearchTermViewName result) { gax::GaxPreconditions.CheckNotNull(smartCampaignSearchTermViewName, nameof(smartCampaignSearchTermViewName)); gax::TemplatedResourceName resourceName; if (s_customerCampaignQuery.TryParseName(smartCampaignSearchTermViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerCampaignQuery(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(smartCampaignSearchTermViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private SmartCampaignSearchTermViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null, string queryId = null) { Type = type; UnparsedResource = unparsedResourceName; CampaignId = campaignId; CustomerId = customerId; QueryId = queryId; } /// <summary> /// Constructs a new instance of a <see cref="SmartCampaignSearchTermViewName"/> class from the component parts /// of pattern <c>customers/{customer_id}/smartCampaignSearchTermViews/{campaign_id}~{query}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="queryId">The <c>Query</c> ID. Must not be <c>null</c> or empty.</param> public SmartCampaignSearchTermViewName(string customerId, string campaignId, string queryId) : this(ResourceNameType.CustomerCampaignQuery, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), queryId: gax::GaxPreconditions.CheckNotNullOrEmpty(queryId, nameof(queryId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CampaignId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Query</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string QueryId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCampaignQuery: return s_customerCampaignQuery.Expand(CustomerId, $"{CampaignId}~{QueryId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SmartCampaignSearchTermViewName); /// <inheritdoc/> public bool Equals(SmartCampaignSearchTermViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SmartCampaignSearchTermViewName a, SmartCampaignSearchTermViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SmartCampaignSearchTermViewName a, SmartCampaignSearchTermViewName b) => !(a == b); } public partial class SmartCampaignSearchTermView { /// <summary> /// <see cref="SmartCampaignSearchTermViewName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal SmartCampaignSearchTermViewName ResourceNameAsSmartCampaignSearchTermViewName { get => string.IsNullOrEmpty(ResourceName) ? null : SmartCampaignSearchTermViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property. /// </summary> internal CampaignName CampaignAsCampaignName { get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true); set => Campaign = value?.ToString() ?? ""; } } }
/* * A speed-improved simplex noise algorithm for 2D, 3D and 4D in Java. * * Based on example code by Stefan Gustavson ([email protected]). * Optimisations by Peter Eastman ([email protected]). * Better rank ordering method by Stefan Gustavson in 2012. * * This could be speeded up even further, but it's useful as it is. * * Version 2012-03-09 * * This code was placed in the public domain by its original author, * Stefan Gustavson. You may use it as you see fit, but * attribution is appreciated. * * Update by NightCabbage (2013-11-05) [email protected] * * Working with Stefan (thanks!) I have compiled all of the * improvements I could find and put them into this code. * * Note that for corner contribution I have made the decision here to * use 0.6 instead of 0.5, as I believe it looks a bit better for 2d * purposes (0.5 made it a bit more grey, and also had more pulsating for * integral inputs). If you're using it for bumpmaps or similar, feel * free to change it - and the final scale factor is 76 (as opposed to 32). */ using UnityEngine; using System; using System.Collections; namespace Noise { public class NoiseGen { public double XScale = 0.02; public double YScale = 0.02; public double ZScale = 1; public byte Octaves = 1; public double Scale { set { XScale = value; YScale = value; } } public NoiseGen() { } public NoiseGen(double pScale, byte pOctaves) { XScale = pScale; YScale = pScale; Octaves = pOctaves; } public NoiseGen(double pXScale, double pYScale, byte pOctaves) { XScale = pXScale; YScale = pYScale; Octaves = pOctaves; } public float GetNoise(double x, double y, double z) { if (Octaves > 1) return Noise.GetOctaveNoise(x * XScale, y * YScale, z * ZScale, Octaves); else return Noise.GetNoise(x * XScale, y * YScale, z * ZScale); } } // Simplex noise in 3D public static class Noise { // Inner class to speed up gradient computations // (array access is a lot slower than member access) private struct Grad { public double x, y, z, w; public Grad(double x, double y, double z) { this.x = x; this.y = y; this.z = z; this.w = 0; } } private static Grad[] grad3 = new Grad[] { new Grad(1, 1, 0), new Grad(-1, 1, 0), new Grad(1, -1, 0), new Grad(-1, -1, 0), new Grad(1, 0, 1), new Grad(-1, 0, 1), new Grad(1, 0, -1), new Grad(-1, 0, -1), new Grad(0, 1, 1), new Grad(0, -1, 1), new Grad(0, 1, -1), new Grad(0, -1, -1) }; private static short[] p = new short[] { 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148, 247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175, 74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54, 65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64, 52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213, 119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104, 218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157, 184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; // To remove the need for index wrapping, double the permutation table length private static short[] perm = new short[512]; private static short[] permMod12 = new short[512]; static Noise() { for (int i = 0; i < 512; i++) { perm[i] = p[i & 255]; permMod12[i] = (short)(perm[i] % 12); } } // Skewing and unskewing factors for 2, 3, and 4 dimensions private static double F3 = 1.0 / 3.0; private static double G3 = 1.0 / 6.0; // This method is a *lot* faster than using (int)Math.floor(x) private static int fastfloor(double x) { int xi = (int)x; return x < xi ? xi - 1 : xi; } private static double dot(Grad g, double x, double y, double z) { return g.x * x + g.y * y + g.z * z; } // 3D simplex noise public static float GetNoise(double xin, double yin, double zin) { double n0, n1, n2, n3; // Noise contributions from the four corners // Skew the input space to determine which simplex cell we're in double s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D int i = fastfloor(xin + s); int j = fastfloor(yin + s); int k = fastfloor(zin + s); double t = (i + j + k) * G3; double X0 = i - t; // Unskew the cell origin back to (x,y,z) space double Y0 = j - t; double Z0 = k - t; double x0 = xin - X0; // The x,y,z distances from the cell origin double y0 = yin - Y0; double z0 = zin - Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords if (x0 >= y0) { if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // X Y Z order else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } // X Z Y order else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } // Z X Y order } else { // x0<y0 if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; } // Z Y X order else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; } // Y Z X order else { i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // Y X Z order } // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z), // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where // c = 1/6. double x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords double y1 = y0 - j1 + G3; double z1 = z0 - k1 + G3; double x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords double y2 = y0 - j2 + 2.0 * G3; double z2 = z0 - k2 + 2.0 * G3; double x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords double y3 = y0 - 1.0 + 3.0 * G3; double z3 = z0 - 1.0 + 3.0 * G3; // Work out the hashed gradient indices of the four simplex corners int ii = i & 255; int jj = j & 255; int kk = k & 255; int gi0 = permMod12[ii + perm[jj + perm[kk]]]; int gi1 = permMod12[ii + i1 + perm[jj + j1 + perm[kk + k1]]]; int gi2 = permMod12[ii + i2 + perm[jj + j2 + perm[kk + k2]]]; int gi3 = permMod12[ii + 1 + perm[jj + 1 + perm[kk + 1]]]; // Calculate the contribution from the four corners double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0; // change to 0.5 if you want if (t0 < 0) n0 = 0.0; else { t0 *= t0; n0 = t0 * t0 * dot(grad3[gi0], x0, y0, z0); } double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; // change to 0.5 if you want if (t1 < 0) n1 = 0.0; else { t1 *= t1; n1 = t1 * t1 * dot(grad3[gi1], x1, y1, z1); } double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2; // change to 0.5 if you want if (t2 < 0) n2 = 0.0; else { t2 *= t2; n2 = t2 * t2 * dot(grad3[gi2], x2, y2, z2); } double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; // change to 0.5 if you want if (t3 < 0) n3 = 0.0; else { t3 *= t3; n3 = t3 * t3 * dot(grad3[gi3], x3, y3, z3); } // Add contributions from each corner to get the final noise value. // The result is scaled to stay just inside [-1,1] (now [0, 1]) return (float)(32.0 * (n0 + n1 + n2 + n3) + 1) * 0.5f; // change to 76.0 if you want } // get multiple octaves of noise at once public static float GetOctaveNoise(double pX, double pY, double pZ, int pOctaves) { float value = 0; float divisor = 0; float currentHalf = 0; float currentDouble = 0; for (int i = 0; i < pOctaves; i++) { currentHalf = (float)Math.Pow(0.5f, i); currentDouble = (float)Math.Pow(2, i); value += GetNoise(pX * currentDouble, pY * currentDouble, pZ) * currentHalf; divisor += currentHalf; } return value / divisor; } } }
// // Mono.Security.Cryptography.SymmetricTransform implementation // // Authors: // Thomas Neidhart ([email protected]) // Sebastien Pouliot <[email protected]> // // Portions (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Security.Cryptography; namespace Mono.Security.Cryptography { // This class implement most of the common code required for symmetric // algorithm transforms, like: // - CipherMode: Builds CBC and CFB on top of (descendant supplied) ECB // - PaddingMode, transform properties, multiple blocks, reuse... // // Descendants MUST: // - intialize themselves (like key expansion, ...) // - override the ECB (Electronic Code Book) method which will only be // called using BlockSize byte[] array. internal abstract class SymmetricTransform : ICryptoTransform { protected SymmetricAlgorithm algo; protected bool encrypt; protected int BlockSizeByte; protected byte[] temp; protected byte[] temp2; private byte[] workBuff; private byte[] workout; protected PaddingMode padmode; // Silverlight 2.0 does not support any feedback mode protected int FeedBackByte; private bool m_disposed = false; protected bool lastBlock; public SymmetricTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] rgbIV) { algo = symmAlgo; encrypt = encryption; BlockSizeByte = (algo.BlockSize >> 3); if (rgbIV == null) { rgbIV = KeyBuilder.IV (BlockSizeByte); } else { rgbIV = (byte[]) rgbIV.Clone (); } // compare the IV length with the "currently selected" block size and *ignore* IV that are too big if (rgbIV.Length < BlockSizeByte) { string msg = string.Format ("IV is too small ({0} bytes), it should be {1} bytes long.", rgbIV.Length, BlockSizeByte); throw new CryptographicException (msg); } padmode = algo.Padding; // mode buffers temp = new byte [BlockSizeByte]; Buffer.BlockCopy (rgbIV, 0, temp, 0, System.Math.Min (BlockSizeByte, rgbIV.Length)); temp2 = new byte [BlockSizeByte]; FeedBackByte = (algo.FeedbackSize >> 3); // transform buffers workBuff = new byte [BlockSizeByte]; workout = new byte [BlockSizeByte]; } ~SymmetricTransform () { Dispose (false); } void IDisposable.Dispose () { Dispose (true); GC.SuppressFinalize (this); // Finalization is now unnecessary } // MUST be overriden by classes using unmanaged ressources // the override method must call the base class protected virtual void Dispose (bool disposing) { if (!m_disposed) { if (disposing) { // dispose managed object: zeroize and free Array.Clear (temp, 0, BlockSizeByte); temp = null; Array.Clear (temp2, 0, BlockSizeByte); temp2 = null; } m_disposed = true; } } public virtual bool CanTransformMultipleBlocks { get { return true; } } public virtual bool CanReuseTransform { get { return false; } } public virtual int InputBlockSize { get { return BlockSizeByte; } } public virtual int OutputBlockSize { get { return BlockSizeByte; } } // note: Each block MUST be BlockSizeValue in size!!! // i.e. Any padding must be done before calling this method protected virtual void Transform (byte[] input, byte[] output) { switch (algo.Mode) { case CipherMode.ECB: ECB (input, output); break; case CipherMode.CBC: CBC (input, output); break; case CipherMode.CFB: CFB (input, output); break; case CipherMode.OFB: OFB (input, output); break; case CipherMode.CTS: CTS (input, output); break; default: throw new NotImplementedException ("Unkown CipherMode" + algo.Mode.ToString ()); } } // Electronic Code Book (ECB) protected abstract void ECB (byte[] input, byte[] output); // Cipher-Block-Chaining (CBC) protected virtual void CBC (byte[] input, byte[] output) { if (encrypt) { for (int i = 0; i < BlockSizeByte; i++) temp[i] ^= input[i]; ECB (temp, output); Buffer.BlockCopy (output, 0, temp, 0, BlockSizeByte); } else { Buffer.BlockCopy (input, 0, temp2, 0, BlockSizeByte); ECB (input, output); for (int i = 0; i < BlockSizeByte; i++) output[i] ^= temp[i]; Buffer.BlockCopy (temp2, 0, temp, 0, BlockSizeByte); } } // Cipher-FeedBack (CFB) // this is how *CryptoServiceProvider implements CFB // only AesCryptoServiceProvider support CFB > 8 // RijndaelManaged is incompatible with this implementation (and overrides it in it's own transform) protected virtual void CFB (byte[] input, byte[] output) { if (encrypt) { for (int x = 0; x < BlockSizeByte; x++) { // temp is first initialized with the IV ECB (temp, temp2); output [x] = (byte) (temp2 [0] ^ input [x]); Buffer.BlockCopy (temp, 1, temp, 0, BlockSizeByte - 1); Buffer.BlockCopy (output, x, temp, BlockSizeByte - 1, 1); } } else { for (int x = 0; x < BlockSizeByte; x++) { // we do not really decrypt this data! encrypt = true; // temp is first initialized with the IV ECB (temp, temp2); encrypt = false; Buffer.BlockCopy (temp, 1, temp, 0, BlockSizeByte - 1); Buffer.BlockCopy (input, x, temp, BlockSizeByte - 1, 1); output [x] = (byte) (temp2 [0] ^ input [x]); } } } // Output-FeedBack (OFB) protected virtual void OFB (byte[] input, byte[] output) { throw new CryptographicException ("OFB isn't supported by the framework"); } // Cipher Text Stealing (CTS) protected virtual void CTS (byte[] input, byte[] output) { throw new CryptographicException ("CTS isn't supported by the framework"); } private void CheckInput (byte[] inputBuffer, int inputOffset, int inputCount) { if (inputBuffer == null) throw new ArgumentNullException ("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException ("inputOffset", "< 0"); if (inputCount < 0) throw new ArgumentOutOfRangeException ("inputCount", "< 0"); // ordered to avoid possible integer overflow if (inputOffset > inputBuffer.Length - inputCount) throw new ArgumentException ("inputBuffer", ("Overflow")); } // this method may get called MANY times so this is the one to optimize public virtual int TransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (m_disposed) throw new ObjectDisposedException ("Object is disposed"); CheckInput (inputBuffer, inputOffset, inputCount); // check output parameters if (outputBuffer == null) throw new ArgumentNullException ("outputBuffer"); if (outputOffset < 0) throw new ArgumentOutOfRangeException ("outputOffset", "< 0"); // ordered to avoid possible integer overflow int len = outputBuffer.Length - inputCount - outputOffset; if (!encrypt && (0 > len) && ((padmode == PaddingMode.None) || (padmode == PaddingMode.Zeros))) { throw new CryptographicException ("outputBuffer", ("Overflow")); } else if (KeepLastBlock) { if (0 > len + BlockSizeByte) { throw new CryptographicException ("outputBuffer", ("Overflow")); } } else { if (0 > len) { // there's a special case if this is the end of the decryption process if (inputBuffer.Length - inputOffset - outputBuffer.Length == BlockSizeByte) inputCount = outputBuffer.Length - outputOffset; else throw new CryptographicException ("outputBuffer", ("Overflow")); } } return InternalTransformBlock (inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); } private bool KeepLastBlock { get { return ((!encrypt) && (padmode != PaddingMode.None) && (padmode != PaddingMode.Zeros)); } } private int InternalTransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { int offs = inputOffset; int full; // this way we don't do a modulo every time we're called // and we may save a division if (inputCount != BlockSizeByte) { if ((inputCount % BlockSizeByte) != 0) throw new CryptographicException ("Invalid input block size."); full = inputCount / BlockSizeByte; } else full = 1; if (KeepLastBlock) full--; int total = 0; if (lastBlock) { Transform (workBuff, workout); Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte); outputOffset += BlockSizeByte; total += BlockSizeByte; lastBlock = false; } for (int i = 0; i < full; i++) { Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte); Transform (workBuff, workout); Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte); offs += BlockSizeByte; outputOffset += BlockSizeByte; total += BlockSizeByte; } if (KeepLastBlock) { Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte); lastBlock = true; } return total; } RandomNumberGenerator _rng; private void Random (byte[] buffer, int start, int length) { if (_rng == null) { _rng = RandomNumberGenerator.Create (); } byte[] random = new byte [length]; _rng.GetBytes (random); Buffer.BlockCopy (random, 0, buffer, start, length); } private void ThrowBadPaddingException (PaddingMode padding, int length, int position) { string msg = String.Format ( ("Bad {0} padding."), padding); if (length >= 0) msg += String.Format ( (" Invalid length {0}."), length); if (position >= 0) msg += String.Format ( (" Error found at position {0}."), position); throw new CryptographicException (msg); } protected virtual byte[] FinalEncrypt (byte[] inputBuffer, int inputOffset, int inputCount) { // are there still full block to process ? int full = (inputCount / BlockSizeByte) * BlockSizeByte; int rem = inputCount - full; int total = full; switch (padmode) { case PaddingMode.ANSIX923: case PaddingMode.ISO10126: case PaddingMode.PKCS7: // we need to add an extra block for padding total += BlockSizeByte; break; default: if (inputCount == 0) return new byte [0]; if (rem != 0) { if (padmode == PaddingMode.None) throw new CryptographicException ("invalid block length"); // zero padding the input (by adding a block for the partial data) byte[] paddedInput = new byte [full + BlockSizeByte]; Buffer.BlockCopy (inputBuffer, inputOffset, paddedInput, 0, inputCount); inputBuffer = paddedInput; inputOffset = 0; inputCount = paddedInput.Length; total = inputCount; } break; } byte[] res = new byte [total]; int outputOffset = 0; // process all blocks except the last (final) block while (total > BlockSizeByte) { InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset); inputOffset += BlockSizeByte; outputOffset += BlockSizeByte; total -= BlockSizeByte; } // now we only have a single last block to encrypt byte padding = (byte) (BlockSizeByte - rem); switch (padmode) { case PaddingMode.ANSIX923: // XX 00 00 00 00 00 00 07 (zero + padding length) res [res.Length - 1] = padding; Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem); // the last padded block will be transformed in-place InternalTransformBlock (res, full, BlockSizeByte, res, full); break; case PaddingMode.ISO10126: // XX 3F 52 2A 81 AB F7 07 (random + padding length) Random (res, res.Length - padding, padding - 1); res [res.Length - 1] = padding; Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem); // the last padded block will be transformed in-place InternalTransformBlock (res, full, BlockSizeByte, res, full); break; case PaddingMode.PKCS7: // XX 07 07 07 07 07 07 07 (padding length) for (int i = res.Length; --i >= (res.Length - padding);) res [i] = padding; Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem); // the last padded block will be transformed in-place InternalTransformBlock (res, full, BlockSizeByte, res, full); break; default: InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset); break; } return res; } protected virtual byte[] FinalDecrypt (byte[] inputBuffer, int inputOffset, int inputCount) { int full = inputCount; int total = inputCount; if (lastBlock) total += BlockSizeByte; byte[] res = new byte [total]; int outputOffset = 0; while (full > 0) { int len = InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset); inputOffset += BlockSizeByte; outputOffset += len; full -= BlockSizeByte; } if (lastBlock) { Transform (workBuff, workout); Buffer.BlockCopy (workout, 0, res, outputOffset, BlockSizeByte); outputOffset += BlockSizeByte; lastBlock = false; } // total may be 0 (e.g. PaddingMode.None) byte padding = ((total > 0) ? res [total - 1] : (byte) 0); switch (padmode) { case PaddingMode.ANSIX923: if ((padding == 0) || (padding > BlockSizeByte)) ThrowBadPaddingException (padmode, padding, -1); for (int i = padding - 1; i > 0; i--) { if (res [total - 1 - i] != 0x00) ThrowBadPaddingException (padmode, -1, i); } total -= padding; break; case PaddingMode.ISO10126: if ((padding == 0) || (padding > BlockSizeByte)) ThrowBadPaddingException (padmode, padding, -1); total -= padding; break; case PaddingMode.PKCS7: if ((padding == 0) || (padding > BlockSizeByte)) ThrowBadPaddingException (padmode, padding, -1); for (int i = padding - 1; i > 0; i--) { if (res [total - 1 - i] != padding) ThrowBadPaddingException (padmode, -1, i); } total -= padding; break; case PaddingMode.None: // nothing to do - it's a multiple of block size case PaddingMode.Zeros: // nothing to do - user must unpad himself break; } // return output without padding if (total > 0) { byte[] data = new byte [total]; Buffer.BlockCopy (res, 0, data, 0, total); // zeroize decrypted data (copy with padding) Array.Clear (res, 0, res.Length); return data; } else return new byte [0]; } public virtual byte[] TransformFinalBlock (byte[] inputBuffer, int inputOffset, int inputCount) { if (m_disposed) throw new ObjectDisposedException ("Object is disposed"); CheckInput (inputBuffer, inputOffset, inputCount); if (encrypt) return FinalEncrypt (inputBuffer, inputOffset, inputCount); else return FinalDecrypt (inputBuffer, inputOffset, inputCount); } } }
using UnityEngine; using System.Collections; [System.Serializable] public class tk2dTextMeshData { public int version = 0; public tk2dFontData font; public string text = ""; public Color color = Color.white; public Color color2 = Color.white; public bool useGradient = false; public int textureGradient = 0; public TextAnchor anchor = TextAnchor.LowerLeft; public int renderLayer = 0; public Vector3 scale = Vector3.one; public bool kerning = false; public int maxChars = 16; public bool inlineStyling = false; public bool formatting = false; public int wordWrapWidth = 0; public float spacing = 0.0f; public float lineSpacing = 0.0f; } [ExecuteInEditMode] [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] [AddComponentMenu("2D Toolkit/Text/tk2dTextMesh")] /// <summary> /// Text mesh /// </summary> public class tk2dTextMesh : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild { tk2dFontData _fontInst; string _formattedText = ""; // This stuff now kept in tk2dTextMeshData. Remove in future version. [SerializeField] tk2dFontData _font = null; [SerializeField] string _text = ""; [SerializeField] Color _color = Color.white; [SerializeField] Color _color2 = Color.white; [SerializeField] bool _useGradient = false; [SerializeField] int _textureGradient = 0; [SerializeField] TextAnchor _anchor = TextAnchor.LowerLeft; [SerializeField] Vector3 _scale = new Vector3(1.0f, 1.0f, 1.0f); [SerializeField] bool _kerning = false; [SerializeField] int _maxChars = 16; [SerializeField] bool _inlineStyling = false; [SerializeField] bool _formatting = false; [SerializeField] int _wordWrapWidth = 0; [SerializeField] float spacing = 0.0f; [SerializeField] float lineSpacing = 0.0f; // Holding the data in this struct for the next version [SerializeField] tk2dTextMeshData data = new tk2dTextMeshData(); // Batcher needs to grab this public string FormattedText { get {return _formattedText;} } void UpgradeData() { if (data.version != 1) { data.font = _font; data.text = _text; data.color = _color; data.color2 = _color2; data.useGradient = _useGradient; data.textureGradient = _textureGradient; data.anchor = _anchor; data.scale = _scale; data.kerning = _kerning; data.maxChars = _maxChars; data.inlineStyling = _inlineStyling; data.formatting = _formatting; data.wordWrapWidth = _wordWrapWidth; data.spacing = spacing; data.lineSpacing = lineSpacing; } data.version = 1; } Vector3[] vertices; Vector2[] uvs; Vector2[] uv2; Color32[] colors; Color32[] untintedColors; static int GetInlineStyleCommandLength(int cmdSymbol) { int val = 0; switch (cmdSymbol) { case 'c': val = 5; break; // cRGBA case 'C': val = 9; break; // CRRGGBBAA case 'g': val = 9; break; // gRGBARGBA case 'G': val = 17; break; // GRRGGBBAARRGGBBAA } return val; } /// <summary> /// Formats the string using the current settings, and returns the formatted string. /// You can use this if you need to calculate how many lines your string is going to be wrapped to. /// </summary> public string FormatText(string unformattedString) { string returnValue = ""; FormatText(ref returnValue, unformattedString); return returnValue; } void FormatText() { FormatText(ref _formattedText, data.text); } void FormatText(ref string _targetString, string _source) { InitInstance(); if (formatting == false || wordWrapWidth == 0 || _fontInst.texelSize == Vector2.zero) { _targetString = _source; return; } float lineWidth = _fontInst.texelSize.x * wordWrapWidth; System.Text.StringBuilder target = new System.Text.StringBuilder(_source.Length); float widthSoFar = 0.0f; float wordStart = 0.0f; int targetWordStartIndex = -1; int fmtWordStartIndex = -1; bool ignoreNextCharacter = false; for (int i = 0; i < _source.Length; ++i) { char idx = _source[i]; tk2dFontChar chr; bool inlineHatChar = (idx == '^'); if (_fontInst.useDictionary) { if (!_fontInst.charDict.ContainsKey(idx)) idx = (char)0; chr = _fontInst.charDict[idx]; } else { if (idx >= _fontInst.chars.Length) idx = (char)0; // should be space chr = _fontInst.chars[idx]; } if (inlineHatChar) idx = '^'; if (ignoreNextCharacter) { ignoreNextCharacter = false; continue; } if (data.inlineStyling && idx == '^' && i + 1 < _source.Length) { if (_source[i + 1] == '^') { ignoreNextCharacter = true; target.Append('^'); // add the second hat that we'll skip } else { int cmdLength = GetInlineStyleCommandLength(_source[i + 1]); int skipLength = 1 + cmdLength; // The ^ plus the command for (int j = 0; j < skipLength; ++j) { if (i + j < _source.Length) { target.Append(_source[i + j]); } } i += skipLength - 1; continue; } } if (idx == '\n') { widthSoFar = 0.0f; wordStart = 0.0f; targetWordStartIndex = target.Length; fmtWordStartIndex = i; } else if (idx == ' '/* || idx == '.' || idx == ',' || idx == ':' || idx == ';' || idx == '!'*/) { /*if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth) { target.Append('\n'); widthSoFar = chr.advance * data.scale.x; } else {*/ widthSoFar += (chr.advance + data.spacing) * data.scale.x; //} wordStart = widthSoFar; targetWordStartIndex = target.Length; fmtWordStartIndex = i; } else { if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth) { // If the last word started after the start of the line if (wordStart > 0.0f) { wordStart = 0.0f; widthSoFar = 0.0f; // rewind target.Remove(targetWordStartIndex + 1, target.Length - targetWordStartIndex - 1); target.Append('\n'); i = fmtWordStartIndex; continue; // don't add this character } else { target.Append('\n'); widthSoFar = (chr.advance + data.spacing) * data.scale.x; } } else { widthSoFar += (chr.advance + data.spacing) * data.scale.x; } } target.Append(idx); } _targetString = target.ToString(); } [System.FlagsAttribute] enum UpdateFlags { UpdateNone = 0, UpdateText = 1, // update text vertices & uvs UpdateColors = 2, // only colors have changed UpdateBuffers = 4, // update buffers (maxchars has changed) }; UpdateFlags updateFlags = UpdateFlags.UpdateBuffers; Mesh mesh; MeshFilter meshFilter; void SetNeedUpdate(UpdateFlags uf) { if (updateFlags == UpdateFlags.UpdateNone) { updateFlags |= uf; tk2dUpdateManager.QueueCommit(this); } else { // Already queued updateFlags |= uf; } } // accessors /// <summary>Gets or sets the font. Call <see cref="Commit"/> to commit changes.</summary> public tk2dFontData font { get { UpgradeData(); return data.font; } set { UpgradeData(); data.font = value; _fontInst = data.font.inst; SetNeedUpdate( UpdateFlags.UpdateText ); UpdateMaterial(); } } /// <summary>Enables or disables formatting. Call <see cref="Commit"/> to commit changes.</summary> public bool formatting { get { UpgradeData(); return data.formatting; } set { UpgradeData(); if (data.formatting != value) { data.formatting = value; SetNeedUpdate( UpdateFlags.UpdateText ); } } } /// <summary>Change word wrap width. This only works when formatting is enabled. /// Call <see cref="Commit"/> to commit changes.</summary> public int wordWrapWidth { get { UpgradeData(); return data.wordWrapWidth; } set { UpgradeData(); if (data.wordWrapWidth != value) { data.wordWrapWidth = value; SetNeedUpdate(UpdateFlags.UpdateText); } } } /// <summary>Gets or sets the text. Call <see cref="Commit"/> to commit changes.</summary> public string text { get { UpgradeData(); return data.text; } set { UpgradeData(); data.text = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets the color. Call <see cref="Commit"/> to commit changes.</summary> public Color color { get { UpgradeData(); return data.color; } set { UpgradeData(); data.color = value; SetNeedUpdate(UpdateFlags.UpdateColors); } } /// <summary>Gets or sets the secondary color (used in the gradient). Call <see cref="Commit"/> to commit changes.</summary> public Color color2 { get { UpgradeData(); return data.color2; } set { UpgradeData(); data.color2 = value; SetNeedUpdate(UpdateFlags.UpdateColors); } } /// <summary>Use vertex vertical gradient. Call <see cref="Commit"/> to commit changes.</summary> public bool useGradient { get { UpgradeData(); return data.useGradient; } set { UpgradeData(); data.useGradient = value; SetNeedUpdate(UpdateFlags.UpdateColors); } } /// <summary>Gets or sets the text anchor. Call <see cref="Commit"/> to commit changes.</summary> public TextAnchor anchor { get { UpgradeData(); return data.anchor; } set { UpgradeData(); data.anchor = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets the scale. Call <see cref="Commit"/> to commit changes.</summary> public Vector3 scale { get { UpgradeData(); return data.scale; } set { UpgradeData(); data.scale = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets kerning state. Call <see cref="Commit"/> to commit changes.</summary> public bool kerning { get { UpgradeData(); return data.kerning; } set { UpgradeData(); data.kerning = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets maxChars. Call <see cref="Commit"/> to commit changes. /// NOTE: This will free & allocate memory, avoid using at runtime. /// </summary> public int maxChars { get { UpgradeData(); return data.maxChars; } set { UpgradeData(); data.maxChars = value; SetNeedUpdate(UpdateFlags.UpdateBuffers); } } /// <summary>Gets or sets the default texture gradient. /// You can also change texture gradient inline by using ^1 - ^9 sequences within your text. /// Call <see cref="Commit"/> to commit changes.</summary> public int textureGradient { get { UpgradeData(); return data.textureGradient; } set { UpgradeData(); data.textureGradient = value % font.gradientCount; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Enables or disables inline styling (texture gradient). Call <see cref="Commit"/> to commit changes.</summary> public bool inlineStyling { get { UpgradeData(); return data.inlineStyling; } set { UpgradeData(); data.inlineStyling = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Additional spacing between characters. /// This can be negative to bring characters closer together. /// Call <see cref="Commit"/> to commit changes.</summary> public float Spacing { get { UpgradeData(); return data.spacing; } set { UpgradeData(); if (data.spacing != value) { data.spacing = value; SetNeedUpdate(UpdateFlags.UpdateText); } } } /// <summary>Additional line spacing for multieline text. /// This can be negative to bring lines closer together. /// Call <see cref="Commit"/> to commit changes.</summary> public float LineSpacing { get { UpgradeData(); return data.lineSpacing; } set { UpgradeData(); if (data.lineSpacing != value) { data.lineSpacing = value; SetNeedUpdate(UpdateFlags.UpdateText); } } } /// <summary> /// Gets or sets the sorting order /// The sorting order lets you override draw order for sprites which are at the same z position /// It is similar to offsetting in z - the sprite stays at the original position /// This corresponds to the renderer.sortingOrder property in Unity 4.3 /// </summary> public int SortingOrder { get { #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) return data.renderLayer; #else return CachedRenderer.sortingOrder; #endif } set { #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (data.renderLayer != value) { data.renderLayer = value; SetNeedUpdate(UpdateFlags.UpdateText); } #else if (CachedRenderer.sortingOrder != value) { data.renderLayer = value; // for awake CachedRenderer.sortingOrder = value; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(CachedRenderer); #endif } #endif } } void InitInstance() { if (data != null && data.font != null) { _fontInst = data.font.inst; _fontInst.InitDictionary(); } } Renderer _cachedRenderer = null; Renderer CachedRenderer { get { if (_cachedRenderer == null) { _cachedRenderer = GetComponent<Renderer>(); } return _cachedRenderer; } } // Use this for initialization void Awake() { UpgradeData(); if (data.font != null) _fontInst = data.font.inst; // force rebuild when awakened, for when the object has been pooled, etc // this is probably not the best way to do it updateFlags = UpdateFlags.UpdateBuffers; if (data.font != null) { Init(); UpdateMaterial(); } // Sensibly reset, so tk2dUpdateManager can deal with this properly updateFlags = UpdateFlags.UpdateNone; } #if UNITY_EDITOR private void OnEnable() { if (GetComponent<Renderer>() != null && data != null && data.font != null && data.font.inst != null && GetComponent<Renderer>().sharedMaterial == null && data.font.inst.needMaterialInstance) { ForceBuild(); } } #endif protected void OnDestroy() { if (meshFilter == null) { meshFilter = GetComponent<MeshFilter>(); } if (meshFilter != null) { mesh = meshFilter.sharedMesh; } if (mesh) { DestroyImmediate(mesh, true); meshFilter.mesh = null; } } bool useInlineStyling { get { return inlineStyling && _fontInst.textureGradients; } } /// <summary> /// Returns the number of characters drawn for the currently active string. /// This may be less than string.Length - some characters are used as escape codes for switching texture gradient ^0-^9 /// Also, there might be more characters in the string than have been allocated for the textmesh, in which case /// the string will be truncated. /// </summary> public int NumDrawnCharacters() { int charsDrawn = NumTotalCharacters(); if (charsDrawn > data.maxChars) charsDrawn = data.maxChars; return charsDrawn; } /// <summary> /// Returns the number of characters excluding texture gradient escape codes. /// </summary> public int NumTotalCharacters() { InitInstance(); if ((updateFlags & (UpdateFlags.UpdateText | UpdateFlags.UpdateBuffers)) != 0) FormatText(); int numChars = 0; for (int i = 0; i < _formattedText.Length; ++i) { int idx = _formattedText[i]; bool inlineHatChar = (idx == '^'); if (_fontInst.useDictionary) { if (!_fontInst.charDict.ContainsKey(idx)) idx = 0; } else { if (idx >= _fontInst.chars.Length) idx = 0; // should be space } if (inlineHatChar) idx = '^'; if (idx == '\n') { continue; } else if (data.inlineStyling) { if (idx == '^' && i + 1 < _formattedText.Length) { if (_formattedText[i + 1] == '^') { ++i; } else { i += GetInlineStyleCommandLength(_formattedText[i + 1]); continue; } } } ++numChars; } return numChars; } [System.Obsolete("Use GetEstimatedMeshBoundsForString().size instead")] public Vector2 GetMeshDimensionsForString(string str) { return tk2dTextGeomGen.GetMeshDimensionsForString(str, tk2dTextGeomGen.Data( data, _fontInst, _formattedText )); } /// <summary> /// Calculates an estimated bounds for the given string if it were rendered /// using the current settings. /// This expects an unformatted string and will wrap the string if required. /// </summary> public Bounds GetEstimatedMeshBoundsForString( string str ) { InitInstance(); tk2dTextGeomGen.GeomData geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); Vector2 dims = tk2dTextGeomGen.GetMeshDimensionsForString( FormatText( str ), geomData); float offsetY = tk2dTextGeomGen.GetYAnchorForHeight(dims.y, geomData); float offsetX = tk2dTextGeomGen.GetXAnchorForWidth(dims.x, geomData); float lineHeight = (_fontInst.lineHeight + data.lineSpacing) * data.scale.y; return new Bounds( new Vector3(offsetX + dims.x * 0.5f, offsetY + dims.y * 0.5f + lineHeight, 0), Vector3.Scale(dims, new Vector3(1, -1, 1)) ); } public void Init(bool force) { if (force) { SetNeedUpdate(UpdateFlags.UpdateBuffers); } Init(); } public void Init() { if (_fontInst && ((updateFlags & UpdateFlags.UpdateBuffers) != 0 || mesh == null)) { _fontInst.InitDictionary(); FormatText(); var geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); // volatile data int numVertices; int numIndices; tk2dTextGeomGen.GetTextMeshGeomDesc(out numVertices, out numIndices, geomData); vertices = new Vector3[numVertices]; uvs = new Vector2[numVertices]; colors = new Color32[numVertices]; untintedColors = new Color32[numVertices]; if (_fontInst.textureGradients) { uv2 = new Vector2[numVertices]; } int[] triangles = new int[numIndices]; int target = tk2dTextGeomGen.SetTextMeshGeom(vertices, uvs, uv2, untintedColors, 0, geomData); if (!_fontInst.isPacked) { Color32 topColor = data.color; Color32 bottomColor = data.useGradient ? data.color2 : data.color; for (int i = 0; i < numVertices; ++i) { Color32 c = ((i % 4) < 2) ? topColor : bottomColor; byte red = (byte)(((int)untintedColors[i].r * (int)c.r) / 255); byte green = (byte)(((int)untintedColors[i].g * (int)c.g) / 255); byte blue = (byte)(((int)untintedColors[i].b * (int)c.b) / 255); byte alpha = (byte)(((int)untintedColors[i].a * (int)c.a) / 255); if (_fontInst.premultipliedAlpha) { red = (byte)(((int)red * (int)alpha) / 255); green = (byte)(((int)green * (int)alpha) / 255); blue = (byte)(((int)blue * (int)alpha) / 255); } colors[i] = new Color32(red, green, blue, alpha); } } else { colors = untintedColors; } tk2dTextGeomGen.SetTextMeshIndices(triangles, 0, 0, geomData, target); if (mesh == null) { if (meshFilter == null) meshFilter = GetComponent<MeshFilter>(); mesh = new Mesh(); #if !UNITY_3_5 mesh.MarkDynamic(); #endif mesh.hideFlags = HideFlags.DontSave; meshFilter.mesh = mesh; } else { mesh.Clear(); } mesh.vertices = vertices; mesh.uv = uvs; if (font.textureGradients) { mesh.uv2 = uv2; } mesh.triangles = triangles; mesh.colors32 = colors; mesh.RecalculateBounds(); mesh.bounds = tk2dBaseSprite.AdjustedMeshBounds( mesh.bounds, data.renderLayer ); updateFlags = UpdateFlags.UpdateNone; } } /// <summary> /// Calling commit is no longer required on text meshes. /// You can still call commit to manually commit all changes so far in the frame. /// </summary> public void Commit() { tk2dUpdateManager.FlushQueues(); } // Do not call this, its meant fo internal use public void DoNotUse__CommitInternal() { // Make sure instance is set up, might not be when calling from Awake. InitInstance(); // make sure fonts dictionary is initialized properly before proceeding if (_fontInst == null) { return; } _fontInst.InitDictionary(); // Can come in here without anything initalized when // instantiated in code if ((updateFlags & UpdateFlags.UpdateBuffers) != 0 || mesh == null) { Init(); } else { if ((updateFlags & UpdateFlags.UpdateText) != 0) { FormatText(); var geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); int target = tk2dTextGeomGen.SetTextMeshGeom(vertices, uvs, uv2, untintedColors, 0, geomData); for (int i = target; i < data.maxChars; ++i) { // was/is unnecessary to fill anything else vertices[i * 4 + 0] = vertices[i * 4 + 1] = vertices[i * 4 + 2] = vertices[i * 4 + 3] = Vector3.zero; } mesh.vertices = vertices; mesh.uv = uvs; if (_fontInst.textureGradients) { mesh.uv2 = uv2; } if (_fontInst.isPacked) { colors = untintedColors; mesh.colors32 = colors; } if (data.inlineStyling) { SetNeedUpdate(UpdateFlags.UpdateColors); } mesh.RecalculateBounds(); mesh.bounds = tk2dBaseSprite.AdjustedMeshBounds( mesh.bounds, data.renderLayer ); } if (!font.isPacked && (updateFlags & UpdateFlags.UpdateColors) != 0) // packed fonts don't support tinting { Color32 topColor = data.color; Color32 bottomColor = data.useGradient ? data.color2 : data.color; for (int i = 0; i < colors.Length; ++i) { Color32 c = ((i % 4) < 2) ? topColor : bottomColor; byte red = (byte)(((int)untintedColors[i].r * (int)c.r) / 255); byte green = (byte)(((int)untintedColors[i].g * (int)c.g) / 255); byte blue = (byte)(((int)untintedColors[i].b * (int)c.b) / 255); byte alpha = (byte)(((int)untintedColors[i].a * (int)c.a) / 255); if (_fontInst.premultipliedAlpha) { red = (byte)(((int)red * (int)alpha) / 255); green = (byte)(((int)green * (int)alpha) / 255); blue = (byte)(((int)blue * (int)alpha) / 255); } colors[i] = new Color32(red, green, blue, alpha); } mesh.colors32 = colors; } } updateFlags = UpdateFlags.UpdateNone; } /// <summary> /// Makes the text mesh pixel perfect to the active camera. /// Automatically detects <see cref="tk2dCamera"/> if present /// Otherwise uses Camera.main /// </summary> public void MakePixelPerfect() { float s = 1.0f; tk2dCamera cam = tk2dCamera.CameraForLayer(gameObject.layer); if (cam != null) { if (_fontInst.version < 1) { Debug.LogError("Need to rebuild font."); } float zdist = (transform.position.z - cam.transform.position.z); float textMeshSize = (_fontInst.invOrthoSize * _fontInst.halfTargetHeight); s = cam.GetSizeAtDistance(zdist) * textMeshSize; } else if (Camera.main) { if (Camera.main.orthographic) { s = Camera.main.orthographicSize; } else { float zdist = (transform.position.z - Camera.main.transform.position.z); s = tk2dPixelPerfectHelper.CalculateScaleForPerspectiveCamera(Camera.main.fieldOfView, zdist); } s *= _fontInst.invOrthoSize; } scale = new Vector3(Mathf.Sign(scale.x) * s, Mathf.Sign(scale.y) * s, Mathf.Sign(scale.z) * s); } // tk2dRuntime.ISpriteCollectionEditor public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection) { if (data.font != null && data.font.spriteCollection != null) return data.font.spriteCollection == spriteCollection; // No easy way to identify this at this stage return true; } void UpdateMaterial() { if (GetComponent<Renderer>().sharedMaterial != _fontInst.materialInst) GetComponent<Renderer>().material = _fontInst.materialInst; } public void ForceBuild() { if (data.font != null) { _fontInst = data.font.inst; UpdateMaterial(); } Init(true); } #if UNITY_EDITOR void OnDrawGizmos() { if (mesh != null) { Bounds b = mesh.bounds; Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(b.center, b.extents * 2); Gizmos.matrix = Matrix4x4.identity; Gizmos.color = Color.white; } } #endif }
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Globalization; using System.Runtime.Serialization; using System.Text; using Quartz.Util; namespace Quartz.Impl.Calendar { /// <summary> /// This implementation of the Calendar excludes (or includes - see below) a /// specified time range each day. /// </summary> /// <remarks> /// For example, you could use this calendar to /// exclude business hours (8AM - 5PM) every day. Each <see cref="DailyCalendar" /> /// only allows a single time range to be specified, and that time range may not /// * cross daily boundaries (i.e. you cannot specify a time range from 8PM - 5AM). /// If the property <see cref="InvertTimeRange" /> is <see langword="false" /> (default), /// the time range defines a range of times in which triggers are not allowed to /// * fire. If <see cref="InvertTimeRange" /> is <see langword="true" />, the time range /// is inverted: that is, all times <i>outside</i> the defined time range /// are excluded. /// <para> /// Note when using <see cref="DailyCalendar" />, it behaves on the same principals /// as, for example, WeeklyCalendar defines a set of days that are /// excluded <i>every week</i>. Likewise, <see cref="DailyCalendar" /> defines a /// set of times that are excluded <i>every day</i>. /// </para> /// </remarks> /// <author>Mike Funk</author> /// <author>Aaron Craven</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class DailyCalendar : BaseCalendar { private const string InvalidHourOfDay = "Invalid hour of day: "; private const string InvalidMinute = "Invalid minute: "; private const string InvalidSecond = "Invalid second: "; private const string InvalidMillis = "Invalid millis: "; private const string InvalidTimeRange = "Invalid time range: "; private const string Separator = " - "; private const long OneMillis = 1; private const char Colon = ':'; private const string TwoDigitFormat = "00"; private const string ThreeDigitFormat = "000"; // JsonProperty attributes are necessary because no public field/property exposes these directly // Adding RangeStartingTimeUTC and RangeEndingTimeUTC properties with getters/setters to control // these would remove the need for the attribute. private int rangeStartingHourOfDay; private int rangeStartingMinute; private int rangeStartingSecond; private int rangeStartingMillis; private int rangeEndingHourOfDay; private int rangeEndingMinute; private int rangeEndingSecond; private int rangeEndingMillis; private DailyCalendar() { } /// <summary> /// Create a <see cref="DailyCalendar" /> with a time range defined by the /// specified strings and no baseCalendar. /// <paramref name="rangeStartingTime" /> and <paramref name="rangeEndingTime" /> /// must be in the format &quot;HH:MM[:SS[:mmm]]&quot; where: /// <ul> /// <li> /// HH is the hour of the specified time. The hour should be /// specified using military (24-hour) time and must be in the range /// 0 to 23. /// </li> /// <li> /// MM is the minute of the specified time and must be in the range /// 0 to 59. /// </li> /// <li> /// SS is the second of the specified time and must be in the range /// 0 to 59. /// </li> /// <li> /// mmm is the millisecond of the specified time and must be in the /// range 0 to 999. /// </li> /// <li>items enclosed in brackets ('[', ']') are optional.</li> /// <li> /// The time range starting time must be before the time range ending /// time. Note this means that a time range may not cross daily /// boundaries (10PM - 2AM) /// </li> /// </ul> /// </summary> /// <param name="rangeStartingTime">The range starting time in millis.</param> /// <param name="rangeEndingTime">The range ending time in millis.</param> public DailyCalendar(string rangeStartingTime, string rangeEndingTime) { SetTimeRange(rangeStartingTime, rangeEndingTime); } /// <summary> /// Create a <see cref="DailyCalendar"/> with a time range defined by the /// specified strings and the specified baseCalendar. /// <paramref name="rangeStartingTime"/> and <paramref name="rangeEndingTime"/> /// must be in the format "HH:MM[:SS[:mmm]]" where: /// <ul> /// <li> /// HH is the hour of the specified time. The hour should be /// specified using military (24-hour) time and must be in the range /// 0 to 23. /// </li> /// <li> /// MM is the minute of the specified time and must be in the range /// 0 to 59. /// </li> /// <li> /// SS is the second of the specified time and must be in the range /// 0 to 59. /// </li> /// <li> /// mmm is the millisecond of the specified time and must be in the /// range 0 to 999. /// </li> /// <li> /// items enclosed in brackets ('[', ']') are optional. /// </li> /// <li> /// The time range starting time must be before the time range ending /// time. Note this means that a time range may not cross daily /// boundaries (10PM - 2AM) /// </li> /// </ul> /// </summary> /// <param name="baseCalendar">The base calendar for this calendar instance see BaseCalendar for more /// information on base calendar functionality.</param> /// <param name="rangeStartingTime">The range starting time in millis.</param> /// <param name="rangeEndingTime">The range ending time in millis.</param> public DailyCalendar(ICalendar? baseCalendar, string rangeStartingTime, string rangeEndingTime) : base(baseCalendar) { SetTimeRange(rangeStartingTime, rangeEndingTime); } /// <summary> /// Create a <see cref="DailyCalendar" /> with a time range defined by the /// specified values and no baseCalendar. Values are subject to /// the following validations: /// <ul> /// <li> /// Hours must be in the range 0-23 and are expressed using military /// (24-hour) time. /// </li> /// <li>Minutes must be in the range 0-59</li> /// <li>Seconds must be in the range 0-59</li> /// <li>Milliseconds must be in the range 0-999</li> /// <li> /// The time range starting time must be before the time range ending /// time. Note this means that a time range may not cross daily /// boundaries (10PM - 2AM) /// </li> /// </ul> /// </summary> /// <param name="rangeStartingHourOfDay">The range starting hour of day.</param> /// <param name="rangeStartingMinute">The range starting minute.</param> /// <param name="rangeStartingSecond">The range starting second.</param> /// <param name="rangeStartingMillis">The range starting millis.</param> /// <param name="rangeEndingHourOfDay">The range ending hour of day.</param> /// <param name="rangeEndingMinute">The range ending minute.</param> /// <param name="rangeEndingSecond">The range ending second.</param> /// <param name="rangeEndingMillis">The range ending millis.</param> public DailyCalendar(int rangeStartingHourOfDay, int rangeStartingMinute, int rangeStartingSecond, int rangeStartingMillis, int rangeEndingHourOfDay, int rangeEndingMinute, int rangeEndingSecond, int rangeEndingMillis) { SetTimeRange(rangeStartingHourOfDay, rangeStartingMinute, rangeStartingSecond, rangeStartingMillis, rangeEndingHourOfDay, rangeEndingMinute, rangeEndingSecond, rangeEndingMillis); } /// <summary> /// Create a <see cref="DailyCalendar"/> with a time range defined by the /// specified values and the specified <paramref name="baseCalendar"/>. Values are /// subject to the following validations: /// <ul> /// <li> /// Hours must be in the range 0-23 and are expressed using military /// (24-hour) time. /// </li> /// <li>Minutes must be in the range 0-59</li> /// <li>Seconds must be in the range 0-59</li> /// <li>Milliseconds must be in the range 0-999</li> /// <li> /// The time range starting time must be before the time range ending /// time. Note this means that a time range may not cross daily /// boundaries (10PM - 2AM) /// </li> /// </ul> /// </summary> /// <param name="baseCalendar">The base calendar for this calendar instance see BaseCalendar for more /// information on base calendar functionality.</param> /// <param name="rangeStartingHourOfDay">The range starting hour of day.</param> /// <param name="rangeStartingMinute">The range starting minute.</param> /// <param name="rangeStartingSecond">The range starting second.</param> /// <param name="rangeStartingMillis">The range starting millis.</param> /// <param name="rangeEndingHourOfDay">The range ending hour of day.</param> /// <param name="rangeEndingMinute">The range ending minute.</param> /// <param name="rangeEndingSecond">The range ending second.</param> /// <param name="rangeEndingMillis">The range ending millis.</param> public DailyCalendar(ICalendar baseCalendar, int rangeStartingHourOfDay, int rangeStartingMinute, int rangeStartingSecond, int rangeStartingMillis, int rangeEndingHourOfDay, int rangeEndingMinute, int rangeEndingSecond, int rangeEndingMillis) : base(baseCalendar) { SetTimeRange(rangeStartingHourOfDay, rangeStartingMinute, rangeStartingSecond, rangeStartingMillis, rangeEndingHourOfDay, rangeEndingMinute, rangeEndingSecond, rangeEndingMillis); } /// <summary> /// Create a <see cref="DailyCalendar" /> with a time range defined by the /// specified <see cref="DateTime" />s and no /// baseCalendar. The Calendars are subject to the following /// considerations: /// <ul> /// <li> /// Only the time-of-day fields of the specified Calendars will be /// used (the date fields will be ignored) /// </li> /// <li> /// The starting time must be before the ending time of the defined /// time range. Note this means that a time range may not cross /// daily boundaries (10PM - 2AM). <i>(because only time fields are /// are used, it is possible for two Calendars to represent a valid /// time range and /// <c>rangeStartingCalendar.after(rangeEndingCalendar) == true</c>) /// </i> /// </li> /// </ul> /// </summary> /// <param name="rangeStartingCalendarUtc">The range starting calendar.</param> /// <param name="rangeEndingCalendarUtc">The range ending calendar.</param> public DailyCalendar(DateTime rangeStartingCalendarUtc, DateTime rangeEndingCalendarUtc) { SetTimeRange(rangeStartingCalendarUtc, rangeEndingCalendarUtc); } /// <summary> /// Create a <see cref="DailyCalendar"/> with a time range defined by the /// specified <see cref="DateTime"/>s and the specified /// <paramref name="baseCalendar"/>. The Calendars are subject to the following /// considerations: /// <ul> /// <li> /// Only the time-of-day fields of the specified Calendars will be /// used (the date fields will be ignored) /// </li> /// <li> /// The starting time must be before the ending time of the defined /// time range. Note this means that a time range may not cross /// daily boundaries (10PM - 2AM). <i>(because only time fields are /// are used, it is possible for two Calendars to represent a valid /// time range and /// <c>rangeStartingCalendarUtc > rangeEndingCalendarUtc == true</c>)</i> /// </li> /// </ul> /// </summary> /// <param name="baseCalendar">The base calendar for this calendar instance see BaseCalendar for more /// information on base calendar functionality.</param> /// <param name="rangeStartingCalendarUtc">The range starting calendar.</param> /// <param name="rangeEndingCalendarUtc">The range ending calendar.</param> public DailyCalendar(ICalendar baseCalendar, DateTime rangeStartingCalendarUtc, DateTime rangeEndingCalendarUtc) : base(baseCalendar) { SetTimeRange(rangeStartingCalendarUtc, rangeEndingCalendarUtc); } /// <summary> /// Create a <see cref="DailyCalendar" /> with a time range defined by the /// specified values and no baseCalendar. The values are /// subject to the following considerations: /// <ul> /// <li> /// Only the time-of-day portion of the specified values will be /// used /// </li> /// <li> /// The starting time must be before the ending time of the defined /// time range. Note this means that a time range may not cross /// daily boundaries (10PM - 2AM). <i>(because only time value are /// are used, it is possible for the two values to represent a valid /// time range and <c>rangeStartingTime &gt; rangeEndingTime</c>)</i> /// </li> /// </ul> /// </summary> /// <param name="rangeStartingTimeInMillis">The range starting time in millis.</param> /// <param name="rangeEndingTimeInMillis">The range ending time in millis.</param> public DailyCalendar(long rangeStartingTimeInMillis, long rangeEndingTimeInMillis) { SetTimeRange(rangeStartingTimeInMillis, rangeEndingTimeInMillis); } /// <summary> /// Create a <see cref="DailyCalendar"/> with a time range defined by the /// specified values and the specified <paramref name="baseCalendar"/>. The values /// are subject to the following considerations: /// <ul> /// <li> /// Only the time-of-day portion of the specified values will be /// used /// </li> /// <li> /// The starting time must be before the ending time of the defined /// time range. Note this means that a time range may not cross /// daily boundaries (10PM - 2AM). <i>(because only time value are /// are used, it is possible for the two values to represent a valid /// time range and <c>rangeStartingTime &gt; rangeEndingTime</c>)</i> /// </li> /// </ul> /// </summary> /// <param name="baseCalendar">The base calendar for this calendar instance see BaseCalendar for more /// information on base calendar functionality.</param> /// <param name="rangeStartingTimeInMillis">The range starting time in millis.</param> /// <param name="rangeEndingTimeInMillis">The range ending time in millis.</param> public DailyCalendar(ICalendar baseCalendar, long rangeStartingTimeInMillis, long rangeEndingTimeInMillis) : base(baseCalendar) { SetTimeRange(rangeStartingTimeInMillis, rangeEndingTimeInMillis); } /// <summary> /// Serialization constructor. /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected DailyCalendar(SerializationInfo info, StreamingContext context) : base(info, context) { int version; try { version = info.GetInt32("version"); } catch { version = 0; } switch (version) { case 0: case 1: rangeStartingHourOfDay = info.GetInt32("rangeStartingHourOfDay"); rangeStartingMinute = info.GetInt32("rangeStartingMinute"); rangeStartingSecond = info.GetInt32("rangeStartingSecond"); rangeStartingMillis = info.GetInt32("rangeStartingMillis"); rangeEndingHourOfDay = info.GetInt32("rangeEndingHourOfDay"); rangeEndingMinute = info.GetInt32("rangeEndingMinute"); rangeEndingSecond = info.GetInt32("rangeEndingSecond"); rangeEndingMillis = info.GetInt32("rangeEndingMillis"); InvertTimeRange = info.GetBoolean("invertTimeRange"); break; default: throw new NotSupportedException("Unknown serialization version"); } } [System.Security.SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("version", 1); info.AddValue("rangeStartingHourOfDay", rangeStartingHourOfDay); info.AddValue("rangeStartingMinute", rangeStartingMinute); info.AddValue("rangeStartingSecond", rangeStartingSecond); info.AddValue("rangeStartingMillis", rangeStartingMillis); info.AddValue("rangeEndingHourOfDay", rangeEndingHourOfDay); info.AddValue("rangeEndingMinute", rangeEndingMinute); info.AddValue("rangeEndingSecond", rangeEndingSecond); info.AddValue("rangeEndingMillis", rangeEndingMillis); info.AddValue("invertTimeRange", InvertTimeRange); } /// <summary> /// Determine whether the given time is 'included' by the /// Calendar. /// </summary> /// <param name="timeUtc"></param> /// <returns></returns> public override bool IsTimeIncluded(DateTimeOffset timeUtc) { if (CalendarBase != null && CalendarBase.IsTimeIncluded(timeUtc) == false) { return false; } //Before we start, apply the correct timezone offsets. timeUtc = TimeZoneUtil.ConvertTime(timeUtc, TimeZone); DateTimeOffset startOfDayInMillis = GetStartOfDay(timeUtc); DateTimeOffset endOfDayInMillis = GetEndOfDay(timeUtc); DateTimeOffset timeRangeStartingTimeInMillis = GetTimeRangeStartingTimeUtc(timeUtc); DateTimeOffset timeRangeEndingTimeInMillis = GetTimeRangeEndingTimeUtc(timeUtc); if (!InvertTimeRange) { if (timeUtc > startOfDayInMillis && timeUtc < timeRangeStartingTimeInMillis || timeUtc > timeRangeEndingTimeInMillis && timeUtc < endOfDayInMillis) { return true; } return false; } if (timeUtc >= timeRangeStartingTimeInMillis && timeUtc <= timeRangeEndingTimeInMillis) { return true; } return false; } /// <summary> /// Determine the next time (in milliseconds) that is 'included' by the /// Calendar after the given time. Return the original value if timeStamp is /// included. Return 0 if all days are excluded. /// </summary> /// <param name="timeUtc"></param> /// <returns></returns> /// <seealso cref="ICalendar.GetNextIncludedTimeUtc"/> public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc) { DateTimeOffset nextIncludedTime = timeUtc.AddMilliseconds(OneMillis); while (!IsTimeIncluded(nextIncludedTime)) { if (!InvertTimeRange) { //If the time is in a range excluded by this calendar, we can // move to the end of the excluded time range and continue // testing from there. Otherwise, if nextIncludedTime is // excluded by the baseCalendar, ask it the next time it // includes and begin testing from there. Failing this, add one // millisecond and continue testing. if (nextIncludedTime >= GetTimeRangeStartingTimeUtc(nextIncludedTime) && nextIncludedTime <= GetTimeRangeEndingTimeUtc(nextIncludedTime)) { nextIncludedTime = GetTimeRangeEndingTimeUtc(nextIncludedTime).AddMilliseconds(OneMillis); } else if (CalendarBase != null && !CalendarBase.IsTimeIncluded(nextIncludedTime)) { nextIncludedTime = CalendarBase.GetNextIncludedTimeUtc(nextIncludedTime); } else { nextIncludedTime = nextIncludedTime.AddMilliseconds(1); } } else { //If the time is in a range excluded by this calendar, we can // move to the end of the excluded time range and continue // testing from there. Otherwise, if nextIncludedTime is // excluded by the baseCalendar, ask it the next time it // includes and begin testing from there. Failing this, add one // millisecond and continue testing. if (nextIncludedTime < GetTimeRangeStartingTimeUtc(nextIncludedTime)) { nextIncludedTime = GetTimeRangeStartingTimeUtc(nextIncludedTime); } else if (nextIncludedTime > GetTimeRangeEndingTimeUtc(nextIncludedTime)) { //(move to start of next day) nextIncludedTime = GetEndOfDay(nextIncludedTime); nextIncludedTime = nextIncludedTime.AddMilliseconds(1); } else if (CalendarBase != null && !CalendarBase.IsTimeIncluded(nextIncludedTime)) { nextIncludedTime = CalendarBase.GetNextIncludedTimeUtc(nextIncludedTime); } else { nextIncludedTime = nextIncludedTime.AddMilliseconds(1); } } } return nextIncludedTime; } public override ICalendar Clone() { var clone = new DailyCalendar(CalendarBase, RangeStartingTime, RangeEndingTime); CloneFields(clone); return clone; } /// <summary> /// Returns the start time of the time range of the day /// specified in <paramref name="timeUtc" />. /// </summary> /// <returns> /// a DateTime representing the start time of the /// time range for the specified date. /// </returns> public DateTimeOffset GetTimeRangeStartingTimeUtc(DateTimeOffset timeUtc) { DateTimeOffset rangeStartingTime = new DateTimeOffset(timeUtc.Year, timeUtc.Month, timeUtc.Day, rangeStartingHourOfDay, rangeStartingMinute, rangeStartingSecond, rangeStartingMillis, timeUtc.Offset); return rangeStartingTime; } /// <summary> /// Returns the end time of the time range of the day /// specified in <paramref name="timeUtc" /> /// </summary> /// <returns> /// A DateTime representing the end time of the /// time range for the specified date. /// </returns> public DateTimeOffset GetTimeRangeEndingTimeUtc(DateTimeOffset timeUtc) { DateTimeOffset rangeEndingTime = new DateTimeOffset(timeUtc.Year, timeUtc.Month, timeUtc.Day, rangeEndingHourOfDay, rangeEndingMinute, rangeEndingSecond, rangeEndingMillis, timeUtc.Offset); return rangeEndingTime; } /// <summary> /// Indicates whether the time range represents an inverted time range (see /// class description). /// </summary> /// <value><c>true</c> if invert time range; otherwise, <c>false</c>.</value> public bool InvertTimeRange { get; set; } public string RangeStartingTime => FormatTimeRange(rangeStartingHourOfDay, rangeStartingMinute, rangeStartingSecond, rangeStartingMillis); public string RangeEndingTime => FormatTimeRange(rangeEndingHourOfDay, rangeEndingMinute, rangeEndingSecond, rangeEndingMillis); private static string FormatTimeRange(int hourOfDay, int minute, int seconds, int milliseconds) { return $"{hourOfDay.ToString(TwoDigitFormat, CultureInfo.InvariantCulture)}:{minute.ToString(TwoDigitFormat, CultureInfo.InvariantCulture)}:{seconds.ToString(TwoDigitFormat, CultureInfo.InvariantCulture)}:{milliseconds.ToString(ThreeDigitFormat, CultureInfo.InvariantCulture)}"; } /// <summary> /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>. /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>. /// </returns> public override string ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("base calendar: ["); if (CalendarBase != null) { buffer.Append(CalendarBase); } else { buffer.Append("null"); } buffer.Append("], time range: '"); buffer.Append(RangeStartingTime); buffer.Append(" - "); buffer.Append(RangeEndingTime); buffer.AppendFormat("', inverted: {0}", InvertTimeRange); return buffer.ToString(); } /// <summary> /// Sets the time range for the <see cref="DailyCalendar" /> to the times /// represented in the specified Strings. /// </summary> /// <param name="rangeStartingTimeString">The range starting time string.</param> /// <param name="rangeEndingTimeString">The range ending time string.</param> public void SetTimeRange(string rangeStartingTimeString, string rangeEndingTimeString) { int rangeStartingSecond; int rangeStartingMillis; int rangeEndingSecond; int rangeEndingMillis; var rangeStartingTime = rangeStartingTimeString.Split(Colon); if (rangeStartingTime.Length < 2 || rangeStartingTime.Length > 4) { throw new ArgumentException($"Invalid time string '{rangeStartingTimeString}'"); } int rangeStartingHourOfDay = Convert.ToInt32(rangeStartingTime[0], CultureInfo.InvariantCulture); int rangeStartingMinute = Convert.ToInt32(rangeStartingTime[1], CultureInfo.InvariantCulture); if (rangeStartingTime.Length > 2) { rangeStartingSecond = Convert.ToInt32(rangeStartingTime[2], CultureInfo.InvariantCulture); } else { rangeStartingSecond = 0; } if (rangeStartingTime.Length == 4) { rangeStartingMillis = Convert.ToInt32(rangeStartingTime[3], CultureInfo.InvariantCulture); } else { rangeStartingMillis = 0; } var rangeEndingTime = rangeEndingTimeString.Split(Colon); if (rangeEndingTime.Length < 2 || rangeEndingTime.Length > 4) { throw new ArgumentException($"Invalid time string '{rangeEndingTimeString}'"); } int rangeEndingHourOfDay = Convert.ToInt32(rangeEndingTime[0], CultureInfo.InvariantCulture); int rangeEndingMinute = Convert.ToInt32(rangeEndingTime[1], CultureInfo.InvariantCulture); if (rangeEndingTime.Length > 2) { rangeEndingSecond = Convert.ToInt32(rangeEndingTime[2], CultureInfo.InvariantCulture); } else { rangeEndingSecond = 0; } if (rangeEndingTime.Length == 4) { rangeEndingMillis = Convert.ToInt32(rangeEndingTime[3], CultureInfo.InvariantCulture); } else { rangeEndingMillis = 0; } SetTimeRange(rangeStartingHourOfDay, rangeStartingMinute, rangeStartingSecond, rangeStartingMillis, rangeEndingHourOfDay, rangeEndingMinute, rangeEndingSecond, rangeEndingMillis); } /// <summary> /// Sets the time range for the <see cref="DailyCalendar" /> to the times /// represented in the specified values. /// </summary> /// <param name="rangeStartingHourOfDay">The range starting hour of day.</param> /// <param name="rangeStartingMinute">The range starting minute.</param> /// <param name="rangeStartingSecond">The range starting second.</param> /// <param name="rangeStartingMillis">The range starting millis.</param> /// <param name="rangeEndingHourOfDay">The range ending hour of day.</param> /// <param name="rangeEndingMinute">The range ending minute.</param> /// <param name="rangeEndingSecond">The range ending second.</param> /// <param name="rangeEndingMillis">The range ending millis.</param> public void SetTimeRange(int rangeStartingHourOfDay, int rangeStartingMinute, int rangeStartingSecond, int rangeStartingMillis, int rangeEndingHourOfDay, int rangeEndingMinute, int rangeEndingSecond, int rangeEndingMillis) { Validate(rangeStartingHourOfDay, rangeStartingMinute, rangeStartingSecond, rangeStartingMillis); Validate(rangeEndingHourOfDay, rangeEndingMinute, rangeEndingSecond, rangeEndingMillis); DateTimeOffset startCal = SystemTime.UtcNow(); startCal = new DateTimeOffset(startCal.Year, startCal.Month, startCal.Day, rangeStartingHourOfDay, rangeStartingMinute, rangeStartingSecond, rangeStartingMillis, TimeSpan.Zero); DateTimeOffset endCal = SystemTime.UtcNow(); endCal = new DateTimeOffset(endCal.Year, endCal.Month, endCal.Day, rangeEndingHourOfDay, rangeEndingMinute, rangeEndingSecond, rangeEndingMillis, TimeSpan.Zero); if (!(startCal < endCal)) { throw new ArgumentException($"{InvalidTimeRange}{rangeStartingHourOfDay}:{rangeStartingMinute}:{rangeStartingSecond}:{rangeStartingMillis}{Separator}{rangeEndingHourOfDay}:{rangeEndingMinute}:{rangeEndingSecond}:{rangeEndingMillis}"); } this.rangeStartingHourOfDay = rangeStartingHourOfDay; this.rangeStartingMinute = rangeStartingMinute; this.rangeStartingSecond = rangeStartingSecond; this.rangeStartingMillis = rangeStartingMillis; this.rangeEndingHourOfDay = rangeEndingHourOfDay; this.rangeEndingMinute = rangeEndingMinute; this.rangeEndingSecond = rangeEndingSecond; this.rangeEndingMillis = rangeEndingMillis; } /// <summary> /// Sets the time range for the <see cref="DailyCalendar" /> to the times /// represented in the specified <see cref="DateTime" />s. /// </summary> /// <param name="rangeStartingCalendarUtc">The range starting calendar.</param> /// <param name="rangeEndingCalendarUtc">The range ending calendar.</param> public void SetTimeRange(DateTime rangeStartingCalendarUtc, DateTime rangeEndingCalendarUtc) { SetTimeRange( rangeStartingCalendarUtc.Hour, rangeStartingCalendarUtc.Minute, rangeStartingCalendarUtc.Second, rangeStartingCalendarUtc.Millisecond, rangeEndingCalendarUtc.Hour, rangeEndingCalendarUtc.Minute, rangeEndingCalendarUtc.Second, rangeEndingCalendarUtc.Millisecond); } /// <summary> /// Sets the time range for the <see cref="DailyCalendar" /> to the times /// represented in the specified values. /// </summary> /// <param name="rangeStartingTime">The range starting time.</param> /// <param name="rangeEndingTime">The range ending time.</param> public void SetTimeRange(long rangeStartingTime, long rangeEndingTime) { SetTimeRange(new DateTime(rangeStartingTime), new DateTime(rangeEndingTime)); } /// <summary> /// Gets the start of day, practically zeroes time part. /// </summary> /// <param name="time">The time.</param> /// <returns></returns> private static DateTimeOffset GetStartOfDay(DateTimeOffset time) { return time.Date; } /// <summary> /// Gets the end of day, practically sets time parts to maximum allowed values. /// </summary> /// <param name="time">The time.</param> /// <returns></returns> private static DateTimeOffset GetEndOfDay(DateTimeOffset time) { DateTime endOfDay = new DateTime(time.Year, time.Month, time.Day, 23, 59, 59, 999); return endOfDay; } /// <summary> /// Checks the specified values for validity as a set of time values. /// </summary> /// <param name="hourOfDay">The hour of day.</param> /// <param name="minute">The minute.</param> /// <param name="second">The second.</param> /// <param name="millis">The millis.</param> private static void Validate(int hourOfDay, int minute, int second, int millis) { if (hourOfDay < 0 || hourOfDay > 23) { throw new ArgumentException(InvalidHourOfDay + hourOfDay); } if (minute < 0 || minute > 59) { throw new ArgumentException(InvalidMinute + minute); } if (second < 0 || second > 59) { throw new ArgumentException(InvalidSecond + second); } if (millis < 0 || millis > 999) { throw new ArgumentException(InvalidMillis + millis); } } public override int GetHashCode() { int baseHash = 0; if (CalendarBase != null) baseHash = CalendarBase.GetHashCode(); return rangeStartingHourOfDay.GetHashCode() + rangeEndingHourOfDay.GetHashCode() + 2*(rangeStartingMinute.GetHashCode() + rangeEndingMinute.GetHashCode()) + 3*(rangeStartingSecond.GetHashCode() + rangeEndingSecond.GetHashCode()) + 4*(rangeStartingMillis.GetHashCode() + rangeEndingMillis.GetHashCode()) + 5*baseHash; } public bool Equals(DailyCalendar obj) { if (obj == null) { return false; } bool baseEqual = CalendarBase == null || CalendarBase.Equals(obj.CalendarBase); return baseEqual && InvertTimeRange == obj.InvertTimeRange && rangeStartingHourOfDay == obj.rangeStartingHourOfDay && rangeStartingMinute == obj.rangeStartingMinute && rangeStartingSecond == obj.rangeStartingSecond && rangeStartingMillis == obj.rangeStartingMillis && rangeEndingHourOfDay == obj.rangeEndingHourOfDay && rangeEndingMinute == obj.rangeEndingMinute && rangeEndingSecond == obj.rangeEndingSecond && rangeEndingMillis == obj.rangeEndingMillis; } public override bool Equals(object? obj) { if (!(obj is DailyCalendar)) return false; return Equals((DailyCalendar) obj); } } }
using System; using System.Collections.Concurrent; using System.IO; using JetBrains.Annotations; using Stef.Validation; namespace WireMock.Util { /// <summary> /// An EnhancedFileSystemWatcher, which can be used to suppress duplicate events that fire on a single change to the file. /// </summary> /// <seealso cref="FileSystemWatcher" /> public class EnhancedFileSystemWatcher : FileSystemWatcher { #region Private Members // Default Watch Interval in Milliseconds private const int DefaultWatchInterval = 100; // This Dictionary keeps the track of when an event occurred last for a particular file private ConcurrentDictionary<string, DateTime> _lastFileEvent; // Watch Interval in Milliseconds private int _interval; // Timespan created when interval is set private TimeSpan _recentTimeSpan; #endregion #region Public Properties /// <summary> /// Interval, in milliseconds, within which events are considered "recent". /// </summary> [PublicAPI] public int Interval { get => _interval; set { _interval = value; // Set timespan based on the value passed _recentTimeSpan = new TimeSpan(0, 0, 0, 0, value); } } /// <summary> /// Allows user to set whether to filter recent events. /// If this is set a false, this class behaves like System.IO.FileSystemWatcher class. /// </summary> [PublicAPI] public bool FilterRecentEvents { get; set; } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="EnhancedFileSystemWatcher"/> class. /// </summary> /// <param name="interval">The interval.</param> public EnhancedFileSystemWatcher(int interval = DefaultWatchInterval) { Guard.Condition(interval, i => i >= 0, nameof(interval)); InitializeMembers(interval); } /// <summary> /// Initializes a new instance of the <see cref="EnhancedFileSystemWatcher"/> class. /// </summary> /// <param name="path">The directory to monitor, in standard or Universal Naming Convention (UNC) notation.</param> /// <param name="interval">The interval.</param> public EnhancedFileSystemWatcher([NotNull] string path, int interval = DefaultWatchInterval) : base(path) { Guard.NotNullOrEmpty(path, nameof(path)); Guard.Condition(interval, i => i >= 0, nameof(interval)); InitializeMembers(interval); } /// <summary> /// Initializes a new instance of the <see cref="EnhancedFileSystemWatcher"/> class. /// </summary> /// <param name="path">The directory to monitor, in standard or Universal Naming Convention (UNC) notation.</param> /// <param name="filter">The type of files to watch. For example, "*.txt" watches for changes to all text files.</param> /// <param name="interval">The interval.</param> public EnhancedFileSystemWatcher([NotNull] string path, [NotNull] string filter, int interval = DefaultWatchInterval) : base(path, filter) { Guard.NotNullOrEmpty(path, nameof(path)); Guard.NotNullOrEmpty(filter, nameof(filter)); Guard.Condition(interval, i => i >= 0, nameof(interval)); InitializeMembers(interval); } #endregion #region Events // These events hide the events from the base class. // We want to raise these events appropriately and we do not want the // users of this class subscribing to these events of the base class accidentally /// <summary> /// Occurs when a file or directory in the specified <see cref="P:System.IO.FileSystemWatcher.Path" /> is changed. /// </summary> public new event FileSystemEventHandler Changed; /// <summary> /// Occurs when a file or directory in the specified <see cref="P:System.IO.FileSystemWatcher.Path" /> is created. /// </summary> public new event FileSystemEventHandler Created; /// <summary> /// Occurs when a file or directory in the specified <see cref="P:System.IO.FileSystemWatcher.Path" /> is deleted. /// </summary> public new event FileSystemEventHandler Deleted; /// <summary> /// Occurs when a file or directory in the specified <see cref="P:System.IO.FileSystemWatcher.Path" /> is renamed. /// </summary> public new event RenamedEventHandler Renamed; #endregion #region Protected Methods to raise the Events for this class /// <summary> /// Raises the <see cref="E:System.IO.FileSystemWatcher.Changed" /> event. /// </summary> /// <param name="e">A <see cref="T:System.IO.FileSystemEventArgs" /> that contains the event data.</param> protected new virtual void OnChanged(FileSystemEventArgs e) { Changed?.Invoke(this, e); } /// <summary> /// Raises the <see cref="E:System.IO.FileSystemWatcher.Created" /> event. /// </summary> /// <param name="e">A <see cref="T:System.IO.FileSystemEventArgs" /> that contains the event data.</param> protected new virtual void OnCreated(FileSystemEventArgs e) { Created?.Invoke(this, e); } /// <summary> /// Raises the <see cref="E:System.IO.FileSystemWatcher.Deleted" /> event. /// </summary> /// <param name="e">A <see cref="T:System.IO.FileSystemEventArgs" /> that contains the event data.</param> protected new virtual void OnDeleted(FileSystemEventArgs e) { Deleted?.Invoke(this, e); } /// <summary> /// Raises the <see cref="E:System.IO.FileSystemWatcher.Renamed" /> event. /// </summary> /// <param name="e">A <see cref="T:System.IO.RenamedEventArgs" /> that contains the event data.</param> protected new virtual void OnRenamed(RenamedEventArgs e) { Renamed?.Invoke(this, e); } #endregion #region Private Methods /// <summary> /// This Method Initializes the private members. /// Interval is set to its default value of 100 millisecond. /// FilterRecentEvents is set to true, _lastFileEvent dictionary is initialized. /// We subscribe to the base class events. /// </summary> private void InitializeMembers(int interval = 100) { Interval = interval; FilterRecentEvents = true; _lastFileEvent = new ConcurrentDictionary<string, DateTime>(); base.Created += OnCreated; base.Changed += OnChanged; base.Deleted += OnDeleted; base.Renamed += OnRenamed; } /// <summary> /// This method searches the dictionary to find out when the last event occurred /// for a particular file. If that event occurred within the specified timespan /// it returns true, else false /// </summary> /// <param name="fileName">The filename to be checked</param> /// <returns>True if an event has occurred within the specified interval, False otherwise</returns> private bool HasAnotherFileEventOccurredRecently(string fileName) { // Check dictionary only if user wants to filter recent events otherwise return value stays false. if (!FilterRecentEvents) { return false; } bool retVal = false; if (_lastFileEvent.ContainsKey(fileName)) { // If dictionary contains the filename, check how much time has elapsed // since the last event occurred. If the timespan is less that the // specified interval, set return value to true // and store current datetime in dictionary for this file DateTime lastEventTime = _lastFileEvent[fileName]; DateTime currentTime = DateTime.Now; TimeSpan timeSinceLastEvent = currentTime - lastEventTime; retVal = timeSinceLastEvent < _recentTimeSpan; _lastFileEvent[fileName] = currentTime; } else { // If dictionary does not contain the filename, // no event has occurred in past for this file, so set return value to false // and append filename along with current datetime to the dictionary _lastFileEvent.TryAdd(fileName, DateTime.Now); } return retVal; } #region FileSystemWatcher EventHandlers // Base class Event Handlers. Check if an event has occurred recently and call method // to raise appropriate event only if no recent event is detected private void OnChanged(object sender, FileSystemEventArgs e) { if (!HasAnotherFileEventOccurredRecently(e.FullPath)) { OnChanged(e); } } private void OnCreated(object sender, FileSystemEventArgs e) { if (!HasAnotherFileEventOccurredRecently(e.FullPath)) { OnCreated(e); } } private void OnDeleted(object sender, FileSystemEventArgs e) { if (!HasAnotherFileEventOccurredRecently(e.FullPath)) { OnDeleted(e); } } private void OnRenamed(object sender, RenamedEventArgs e) { if (!HasAnotherFileEventOccurredRecently(e.OldFullPath)) { OnRenamed(e); } } #endregion #endregion } }
// Copyright 2006 Alp Toker <[email protected]> // This software is made available under the MIT License // See COPYING for details using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using org.freedesktop.DBus; namespace DBus { using Protocol; internal class PropertyCall { public MethodCaller Get { get; set; } public MethodCaller Set { get; set; } public PropertyInfo MetaData { get; set; } } internal class MethodCall { public Signature Out { get; set; } public Signature In { get; set; } public MethodCaller Call { get; set; } public MethodInfo MetaData { get; set; } } internal class MethodDictionary : Dictionary<string, MethodCall> { } internal class PropertyDictionary : Dictionary<string, PropertyCall> { public MethodCaller All { get; set; } } internal class InterfaceMethods : Dictionary<string, MethodDictionary> { } internal class InterfaceProperties : Dictionary<string, PropertyDictionary> { } internal class DBusMemberTable { public Type ObjectType { get; private set; } public DBusMemberTable(Type type) { ObjectType = type; } InterfaceMethods Methods = new InterfaceMethods(); InterfaceProperties Properties = new InterfaceProperties(); public MethodCall GetMethodCall (string iface, string name) { return Lookup<InterfaceMethods, MethodDictionary, string, string, MethodCall> ( Methods, iface, name, (i, n) => { Type it = Mapper.GetInterfaceType (ObjectType, i); MethodInfo mi = it.GetMethod (n); return TypeImplementer.GenMethodCall (mi); } ); } public MethodCaller GetPropertyAllCall (string iface) { PropertyDictionary calls; if (!Properties.TryGetValue(iface, out calls)) { Properties [iface] = calls = new PropertyDictionary (); } if (null == calls.All) { Type it = Mapper.GetInterfaceType (ObjectType, iface); calls.All = TypeImplementer.GenGetAllCall (it); } return calls.All; } public PropertyCall GetPropertyCall (string iface, string name) { return Lookup<InterfaceProperties, PropertyDictionary, string, string, PropertyCall> ( Properties, iface, name, (i, n) => { Type it = Mapper.GetInterfaceType(ObjectType, i); PropertyInfo pi = it.GetProperty(n); return TypeImplementer.GenPropertyCall (pi); } ); } private static V Lookup<TMap1,TMap2,A,B,V> (TMap1 map, A k1, B k2, Func<A,B,V> factory) where TMap2 : IDictionary<B, V>, new() where TMap1 : IDictionary<A, TMap2> { TMap2 first; if (!map.TryGetValue (k1, out first)) { map [k1] = first = new TMap2 (); } V value; if (!first.TryGetValue (k2, out value)) { first [k2] = value = factory (k1, k2); } return value; } } //TODO: perhaps ExportObject should not derive from BusObject internal class ExportObject : BusObject, IDisposable { //maybe add checks to make sure this is not called more than once //it's a bit silly as a property bool isRegistered = false; static readonly Dictionary<Type, DBusMemberTable> typeMembers = new Dictionary<Type, DBusMemberTable>(); public ExportObject (Connection conn, ObjectPath object_path, object obj) : base (conn, null, object_path) { Object = obj; } public virtual bool Registered { get { return isRegistered; } set { if (value == isRegistered) return; Type type = Object.GetType (); foreach (var memberForType in Mapper.GetPublicMembers (type)) { MemberInfo mi = memberForType.Value; EventInfo ei = mi as EventInfo; if (ei == null) continue; Delegate dlg = GetHookupDelegate (ei); if (value) ei.AddEventHandler (Object, dlg); else ei.RemoveEventHandler (Object, dlg); } isRegistered = value; } } internal virtual void WriteIntrospect (Introspector intro) { intro.WriteType (Object.GetType ()); } public static ExportObject CreateExportObject (Connection conn, ObjectPath object_path, object obj) { Type type = obj.GetType (); DBusMemberTable table; if (!typeMembers.TryGetValue (type, out table)) { typeMembers [type] = new DBusMemberTable (type); } return new ExportObject (conn, object_path, obj); } public virtual void HandleMethodCall (MessageContainer method_call) { switch (method_call.Interface) { case "org.freedesktop.DBus.Properties": HandlePropertyCall (method_call); return; } MethodCall mCaller = null; try { mCaller = typeMembers[Object.GetType()].GetMethodCall( method_call.Interface, method_call.Member ); } catch { /* No Such Member */ } if (mCaller == null) { conn.MaybeSendUnknownMethodError (method_call); return; } Signature inSig = mCaller.In, outSig = mCaller.Out; Message msg = method_call.Message; MessageReader msgReader = new MessageReader (msg); MessageWriter retWriter = new MessageWriter (); Exception raisedException = null; try { mCaller.Call (Object, msgReader, msg, retWriter); } catch (Exception e) { raisedException = e; } IssueReply (method_call, outSig, retWriter, mCaller.MetaData, raisedException); } private void IssueReply (MessageContainer method_call, Signature outSig, MessageWriter retWriter, MethodInfo mi, Exception raisedException) { Message msg = method_call.Message; if (!msg.ReplyExpected) return; Message replyMsg; if (raisedException == null) { MessageContainer method_return = new MessageContainer { Type = MessageType.MethodReturn, Destination = method_call.Sender, ReplySerial = msg.Header.Serial }; replyMsg = method_return.Message; replyMsg.AttachBodyTo (retWriter); replyMsg.Signature = outSig; } else { // BusException allows precisely formatted Error messages. BusException busException = raisedException as BusException; if (busException != null) replyMsg = method_call.CreateError (busException.ErrorName, busException.ErrorMessage); else if (raisedException is ArgumentException && raisedException.TargetSite.Name == mi.Name) { // Name match trick above is a hack since we don't have the resolved MethodInfo. ArgumentException argException = (ArgumentException)raisedException; using (System.IO.StringReader sr = new System.IO.StringReader (argException.Message)) { replyMsg = method_call.CreateError ("org.freedesktop.DBus.Error.InvalidArgs", sr.ReadLine ()); } } else replyMsg = method_call.CreateError (Mapper.GetInterfaceName (raisedException.GetType ()), raisedException.Message); } conn.Send (replyMsg); } private void HandlePropertyCall (MessageContainer method_call) { Message msg = method_call.Message; MessageReader msgReader = new MessageReader (msg); MessageWriter retWriter = new MessageWriter (); object[] args = MessageHelper.GetDynamicValues (msg); string face = (string) args [0]; if ("GetAll" == method_call.Member) { Signature asv = Signature.MakeDict (Signature.StringSig, Signature.VariantSig); MethodCaller call = typeMembers [Object.GetType ()].GetPropertyAllCall (face); Exception ex = null; try { call (Object, msgReader, msg, retWriter); } catch (Exception e) { ex = e; } IssueReply (method_call, asv, retWriter, null, ex); return; } string name = (string) args [1]; PropertyCall pcs = typeMembers[Object.GetType()].GetPropertyCall ( face, name ); MethodInfo mi; MethodCaller pc; Signature outSig, inSig = method_call.Signature; switch (method_call.Member) { case "Set": mi = pcs.MetaData.GetSetMethod (); pc = pcs.Set; outSig = Signature.Empty; break; case "Get": mi = pcs.MetaData.GetGetMethod (); pc = pcs.Get; outSig = Signature.GetSig(mi.ReturnType); break; default: throw new ArgumentException (string.Format ("No such method {0}.{1}", method_call.Interface, method_call.Member)); } if (null == pc) { conn.MaybeSendUnknownMethodError (method_call); return; } Exception raised = null; try { pc (Object, msgReader, msg, retWriter); } catch (Exception e) { raised = e; } IssueReply (method_call, outSig, retWriter, mi, raised); } public object Object { get; private set; } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } ~ExportObject () { Dispose (false); } protected virtual void Dispose (bool disposing) { if (disposing) { if (Object != null) { Registered = false; Object = null; } } } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using System.Text.RegularExpressions; namespace InWorldz.ApplicationPlugins.GuestModule { /// <summary> /// Implements a guest functionality that removes certain rights from avatars that are logging in as guests /// /// To enable, add /// /// [GuestModule] /// Enabled = true /// /// into OpenSim.ini. /// </summary> public class GuestModule : INonSharedRegionModule { #region Declares private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private bool m_enabled = false; private string m_guestRegionName; private string m_limitViewerString; private Scene m_scene; #endregion #region INonSharedRegionModule Members public string Name { get { return "GuestModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { IConfig config = source.Configs[Name]; if (config == null) return; m_enabled = config.GetBoolean("Enabled", m_enabled); if (m_enabled) { m_guestRegionName = config.GetString("GuestRegionName", m_guestRegionName); if (m_guestRegionName == null) { m_log.ErrorFormat("[GUESTMOD]: Guest region name is required"); throw new Exception("Guest region name is required"); } m_limitViewerString = config.GetString("ViewerString", m_limitViewerString); if (m_limitViewerString != null) { m_limitViewerString = m_limitViewerString.ToLower(); } } } public void Close() { } public void AddRegion(Scene scene) { if (!m_enabled) return; m_scene = scene; scene.EventManager.OnAuthorizeUser += EventManager_OnAuthorizeUser; scene.EventManager.OnBeforeSendInstantMessage += EventManager_OnBeforeSendInstantMessage; scene.EventManager.OnChatFromClient += EventManager_OnChatFromClient; } void EventManager_OnChatFromClient(object sender, OSChatMessage chat) { if (!m_enabled) return; if (chat.Message == "" || chat.SenderUUID == chat.DestinationUUID) return; CachedUserInfo info = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(chat.SenderUUID); if (info == null) return; if (info.UserProfile.SurName == "Guest") { //scan for and remove hyperlinks //v2 recognizes .com, .org, and .net links with or without HTTP/S in them.. //so we need a few regexes to cover the cases string noProto = "(\\bwww\\.\\S+\\.\\S+|(?<!@)\\b[^[:space:]:@/>]+\\.(?:com|net|edu|org)([/:][^[:space:]<]*)?\\b)"; string withProto = "https?://([-\\w\\.]+)+(:\\d+)?(:\\w+)?(@\\d+)?(@\\w+)?/?\\S*"; string replaced = Regex.Replace(chat.Message, withProto, "", RegexOptions.IgnoreCase); replaced = Regex.Replace(replaced, noProto, "", RegexOptions.IgnoreCase); chat.Message = replaced; } } /// <summary> /// Guests are not allowed to send instant messages /// </summary> /// <param name="message"></param> /// <returns></returns> bool EventManager_OnBeforeSendInstantMessage(GridInstantMessage message) { if (!m_enabled) return true; if (string.IsNullOrEmpty(message.fromAgentName)) return true; if (!message.fromAgentName.Contains(' ')) return true; string[] name = message.fromAgentName.Split(new char[] {' '}); if (name[1] == "Guest") return false; return true; } /// <summary> /// Guests are only allowed to visit a guest region /// </summary> /// <param name="agent"></param> /// <param name="reason"></param> /// <returns></returns> bool EventManager_OnAuthorizeUser(UUID agentID, string firstName, string lastName, string clientVersion, ref string reason) { if (!m_enabled) return true; if (lastName != "Guest") return true; if (m_limitViewerString != null && clientVersion != null && !clientVersion.ToLower().Contains(m_limitViewerString)) return false; //only the demolay viewer if (m_scene.RegionInfo.RegionName.Contains(m_guestRegionName)) return true; //only the guest region return false; } public void RemoveRegion(Scene scene) { if (!m_enabled) return; m_scene = null; scene.EventManager.OnAuthorizeUser -= EventManager_OnAuthorizeUser; scene.EventManager.OnBeforeSendInstantMessage -= EventManager_OnBeforeSendInstantMessage; scene.EventManager.OnChatFromClient -= EventManager_OnChatFromClient; } public void RegionLoaded(Scene scene) { } #endregion #region Functionality #endregion } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <[email protected]> // // // // Permission is hereby granted, free of charge, to any person obtaining a // // copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation // // the rights to use, copy, modify, merge, publish, distribute, sublicense, // // and/or sell copies of the Software, and to permit persons to whom the // // Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included // // in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // // USE OR OTHER DEALINGS IN THE SOFTWARE. // // // //////////////////////////////////////////////////////////////////////////////// namespace Diva.Core { using System; using System.Collections.Generic; using Mono.Unix; using System.Collections; using Widgets; using Basics; public sealed class Commander : IBoilable { // Events ////////////////////////////////////////////////////// public event EventHandler StackChange; // Fields ////////////////////////////////////////////////////// Stack<IUndoableCommand> undoStack; // The list of commands we can undo Stack<IUndoableCommand> redoStack; // The list of commands we can redo // FIXME: We need to get rid of that (by design) Project parentProject; // The parent we're part of // Properties ////////////////////////////////////////////////// /* Can we undo something */ public bool CanUndo { get { return (undoStack.Count > 0) ? true : false ; } } /* Can we redo something */ public bool CanRedo { get { return (redoStack.Count > 0) ? true : false ; } } /* Operation that will be undone next */ public string UndoMessage { get { if (! CanUndo) return String.Empty; return undoStack.Peek ().Message; } } /* Project parent */ public Project Parent { get { return parentProject; } set { parentProject = value; } } /* Operation that will be redone next */ public string RedoMessage { get { if (! CanRedo) return String.Empty; return redoStack.Peek ().Message; } } // Public methods ////////////////////////////////////////////// /* CONSTRUCTOR */ public Commander (Project parent) { undoStack = new Stack<IUndoableCommand> (); redoStack = new Stack<IUndoableCommand> (); parentProject = parent; } /* CONSTRUCTOR */ public Commander (ObjectContainer container, IBoilProvider provider) { undoStack = new Stack<IUndoableCommand> (); redoStack = new Stack<IUndoableCommand> (); parentProject = null; List <IUndoableCommand> undoList = new List <IUndoableCommand> (); List <IUndoableCommand> redoList = new List <IUndoableCommand> (); foreach (RefParameter reff in container.FindAllRefs ("undo")) undoList.Add ((IUndoableCommand) reff.ToObject (provider)); foreach (RefParameter reff in container.FindAllRefs ("redo")) redoList.Add ((IUndoableCommand) reff.ToObject (provider)); undoList.Reverse (); redoList.Reverse (); foreach (IUndoableCommand cmd in undoList) InjectUndoCommand (cmd); foreach (IUndoableCommand cmd in redoList) InjectRedoCommand (cmd); } /* Execute a command immidiately */ public void Run (ICommand cmd) { ExecuteCommand (cmd); if (StackChange != null) StackChange (this, EventArgs.Empty); } /* Undo one command */ public IUndoableCommand Undo () { if (! CanUndo) throw new CommanderException ("Nothing to undo!"); IUndoableCommand cmd = undoStack.Pop (); UndoCommand (cmd); if (StackChange != null) StackChange (this, EventArgs.Empty); return cmd; } /* Undo many commands */ public IUndoableCommand UndoMany (int many) { if (many <= 0 || many > undoStack.Count) throw new CommanderException ("Trying to undo too many/too few!"); IUndoableCommand cmd = null; for (int i = 0; i < many; i++) cmd = Undo (); return cmd; } /* Redo one command */ public IUndoableCommand Redo () { if (! CanRedo) throw new CommanderException ("Nothing to redo!"); IUndoableCommand cmd = redoStack.Pop (); RedoCommand (cmd); if (StackChange != null) StackChange (this, EventArgs.Empty); return cmd; } /* Redo many commands */ public IUndoableCommand RedoMany (int many) { if (many <= 0 || many > redoStack.Count) throw new CommanderException ("Trying to redo too many/too few!"); IUndoableCommand cmd = null; for (int i = 0; i < many; i++) cmd = Redo (); return cmd; } /* Get the enumerator listing all current undoable commands */ public IEnumerator GetUndoableEnumerator () { return undoStack.GetEnumerator (); } /* Get the enumerator listing all current redoable commands */ public IEnumerator GetRedoableEnumerator () { return redoStack.GetEnumerator (); } /* Inject command to the undo stack. DO NOT use manually */ public void InjectUndoCommand (IUndoableCommand cmd) { undoStack.Push (cmd); } /* Inject command to the redo stack. DO NOT use manually */ public void InjectRedoCommand (IUndoableCommand cmd) { redoStack.Push (cmd); } public List <object> GetDepObjects () { List <object> lst = new List <object> (); foreach (object o in undoStack) lst.Add (o); foreach (object o in redoStack) lst.Add (o); return lst; } public void FlushAll () { FlushUndoStack (); FlushRedoStack (); if (StackChange != null) StackChange (this, EventArgs.Empty); } public void Boil (ObjectContainer container, IBoilProvider provider) { foreach (object o in undoStack) container.Add (new RefParameter ("undo", o, provider)); foreach (object o in redoStack) container.Add (new RefParameter ("redo", o, provider)); } // Private methods ///////////////////////////////////////////// /* Clear the whole undo stack */ void FlushUndoStack () { if (undoStack.Count == 0) return; undoStack = new Stack<IUndoableCommand> (); } /* Clear the whole redo stack */ void FlushRedoStack () { if (redoStack.Count == 0) return; redoStack = new Stack<IUndoableCommand> (); } /* Trim the undoStack to fit the capacity. * Returns the amount of commands removed */ int TrimUndoStack () { /* if (undoStack.Count <= capacity) return 0; int removeCount = undoStack.Count - capacity; for (int i = 0; i < removeCount; i++) undoStack.Dequeue (); return removeCount; */ return 0; } bool DoActionStage (ICommand command) { try { command.DoAction (parentProject); } catch (Exception excp) { throw CommanderException.DoActionStage (command, excp); } return true; } bool NotUndoableStage (ICommand command) { if (! (command is INotUndoableCommand)) return true; try { if (command is INotUndoableCommand) { FlushUndoStack (); FlushRedoStack (); } } catch (Exception excp) { throw CommanderException.NotUndoableStage (command, excp); } return true; } bool PostUndoableStage (ICommand command) { if (! (command is IUndoableCommand)) return true; try { if (command is IRepetitiveCommand) throw new Exception ("Not supported! FIXME!"); else { // A simple undoable command undoStack.Push (command as IUndoableCommand); TrimUndoStack (); FlushRedoStack (); } } catch (Exception excp) { throw CommanderException.PostUndoableStage (command, excp); } return true; } /* Execute the given command */ void ExecuteCommand (ICommand command) { try { CheckIfCommandSane (command); // Try actually doing it if (! DoActionStage (command)) return; // If it's not undoable, flush stacks if (! NotUndoableStage (command)) return; // Do the post-undoable actions if (! PostUndoableStage (command)) return; } catch (Exception excp) { throw CommanderException.CommandExecution (command, excp); } } /* Undo a given command */ void UndoCommand (IUndoableCommand cmd) { try { cmd.UndoAction (parentProject); redoStack.Push (cmd); } catch (Exception excp) { throw CommanderException.UndoActionStage (cmd, excp); } } /* Redo a given command */ void RedoCommand (IUndoableCommand cmd) { try { cmd.DoAction (parentProject); undoStack.Push (cmd); } catch (Exception excp) { throw CommanderException.DoActionStage (cmd, excp); } } /* Check if a given command is sane */ void CheckIfCommandSane (ICommand command) { if (command is IUndoableCommand && command is INotUndoableCommand) throw CoreException.NewSanity (command); if (command is IPreparableCommand && command is ITaskPreparableCommand) throw CoreException.NewSanity (command); } } }
// 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. /*============================================================ ** ** Class: LowLevelList<T> ** ** Private version of List<T> for internal System.Private.CoreLib use. This ** permits sharing more source between BCL and System.Private.CoreLib (as well as the ** fact that List<T> is just a useful class in general.) ** ** This does not strive to implement the full api surface area ** (but any portion it does implement should match the real List<T>'s ** behavior.) ** ** This file is a subset of System.Collections\System\Collections\Generics\List.cs ** and should be kept in sync with that file. ** ===========================================================*/ using System; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Collections.Generic { // Implements a variable-size List that uses an array of objects to store the // elements. A List has a capacity, which is the allocated length // of the internal array. As elements are added to a List, the capacity // of the List is automatically increased as required by reallocating the // internal array. // /// <summary> /// LowLevelList with no interface implementation to minimize both code and data size /// Data size is smaller because there will be minimal virtual function table. /// Code size is smaller because only functions called will be in the binary. /// Use LowLevelListWithIList<T> for IList support /// </summary> [DebuggerDisplay("Count = {Count}")] #if TYPE_LOADER_IMPLEMENTATION [System.Runtime.CompilerServices.ForceDictionaryLookups] #endif internal class LowLevelList<T> { private const int _defaultCapacity = 4; protected T[] _items; [ContractPublicPropertyName("Count")] protected int _size; protected int _version; // Constructs a List. The list is initially empty and has a capacity // of zero. Upon adding the first element to the list the capacity is // increased to 16, and then increased in multiples of two as required. public LowLevelList() { _items = Array.Empty<T>(); } // Constructs a List with a given initial capacity. The list is // initially empty, but will have room for the given number of elements // before any reallocations are required. // public LowLevelList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); Contract.EndContractBlock(); if (capacity == 0) _items = Array.Empty<T>(); else _items = new T[capacity]; } // Constructs a List, copying the contents of the given collection. The // size and capacity of the new list will both be equal to the size of the // given collection. // public LowLevelList(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if (c != null) { int count = c.Count; if (count == 0) { _items = Array.Empty<T>(); } else { _items = new T[count]; c.CopyTo(_items, 0); _size = count; } } else { _size = 0; _items = Array.Empty<T>(); // This enumerable could be empty. Let Add allocate a new array, if needed. // Note it will also go to _defaultCapacity first, not 1, then 2, etc. using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Add(en.Current); } } } } // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public int Capacity { get { Contract.Ensures(Contract.Result<int>() >= 0); return _items.Length; } set { if (value < _size) { throw new ArgumentOutOfRangeException(nameof(value)); } Contract.EndContractBlock(); if (value != _items.Length) { if (value > 0) { T[] newItems = new T[value]; Array.Copy(_items, 0, newItems, 0, _size); _items = newItems; } else { _items = Array.Empty<T>(); } } } } // Read-only property describing how many elements are in the List. public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } // Sets or Gets the element at the given index. // public T this[int index] { get { // Following trick can reduce the range check by one if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(); } Contract.EndContractBlock(); return _items[index]; } set { if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(); } Contract.EndContractBlock(); _items[index] = value; _version++; } } // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. // public void Add(T item) { if (_size == _items.Length) EnsureCapacity(_size + 1); _items[_size++] = item; _version++; } // Ensures that the capacity of this list is at least the given minimum // value. If the current capacity of the list is less than min, the // capacity is increased to twice the current capacity or to min, // whichever is larger. private void EnsureCapacity(int min) { if (_items.Length < min) { int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast //if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } } #if !TYPE_LOADER_IMPLEMENTATION // Adds the elements of the given collection to the end of this list. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. // public void AddRange(IEnumerable<T> collection) { Contract.Ensures(Count >= Contract.OldValue(Count)); InsertRange(_size, collection); } // Clears the contents of List. public void Clear() { if (_size > 0) { Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; } _version++; } // Contains returns true if the specified element is in the List. // It does a linear, O(n) search. Equality is determined by calling // item.Equals(). // public bool Contains(T item) { if ((object)item == null) { for (int i = 0; i < _size; i++) if ((object)_items[i] == null) return true; return false; } else { int index = IndexOf(item); if (index >= 0) return true; return false; } } // Copies a section of this list to the given array at the given index. // // The method uses the Array.Copy method to copy the elements. // public void CopyTo(int index, T[] array, int arrayIndex, int count) { if (_size - index < count) { throw new ArgumentException(); } Contract.EndContractBlock(); // Delegate rest of error checking to Array.Copy. Array.Copy(_items, index, array, arrayIndex, count); } public void CopyTo(T[] array, int arrayIndex) { // Delegate rest of error checking to Array.Copy. Array.Copy(_items, 0, array, arrayIndex, _size); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return Array.IndexOf(_items, item, 0, _size); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and ending at count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item, int index) { if (index > _size) throw new ArgumentOutOfRangeException(nameof(index)); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, _size - index); } // Inserts an element into this list at a given index. The size of the list // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. // public void Insert(int index, T item) { // Note that insertions at the end are legal. if ((uint)index > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); if (_size == _items.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(_items, index, _items, index + 1, _size - index); } _items[index] = item; _size++; _version++; } // Inserts the elements of the given collection at a given index. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the List's size. // public void InsertRange(int index, IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if ((uint)index > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if (c != null) { // if collection is ICollection<T> int count = c.Count; if (count > 0) { EnsureCapacity(_size + count); if (index < _size) { Array.Copy(_items, index, _items, index + count, _size - index); } // If we're inserting a List into itself, we want to be able to deal with that. if (this == c) { // Copy first part of _items to insert location Array.Copy(_items, 0, _items, index, index); // Copy last part of _items back to inserted location Array.Copy(_items, index + count, _items, index * 2, _size - index); } else { T[] itemsToInsert = new T[count]; c.CopyTo(itemsToInsert, 0); Array.Copy(itemsToInsert, 0, _items, index, count); } _size += count; } } else { using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Insert(index++, en.Current); } } } _version++; } // Removes the element at the given index. The size of the list is // decreased by one. // public bool Remove(T item) { int index = IndexOf(item); if (index >= 0) { RemoveAt(index); return true; } return false; } // This method removes all items which matches the predicate. // The complexity is O(n). public int RemoveAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count)); Contract.EndContractBlock(); int freeIndex = 0; // the first free slot in items array // Find the first item which needs to be removed. while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++; if (freeIndex >= _size) return 0; int current = freeIndex + 1; while (current < _size) { // Find the first item which needs to be kept. while (current < _size && match(_items[current])) current++; if (current < _size) { // copy item to the free slot. _items[freeIndex++] = _items[current++]; } } Array.Clear(_items, freeIndex, _size - freeIndex); int result = _size - freeIndex; _size = freeIndex; _version++; return result; } // Removes the element at the given index. The size of the list is // decreased by one. // public void RemoveAt(int index) { if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); _size--; if (index < _size) { Array.Copy(_items, index + 1, _items, index, _size - index); } _items[_size] = default(T); _version++; } // ToArray returns a new Object array containing the contents of the List. // This requires copying the List, which is an O(n) operation. public T[] ToArray() { Contract.Ensures(Contract.Result<T[]>() != null); Contract.Ensures(Contract.Result<T[]>().Length == Count); T[] array = new T[_size]; Array.Copy(_items, 0, array, 0, _size); return array; } #endif } #if !TYPE_LOADER_IMPLEMENTATION /// <summary> /// LowLevelList<T> with full IList<T> implementation /// </summary> internal sealed class LowLevelListWithIList<T> : LowLevelList<T>, IList<T> { public LowLevelListWithIList() { } public LowLevelListWithIList(int capacity) : base(capacity) { } // Is this List read-only? bool ICollection<T>.IsReadOnly { get { return false; } } /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } private struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private LowLevelListWithIList<T> _list; private int _index; private int _version; private T _current; internal Enumerator(LowLevelListWithIList<T> list) { _list = list; _index = 0; _version = list._version; _current = default(T); } public void Dispose() { } public bool MoveNext() { LowLevelListWithIList<T> localList = _list; if (_version == localList._version && ((uint)_index < (uint)localList._size)) { _current = localList._items[_index]; _index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { if (_version != _list._version) { throw new InvalidOperationException(); } _index = _list._size + 1; _current = default(T); return false; } public T Current { get { return _current; } } object System.Collections.IEnumerator.Current { get { if (_index == 0 || _index == _list._size + 1) { throw new InvalidOperationException(); } return Current; } } void System.Collections.IEnumerator.Reset() { if (_version != _list._version) { throw new InvalidOperationException(); } _index = 0; _current = default(T); } } } #endif // !TYPE_LOADER_IMPLEMENTATION }
//------------------------------------------------------------------------------ // <copyright file="CheckContentMD5Test.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace DMLibTest.Cases { using System; using System.Collections.Generic; using DMLibTestCodeGen; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage.DataMovement; using MS.Test.Common.MsTestLib; [MultiDirectionTestClass] public class CheckContentMD5Test : DMLibTestBase #if DNXCORE50 , IDisposable #endif { #region Initialization and cleanup methods #if DNXCORE50 public CheckContentMD5Test() { MyTestInitialize(); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { MyTestCleanup(); } #endif [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { Test.Info("Class Initialize: CheckContentMD5Test"); DMLibTestBase.BaseClassInitialize(testContext); } [ClassCleanup()] public static void MyClassCleanup() { DMLibTestBase.BaseClassCleanup(); } [TestInitialize()] public void MyTestInitialize() { base.BaseTestInitialize(); } [TestCleanup()] public void MyTestCleanup() { base.BaseTestCleanup(); } #endregion [TestCategory(Tag.Function)] [DMLibTestMethodSet(DMLibTestMethodSet.LocalDest)] public void TestCheckContentMD5() { long fileSize = 10 * 1024 * 1024; string wrongMD5 = "wrongMD5"; string checkWrongMD5File = "checkWrongMD5File"; string notCheckWrongMD5File = "notCheckWrongMD5File"; string checkCorrectMD5File = "checkCorrectMD5File"; string notCheckCorrectMD5File = "notCheckCorrectMD5File"; DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty); DMLibDataHelper.AddOneFileInBytes(sourceDataInfo.RootNode, checkWrongMD5File, fileSize); FileNode tmpFileNode = sourceDataInfo.RootNode.GetFileNode(checkWrongMD5File); tmpFileNode.MD5 = wrongMD5; DMLibDataHelper.AddOneFileInBytes(sourceDataInfo.RootNode, notCheckWrongMD5File, fileSize); tmpFileNode = sourceDataInfo.RootNode.GetFileNode(notCheckWrongMD5File); tmpFileNode.MD5 = wrongMD5; DMLibDataHelper.AddOneFileInBytes(sourceDataInfo.RootNode, checkCorrectMD5File, fileSize); DMLibDataHelper.AddOneFileInBytes(sourceDataInfo.RootNode, notCheckCorrectMD5File, fileSize); var options = new TestExecutionOptions<DMLibDataInfo>(); options.TransferItemModifier = (fileNode, transferItem) => { string fileName = fileNode.Name; DownloadOptions downloadOptions = new DownloadOptions(); if (fileName.Equals(checkWrongMD5File) || fileName.Equals(checkCorrectMD5File)) { downloadOptions.DisableContentMD5Validation = false; } else if (fileName.Equals(notCheckWrongMD5File) || fileName.Equals(notCheckCorrectMD5File)) { downloadOptions.DisableContentMD5Validation = true; } transferItem.Options = downloadOptions; }; var result = this.ExecuteTestCase(sourceDataInfo, options); Test.Assert(result.Exceptions.Count == 1, "Verify there's one exception."); Exception exception = result.Exceptions[0]; Test.Assert(exception is InvalidOperationException, "Verify it's an invalid operation exception."); VerificationHelper.VerifyExceptionErrorMessage(exception, "The MD5 hash calculated from the downloaded data does not match the MD5 hash stored", checkWrongMD5File); } [TestCategory(Tag.Function)] [DMLibTestMethodSet(DMLibTestMethodSet.LocalDest)] public void TestDirectoryCheckContentMD5() { long fileSize = 5 * 1024 * 1024; long totalSize = fileSize * 4; string wrongMD5 = "wrongMD5"; string checkWrongMD5File = "checkWrongMD5File"; string checkCorrectMD5File = "checkCorrectMD5File"; string notCheckWrongMD5File = "notCheckWrongMD5File"; string notCheckCorrectMD5File = "notCheckCorrectMD5File"; DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty); DirNode checkMD5Folder = new DirNode("checkMD5"); DMLibDataHelper.AddOneFileInBytes(checkMD5Folder, checkWrongMD5File, fileSize); DMLibDataHelper.AddOneFileInBytes(checkMD5Folder, checkCorrectMD5File, fileSize); sourceDataInfo.RootNode.AddDirNode(checkMD5Folder); DirNode notCheckMD5Folder = new DirNode("notCheckMD5"); DMLibDataHelper.AddOneFileInBytes(notCheckMD5Folder, notCheckWrongMD5File, fileSize); DMLibDataHelper.AddOneFileInBytes(notCheckMD5Folder, notCheckCorrectMD5File, fileSize); sourceDataInfo.RootNode.AddDirNode(notCheckMD5Folder); FileNode tmpFileNode = checkMD5Folder.GetFileNode(checkWrongMD5File); tmpFileNode.MD5 = wrongMD5; tmpFileNode = notCheckMD5Folder.GetFileNode(notCheckWrongMD5File); tmpFileNode.MD5 = wrongMD5; SourceAdaptor.GenerateData(sourceDataInfo); TransferEventChecker eventChecker = new TransferEventChecker(); TransferContext context = new DirectoryTransferContext(); eventChecker.Apply(context); bool failureReported = false; context.FileFailed += (sender, args) => { if (args.Exception != null) { failureReported = args.Exception.Message.Contains(checkWrongMD5File); } }; ProgressChecker progressChecker = new ProgressChecker(4, totalSize, 3, 1, 0, totalSize); context.ProgressHandler = progressChecker.GetProgressHandler(); List<Exception> transferExceptions = new List<Exception>(); context.FileFailed += (eventSource, eventArgs) => { transferExceptions.Add(eventArgs.Exception); }; TransferItem checkMD5Item = new TransferItem() { SourceObject = SourceAdaptor.GetTransferObject(sourceDataInfo.RootPath, checkMD5Folder), DestObject = DestAdaptor.GetTransferObject(sourceDataInfo.RootPath, checkMD5Folder), IsDirectoryTransfer = true, SourceType = DMLibTestContext.SourceType, DestType = DMLibTestContext.DestType, IsServiceCopy = DMLibTestContext.IsAsync, TransferContext = context, Options = new DownloadDirectoryOptions() { DisableContentMD5Validation = false, Recursive = true, }, }; TransferItem notCheckMD5Item = new TransferItem() { SourceObject = SourceAdaptor.GetTransferObject(sourceDataInfo.RootPath, notCheckMD5Folder), DestObject = DestAdaptor.GetTransferObject(sourceDataInfo.RootPath, notCheckMD5Folder), IsDirectoryTransfer = true, SourceType = DMLibTestContext.SourceType, DestType = DMLibTestContext.DestType, IsServiceCopy = DMLibTestContext.IsAsync, TransferContext = context, Options = new DownloadDirectoryOptions() { DisableContentMD5Validation = true, Recursive = true, }, }; var testResult = this.RunTransferItems(new List<TransferItem>() { checkMD5Item, notCheckMD5Item }, new TestExecutionOptions<DMLibDataInfo>()); DMLibDataInfo expectedDataInfo = sourceDataInfo.Clone(); expectedDataInfo.RootNode.GetDirNode(checkMD5Folder.Name).DeleteFileNode(checkWrongMD5File); expectedDataInfo.RootNode.GetDirNode(notCheckMD5Folder.Name).DeleteFileNode(notCheckWrongMD5File); DMLibDataInfo actualDataInfo = testResult.DataInfo; actualDataInfo.RootNode.GetDirNode(checkMD5Folder.Name).DeleteFileNode(checkWrongMD5File); actualDataInfo.RootNode.GetDirNode(notCheckMD5Folder.Name).DeleteFileNode(notCheckWrongMD5File); Test.Assert(DMLibDataHelper.Equals(expectedDataInfo, actualDataInfo), "Verify transfer result."); Test.Assert(failureReported, "Verify md5 check failure is reported."); VerificationHelper.VerifyFinalProgress(progressChecker, 3, 0, 1); if (testResult.Exceptions.Count != 0 || transferExceptions.Count != 1) { Test.Error("Expect one exception but actually no exception is thrown."); } else { VerificationHelper.VerifyExceptionErrorMessage(transferExceptions[0], new string[] { "The MD5 hash calculated from the downloaded data does not match the MD5 hash stored in the property of source" }); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.ServiceBus; using Microsoft.WindowsAzure.Management.ServiceBus.Models; namespace Microsoft.WindowsAzure.Management.ServiceBus { /// <summary> /// The Service Bus Management API includes operations for managing Service /// Bus notification hubs. /// </summary> internal partial class NotificationHubOperations : IServiceOperations<ServiceBusManagementClient>, INotificationHubOperations { /// <summary> /// Initializes a new instance of the NotificationHubOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal NotificationHubOperations(ServiceBusManagementClient client) { this._client = client; } private ServiceBusManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.ServiceBus.ServiceBusManagementClient. /// </summary> public ServiceBusManagementClient Client { get { return this._client; } } /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public async Task<ServiceBusNotificationHubResponse> GetAsync(string namespaceName, string notificationHubName, CancellationToken cancellationToken) { // Validate if (namespaceName == null) { throw new ArgumentNullException("namespaceName"); } if (notificationHubName == null) { throw new ArgumentNullException("notificationHubName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("notificationHubName", notificationHubName); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/servicebus/namespaces/" + namespaceName + "/NotificationHubs/" + notificationHubName; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-08-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ServiceBusNotificationHubResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceBusNotificationHubResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement entryElement = responseDoc.Element(XName.Get("entry", "http://www.w3.org/2005/Atom")); if (entryElement != null) { XElement titleElement = entryElement.Element(XName.Get("title", "http://www.w3.org/2005/Atom")); if (titleElement != null) { } XElement contentElement = entryElement.Element(XName.Get("content", "http://www.w3.org/2005/Atom")); if (contentElement != null) { XElement notificationHubDescriptionElement = contentElement.Element(XName.Get("NotificationHubDescription", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (notificationHubDescriptionElement != null) { ServiceBusNotificationHub notificationHubDescriptionInstance = new ServiceBusNotificationHub(); result.NotificationHub = notificationHubDescriptionInstance; XElement registrationTtlElement = notificationHubDescriptionElement.Element(XName.Get("RegistrationTtl", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (registrationTtlElement != null) { string registrationTtlInstance = registrationTtlElement.Value; notificationHubDescriptionInstance.RegistrationTtl = registrationTtlInstance; } XElement authorizationRulesSequenceElement = notificationHubDescriptionElement.Element(XName.Get("AuthorizationRules", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (authorizationRulesSequenceElement != null) { foreach (XElement authorizationRulesElement in authorizationRulesSequenceElement.Elements(XName.Get("AuthorizationRule", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"))) { ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule(); notificationHubDescriptionInstance.AuthorizationRules.Add(authorizationRuleInstance); XElement claimTypeElement = authorizationRulesElement.Element(XName.Get("ClaimType", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (claimTypeElement != null) { string claimTypeInstance = claimTypeElement.Value; authorizationRuleInstance.ClaimType = claimTypeInstance; } XElement claimValueElement = authorizationRulesElement.Element(XName.Get("ClaimValue", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (claimValueElement != null) { string claimValueInstance = claimValueElement.Value; authorizationRuleInstance.ClaimValue = claimValueInstance; } XElement rightsSequenceElement = authorizationRulesElement.Element(XName.Get("Rights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (rightsSequenceElement != null) { foreach (XElement rightsElement in rightsSequenceElement.Elements(XName.Get("AccessRights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"))) { authorizationRuleInstance.Rights.Add((AccessRight)Enum.Parse(typeof(AccessRight), rightsElement.Value, false)); } } XElement createdTimeElement = authorizationRulesElement.Element(XName.Get("CreatedTime", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (createdTimeElement != null) { DateTime createdTimeInstance = DateTime.Parse(createdTimeElement.Value, CultureInfo.InvariantCulture); authorizationRuleInstance.CreatedTime = createdTimeInstance; } XElement keyNameElement = authorizationRulesElement.Element(XName.Get("KeyName", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (keyNameElement != null) { string keyNameInstance = keyNameElement.Value; authorizationRuleInstance.KeyName = keyNameInstance; } XElement modifiedTimeElement = authorizationRulesElement.Element(XName.Get("ModifiedTime", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (modifiedTimeElement != null) { DateTime modifiedTimeInstance = DateTime.Parse(modifiedTimeElement.Value, CultureInfo.InvariantCulture); authorizationRuleInstance.ModifiedTime = modifiedTimeInstance; } XElement primaryKeyElement = authorizationRulesElement.Element(XName.Get("PrimaryKey", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (primaryKeyElement != null) { string primaryKeyInstance = primaryKeyElement.Value; authorizationRuleInstance.PrimaryKey = primaryKeyInstance; } XElement secondaryKeyElement = authorizationRulesElement.Element(XName.Get("SecondaryKey", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (secondaryKeyElement != null) { string secondaryKeyInstance = secondaryKeyElement.Value; authorizationRuleInstance.SecondaryKey = secondaryKeyInstance; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The set of connection details for a service bus entity. /// </returns> public async Task<ServiceBusConnectionDetailsResponse> GetConnectionDetailsAsync(string namespaceName, string notificationHubName, CancellationToken cancellationToken) { // Validate if (namespaceName == null) { throw new ArgumentNullException("namespaceName"); } if (notificationHubName == null) { throw new ArgumentNullException("notificationHubName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("notificationHubName", notificationHubName); Tracing.Enter(invocationId, this, "GetConnectionDetailsAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/servicebus/namespaces/" + namespaceName + "/NotificationHubs/" + notificationHubName + "/ConnectionDetails"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-08-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ServiceBusConnectionDetailsResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceBusConnectionDetailsResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement feedElement = responseDoc.Element(XName.Get("feed", "http://www.w3.org/2005/Atom")); if (feedElement != null) { if (feedElement != null) { foreach (XElement entriesElement in feedElement.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom"))) { ServiceBusConnectionDetail entryInstance = new ServiceBusConnectionDetail(); result.ConnectionDetails.Add(entryInstance); XElement contentElement = entriesElement.Element(XName.Get("content", "http://www.w3.org/2005/Atom")); if (contentElement != null) { XElement connectionDetailElement = contentElement.Element(XName.Get("ConnectionDetail", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (connectionDetailElement != null) { XElement keyNameElement = connectionDetailElement.Element(XName.Get("KeyName", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (keyNameElement != null) { string keyNameInstance = keyNameElement.Value; entryInstance.KeyName = keyNameInstance; } XElement connectionStringElement = connectionDetailElement.Element(XName.Get("ConnectionString", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (connectionStringElement != null) { string connectionStringInstance = connectionStringElement.Value; entryInstance.ConnectionString = connectionStringInstance; } XElement authorizationTypeElement = connectionDetailElement.Element(XName.Get("AuthorizationType", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (authorizationTypeElement != null) { string authorizationTypeInstance = authorizationTypeElement.Value; entryInstance.AuthorizationType = authorizationTypeInstance; } XElement rightsSequenceElement = connectionDetailElement.Element(XName.Get("Rights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (rightsSequenceElement != null) { foreach (XElement rightsElement in rightsSequenceElement.Elements(XName.Get("AccessRights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"))) { entryInstance.Rights.Add((AccessRight)Enum.Parse(typeof(AccessRight), rightsElement.Value, false)); } } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public async Task<ServiceBusNotificationHubsResponse> ListAsync(string namespaceName, CancellationToken cancellationToken) { // Validate if (namespaceName == null) { throw new ArgumentNullException("namespaceName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("namespaceName", namespaceName); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/servicebus/namespaces/" + namespaceName + "/NotificationHubs"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-08-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ServiceBusNotificationHubsResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceBusNotificationHubsResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement feedElement = responseDoc.Element(XName.Get("feed", "http://www.w3.org/2005/Atom")); if (feedElement != null) { if (feedElement != null) { foreach (XElement entriesElement in feedElement.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom"))) { ServiceBusNotificationHub entryInstance = new ServiceBusNotificationHub(); result.NotificationHubs.Add(entryInstance); XElement titleElement = entriesElement.Element(XName.Get("title", "http://www.w3.org/2005/Atom")); if (titleElement != null) { string titleInstance = titleElement.Value; entryInstance.Name = titleInstance; } XElement contentElement = entriesElement.Element(XName.Get("content", "http://www.w3.org/2005/Atom")); if (contentElement != null) { XElement notificationHubDescriptionElement = contentElement.Element(XName.Get("NotificationHubDescription", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (notificationHubDescriptionElement != null) { XElement registrationTtlElement = notificationHubDescriptionElement.Element(XName.Get("RegistrationTtl", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (registrationTtlElement != null) { string registrationTtlInstance = registrationTtlElement.Value; entryInstance.RegistrationTtl = registrationTtlInstance; } XElement authorizationRulesSequenceElement = notificationHubDescriptionElement.Element(XName.Get("AuthorizationRules", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (authorizationRulesSequenceElement != null) { foreach (XElement authorizationRulesElement in authorizationRulesSequenceElement.Elements(XName.Get("AuthorizationRule", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"))) { ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule(); entryInstance.AuthorizationRules.Add(authorizationRuleInstance); XElement claimTypeElement = authorizationRulesElement.Element(XName.Get("ClaimType", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (claimTypeElement != null) { string claimTypeInstance = claimTypeElement.Value; authorizationRuleInstance.ClaimType = claimTypeInstance; } XElement claimValueElement = authorizationRulesElement.Element(XName.Get("ClaimValue", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (claimValueElement != null) { string claimValueInstance = claimValueElement.Value; authorizationRuleInstance.ClaimValue = claimValueInstance; } XElement rightsSequenceElement = authorizationRulesElement.Element(XName.Get("Rights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (rightsSequenceElement != null) { foreach (XElement rightsElement in rightsSequenceElement.Elements(XName.Get("AccessRights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"))) { authorizationRuleInstance.Rights.Add((AccessRight)Enum.Parse(typeof(AccessRight), rightsElement.Value, false)); } } XElement createdTimeElement = authorizationRulesElement.Element(XName.Get("CreatedTime", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (createdTimeElement != null) { DateTime createdTimeInstance = DateTime.Parse(createdTimeElement.Value, CultureInfo.InvariantCulture); authorizationRuleInstance.CreatedTime = createdTimeInstance; } XElement keyNameElement = authorizationRulesElement.Element(XName.Get("KeyName", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (keyNameElement != null) { string keyNameInstance = keyNameElement.Value; authorizationRuleInstance.KeyName = keyNameInstance; } XElement modifiedTimeElement = authorizationRulesElement.Element(XName.Get("ModifiedTime", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (modifiedTimeElement != null) { DateTime modifiedTimeInstance = DateTime.Parse(modifiedTimeElement.Value, CultureInfo.InvariantCulture); authorizationRuleInstance.ModifiedTime = modifiedTimeInstance; } XElement primaryKeyElement = authorizationRulesElement.Element(XName.Get("PrimaryKey", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (primaryKeyElement != null) { string primaryKeyInstance = primaryKeyElement.Value; authorizationRuleInstance.PrimaryKey = primaryKeyInstance; } XElement secondaryKeyElement = authorizationRulesElement.Element(XName.Get("SecondaryKey", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (secondaryKeyElement != null) { string secondaryKeyInstance = secondaryKeyElement.Value; authorizationRuleInstance.SecondaryKey = secondaryKeyInstance; } } } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // HashJoinQueryOperatorEnumerator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// This enumerator implements the hash-join algorithm as noted earlier. /// /// Assumptions: /// This enumerator type won't work properly at all if the analysis engine didn't /// ensure a proper hash-partition. We expect inner and outer elements with equal /// keys are ALWAYS in the same partition. If they aren't (e.g. if the analysis is /// busted) we'll silently drop items on the floor. :( /// /// /// This is the enumerator class for two operators: /// - Join /// - GroupJoin /// </summary> /// <typeparam name="TLeftInput"></typeparam> /// <typeparam name="TLeftKey"></typeparam> /// <typeparam name="TRightInput"></typeparam> /// <typeparam name="THashKey"></typeparam> /// <typeparam name="TOutput"></typeparam> internal class HashJoinQueryOperatorEnumerator<TLeftInput, TLeftKey, TRightInput, THashKey, TOutput> : QueryOperatorEnumerator<TOutput, TLeftKey> { private readonly QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left (outer) data source. For probing. private readonly QueryOperatorEnumerator<Pair, int> _rightSource; // Right (inner) data source. For building. private readonly Func<TLeftInput, TRightInput, TOutput> _singleResultSelector; // Single result selector. private readonly Func<TLeftInput, IEnumerable<TRightInput>, TOutput> _groupResultSelector; // Group result selector. private readonly IEqualityComparer<THashKey> _keyComparer; // An optional key comparison object. private readonly CancellationToken _cancellationToken; private Mutables _mutables; private class Mutables { internal TLeftInput _currentLeft; // The current matching left element. internal TLeftKey _currentLeftKey; // The current index of the matching left element. internal HashLookup<THashKey, Pair> _rightHashLookup; // The hash lookup. internal ListChunk<TRightInput> _currentRightMatches; // Current right matches (if any). internal int _currentRightMatchesIndex; // Current index in the set of right matches. internal int _outputLoopCount; } //--------------------------------------------------------------------------------------- // Instantiates a new hash-join enumerator. // internal HashJoinQueryOperatorEnumerator( QueryOperatorEnumerator<Pair, TLeftKey> leftSource, QueryOperatorEnumerator<Pair, int> rightSource, Func<TLeftInput, TRightInput, TOutput> singleResultSelector, Func<TLeftInput, IEnumerable<TRightInput>, TOutput> groupResultSelector, IEqualityComparer<THashKey> keyComparer, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(rightSource != null); Debug.Assert(singleResultSelector != null || groupResultSelector != null); _leftSource = leftSource; _rightSource = rightSource; _singleResultSelector = singleResultSelector; _groupResultSelector = groupResultSelector; _keyComparer = keyComparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // MoveNext implements all the hash-join logic noted earlier. When it is called first, it // will execute the entire inner query tree, and build a hash-table lookup. This is the // Building phase. Then for the first call and all subsequent calls to MoveNext, we will // incrementally perform the Probing phase. We'll keep getting elements from the outer // data source, looking into the hash-table we built, and enumerating the full results. // // This routine supports both inner and outer (group) joins. An outer join will yield a // (possibly empty) list of matching elements from the inner instead of one-at-a-time, // as we do for inner joins. // internal override bool MoveNext(ref TOutput currentElement, ref TLeftKey currentKey) { Debug.Assert(_singleResultSelector != null || _groupResultSelector != null, "expected a compiled result selector"); Debug.Assert(_leftSource != null); Debug.Assert(_rightSource != null); // BUILD phase: If we haven't built the hash-table yet, create that first. Mutables mutables = _mutables; if (mutables == null) { mutables = _mutables = new Mutables(); #if DEBUG int hashLookupCount = 0; int hashKeyCollisions = 0; #endif mutables._rightHashLookup = new HashLookup<THashKey, Pair>(_keyComparer); Pair rightPair = new Pair(default(TRightInput), default(THashKey)); int rightKeyUnused = default(int); int i = 0; while (_rightSource.MoveNext(ref rightPair, ref rightKeyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); TRightInput rightElement = (TRightInput)rightPair.First; THashKey rightHashKey = (THashKey)rightPair.Second; // We ignore null keys. if (rightHashKey != null) { #if DEBUG hashLookupCount++; #endif // See if we've already stored an element under the current key. If not, we // lazily allocate a pair to hold the elements mapping to the same key. const int INITIAL_CHUNK_SIZE = 2; Pair currentValue = new Pair(default(TRightInput), default(ListChunk<TRightInput>)); if (!mutables._rightHashLookup.TryGetValue(rightHashKey, ref currentValue)) { currentValue = new Pair(rightElement, null); if (_groupResultSelector != null) { // For group joins, we also add the element to the list. This makes // it easier later to yield the list as-is. currentValue.Second = new ListChunk<TRightInput>(INITIAL_CHUNK_SIZE); ((ListChunk<TRightInput>)currentValue.Second).Add((TRightInput)rightElement); } mutables._rightHashLookup.Add(rightHashKey, currentValue); } else { if (currentValue.Second == null) { // Lazily allocate a list to hold all but the 1st value. We need to // re-store this element because the pair is a value type. currentValue.Second = new ListChunk<TRightInput>(INITIAL_CHUNK_SIZE); mutables._rightHashLookup[rightHashKey] = currentValue; } ((ListChunk<TRightInput>)currentValue.Second).Add((TRightInput)rightElement); #if DEBUG hashKeyCollisions++; #endif } } } #if DEBUG TraceHelpers.TraceInfo("ParallelJoinQueryOperator::MoveNext - built hash table [count = {0}, collisions = {1}]", hashLookupCount, hashKeyCollisions); #endif } // PROBE phase: So long as the source has a next element, return the match. ListChunk<TRightInput> currentRightChunk = mutables._currentRightMatches; if (currentRightChunk != null && mutables._currentRightMatchesIndex == currentRightChunk.Count) { currentRightChunk = mutables._currentRightMatches = currentRightChunk.Next; mutables._currentRightMatchesIndex = 0; } if (mutables._currentRightMatches == null) { // We have to look up the next list of matches in the hash-table. Pair leftPair = new Pair(default(TLeftInput), default(THashKey)); TLeftKey leftKey = default(TLeftKey); while (_leftSource.MoveNext(ref leftPair, ref leftKey)) { if ((mutables._outputLoopCount++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Find the match in the hash table. Pair matchValue = new Pair(default(TRightInput), default(ListChunk<TRightInput>)); TLeftInput leftElement = (TLeftInput)leftPair.First; THashKey leftHashKey = (THashKey)leftPair.Second; // Ignore null keys. if (leftHashKey != null) { if (mutables._rightHashLookup.TryGetValue(leftHashKey, ref matchValue)) { // We found a new match. For inner joins, we remember the list in case // there are multiple value under this same key -- the next iteration will pick // them up. For outer joins, we will use the list momentarily. if (_singleResultSelector != null) { mutables._currentRightMatches = (ListChunk<TRightInput>)matchValue.Second; Debug.Assert(mutables._currentRightMatches == null || mutables._currentRightMatches.Count > 0, "we were expecting that the list would be either null or empty"); mutables._currentRightMatchesIndex = 0; // Yield the value. currentElement = _singleResultSelector(leftElement, (TRightInput)matchValue.First); currentKey = leftKey; // If there is a list of matches, remember the left values for next time. if (matchValue.Second != null) { mutables._currentLeft = leftElement; mutables._currentLeftKey = leftKey; } return true; } } } // For outer joins, we always yield a result. if (_groupResultSelector != null) { // Grab the matches, or create an empty list if there are none. IEnumerable<TRightInput> matches = (ListChunk<TRightInput>)matchValue.Second; if (matches == null) { matches = ParallelEnumerable.Empty<TRightInput>(); } // Generate the current value. currentElement = _groupResultSelector(leftElement, matches); currentKey = leftKey; return true; } } // If we've reached the end of the data source, we're done. return false; } // Produce the next element and increment our index within the matches. Debug.Assert(_singleResultSelector != null); Debug.Assert(mutables._currentRightMatches != null); Debug.Assert(0 <= mutables._currentRightMatchesIndex && mutables._currentRightMatchesIndex < mutables._currentRightMatches.Count); currentElement = _singleResultSelector( mutables._currentLeft, mutables._currentRightMatches._chunk[mutables._currentRightMatchesIndex]); currentKey = mutables._currentLeftKey; mutables._currentRightMatchesIndex++; return true; } protected override void Dispose(bool disposing) { Debug.Assert(_leftSource != null && _rightSource != null); _leftSource.Dispose(); _rightSource.Dispose(); } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #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.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Linq { internal class JPath { private readonly string _expression; public List<object> Parts { get; private set; } private int _currentIndex; public JPath(string expression) { ValidationUtils.ArgumentNotNull(expression, "expression"); _expression = expression; Parts = new List<object>(); ParseMain(); } private void ParseMain() { int currentPartStartIndex = _currentIndex; bool followingIndexer = false; while (_currentIndex < _expression.Length) { char currentChar = _expression[_currentIndex]; switch (currentChar) { case '[': case '(': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); Parts.Add(member); } ParseIndexer(currentChar); currentPartStartIndex = _currentIndex + 1; followingIndexer = true; break; case ']': case ')': throw new JsonException("Unexpected character while parsing path: " + currentChar); case '.': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); Parts.Add(member); } currentPartStartIndex = _currentIndex + 1; followingIndexer = false; break; default: if (followingIndexer) throw new JsonException("Unexpected character following indexer: " + currentChar); break; } _currentIndex++; } if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); Parts.Add(member); } } private void ParseIndexer(char indexerOpenChar) { _currentIndex++; char indexerCloseChar = (indexerOpenChar == '[') ? ']' : ')'; int indexerStart = _currentIndex; int indexerLength = 0; bool indexerClosed = false; while (_currentIndex < _expression.Length) { char currentCharacter = _expression[_currentIndex]; if (char.IsDigit(currentCharacter)) { indexerLength++; } else if (currentCharacter == indexerCloseChar) { indexerClosed = true; break; } else { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } _currentIndex++; } if (!indexerClosed) throw new JsonException("Path ended with open indexer. Expected " + indexerCloseChar); if (indexerLength == 0) throw new JsonException("Empty path indexer."); string indexer = _expression.Substring(indexerStart, indexerLength); Parts.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); } internal JToken Evaluate(JToken root, bool errorWhenNoMatch) { JToken current = root; foreach (object part in Parts) { string propertyName = part as string; if (propertyName != null) { JObject o = current as JObject; if (o != null) { current = o[propertyName]; if (current == null && errorWhenNoMatch) throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, propertyName)); } else { if (errorWhenNoMatch) throw new JsonException("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, propertyName, current.GetType().Name)); return null; } } else { int index = (int) part; JArray a = current as JArray; JConstructor c = current as JConstructor; if (a != null) { if (a.Count <= index) { if (errorWhenNoMatch) throw new JsonException("Index {0} outside the bounds of JArray.".FormatWith(CultureInfo.InvariantCulture, index)); return null; } current = a[index]; } else if (c != null) { if (c.Count <= index) { if (errorWhenNoMatch) throw new JsonException("Index {0} outside the bounds of JConstructor.".FormatWith(CultureInfo.InvariantCulture, index)); return null; } current = c[index]; } else { if (errorWhenNoMatch) throw new JsonException("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, current.GetType().Name)); return null; } } } return current; } } } #endif
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.IO; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace Aurora.Framework { public enum StartupType { Medium = 2, Normal = 3 } public class RegionInfo : AllScopeIDImpl { public string RegionFile = String.Empty; public bool Disabled = false; private RegionSettings m_regionSettings; private int m_objectCapacity = 0; private string m_regionType = String.Empty; protected uint m_httpPort; protected string m_serverURI; protected string m_regionName = String.Empty; protected IPEndPoint m_internalEndPoint; protected int m_regionLocX; protected int m_regionLocY; protected int m_regionLocZ; public UUID RegionID = UUID.Zero; public UUID Password = UUID.Random(); private UUID m_GridSecureSessionID = UUID.Zero; public int NumberStartup = 0; public StartupType Startup = StartupType.Normal; public bool InfiniteRegion = false; public bool NewRegion = false; /// <summary> /// The X length (in meters) that the region is /// The default is 256m /// </summary> public int RegionSizeX = 256; /// <summary> /// The Y length (in meters) that the region is /// The default is 256m /// </summary> public int RegionSizeY = 256; /// <summary> /// The Z height (in meters) that the region is (not supported currently) /// The default is 1024m /// </summary> public int RegionSizeZ = 4096; /// <summary> /// The region flags (as set on the Grid Server in the database), cached on RegisterRegion call /// </summary> public int RegionFlags = -1; public EstateSettings EstateSettings { get; set; } public RegionSettings RegionSettings { get { return m_regionSettings ?? (m_regionSettings = new RegionSettings()); } set { m_regionSettings = value; } } public bool HasBeenDeleted { get; set; } public bool AllowScriptCrossing { get; set; } private List<int> m_UDPPorts = new List<int> (); public List<int> UDPPorts { get { return m_UDPPorts; } set { m_UDPPorts = value; } } public bool TrustBinariesFromForeignSims { get; set; } private bool m_seeIntoThisSimFromNeighbor = true; public bool SeeIntoThisSimFromNeighbor { get { return m_seeIntoThisSimFromNeighbor; } set { m_seeIntoThisSimFromNeighbor = value; } } private bool m_allowPhysicalPrims = true; public RegionInfo() { TrustBinariesFromForeignSims = false; AllowScriptCrossing = false; } public bool AllowPhysicalPrims { get { return m_allowPhysicalPrims; } set { m_allowPhysicalPrims = value; } } public int ObjectCapacity { get { return m_objectCapacity; } set { m_objectCapacity = value; } } public byte AccessLevel { get { return Util.ConvertMaturityToAccessLevel((uint)RegionSettings.Maturity); } set { RegionSettings.Maturity = (int)Util.ConvertAccessLevelToMaturity(value); } } public string RegionType { get { return m_regionType; } set { m_regionType = value; } } public UUID GridSecureSessionID { get { return m_GridSecureSessionID; } set { m_GridSecureSessionID = value; } } public string RegionName { get { return m_regionName; } set { m_regionName = value; } } public IPEndPoint InternalEndPoint { get { return m_internalEndPoint; } set { m_internalEndPoint = value; } } public int RegionLocX { get { return m_regionLocX; } set { m_regionLocX = value; } } public int RegionLocY { get { return m_regionLocY; } set { m_regionLocY = value; } } public int RegionLocZ { get { return m_regionLocZ; } set { m_regionLocZ = value; } } public ulong RegionHandle { get { return Utils.UIntsToLong((uint)RegionLocX, (uint)RegionLocY); } } public void WriteNiniConfig(IConfigSource source) { try { //MUST reload or it will overwrite other changes! source = new IniConfigSource(RegionFile, Nini.Ini.IniFileType.AuroraStyle); } catch (FileNotFoundException) { //If this happens, it is the first time a user has opened Aurora and the RegionFile doesn't exist // yet, so just let it gracefully fail and create itself later return; } CreateIConfig(source); source.Save(); } public void CreateIConfig(IConfigSource source) { IConfig config = source.Configs[RegionName]; if (config != null) source.Configs.Remove(config); config = source.AddConfig(RegionName); config.Set("RegionUUID", RegionID.ToString()); string location = String.Format("{0},{1}", m_regionLocX / 256, m_regionLocY / 256); config.Set("Location", location); config.Set("InternalAddress", m_internalEndPoint.Address.ToString()); config.Set("InternalPort", m_internalEndPoint.Port); if (m_objectCapacity != 0) config.Set("MaxPrims", m_objectCapacity); if (ScopeID != UUID.Zero) config.Set("ScopeID", ScopeID.ToString()); if (RegionType != String.Empty) config.Set("RegionType", RegionType); config.Set("AllowPhysicalPrims", AllowPhysicalPrims); config.Set("AllowScriptCrossing", AllowScriptCrossing); config.Set("TrustBinariesFromForeignSims", TrustBinariesFromForeignSims); config.Set("SeeIntoThisSimFromNeighbor", SeeIntoThisSimFromNeighbor); config.Set("RegionSizeX", RegionSizeX); config.Set ("RegionSizeY", RegionSizeY); config.Set ("RegionSizeZ", RegionSizeZ); config.Set ("StartupType", Startup.ToString()); config.Set("NeighborPassword", Password.ToString()); } public void SaveRegionToFile(string description, string filename) { if (filename.ToLower().EndsWith(".ini")) { IniConfigSource source = new IniConfigSource(); try { source = new IniConfigSource(filename, Nini.Ini.IniFileType.AuroraStyle); // Load if it exists } catch (Exception) { } WriteNiniConfig(source); source.Save(filename); } } public OSDMap PackRegionInfoData() { return PackRegionInfoData(false); } public OSDMap PackRegionInfoData(bool secure) { OSDMap args = new OSDMap(); args["region_id"] = OSD.FromUUID(RegionID); if ((RegionName != null) && !RegionName.Equals("")) args["region_name"] = OSD.FromString(RegionName); args["region_xloc"] = OSD.FromString(RegionLocX.ToString()); args["region_yloc"] = OSD.FromString(RegionLocY.ToString()); args["internal_ep_address"] = OSD.FromString(InternalEndPoint.Address.ToString()); args["internal_ep_port"] = OSD.FromString(InternalEndPoint.Port.ToString()); if (RegionType != String.Empty) args["region_type"] = OSD.FromString(RegionType); args["password"] = OSD.FromUUID(Password); args["region_size_x"] = OSD.FromInteger(RegionSizeX); args["region_size_y"] = OSD.FromInteger(RegionSizeY); args["region_size_z"] = OSD.FromInteger(RegionSizeZ); #if (!ISWIN) OSDArray ports = new OSDArray(UDPPorts.ConvertAll<OSD>(delegate(int a) { return a; })); #else OSDArray ports = new OSDArray(UDPPorts.ConvertAll<OSD>(a => a)); #endif args["UDPPorts"] = ports; args["InfiniteRegion"] = OSD.FromBoolean(InfiniteRegion); if (secure) { args["disabled"] = OSD.FromBoolean(Disabled); args["scope_id"] = OSD.FromUUID(ScopeID); args["all_scope_ids"] = AllScopeIDs.ToOSDArray(); args["object_capacity"] = OSD.FromInteger(m_objectCapacity); args["region_type"] = OSD.FromString(RegionType); args["see_into_this_sim_from_neighbor"] = OSD.FromBoolean(SeeIntoThisSimFromNeighbor); args["trust_binaries_from_foreign_sims"] = OSD.FromBoolean(TrustBinariesFromForeignSims); args["allow_script_crossing"] = OSD.FromBoolean(AllowScriptCrossing); args["allow_physical_prims"] = OSD.FromBoolean (AllowPhysicalPrims); args["startupType"] = OSD.FromInteger((int)Startup); args["RegionSettings"] = RegionSettings.ToOSD(); } return args; } public void UnpackRegionInfoData(OSDMap args) { if (args.ContainsKey("region_id")) RegionID = args["region_id"].AsUUID(); if (args.ContainsKey("region_name")) RegionName = args["region_name"].AsString(); if (args.ContainsKey("http_port")) UInt32.TryParse(args["http_port"].AsString(), out m_httpPort); if (args.ContainsKey("region_xloc")) { int locx; Int32.TryParse(args["region_xloc"].AsString(), out locx); RegionLocX = locx; } if (args.ContainsKey("region_yloc")) { int locy; Int32.TryParse(args["region_yloc"].AsString(), out locy); RegionLocY = locy; } IPAddress ip_addr = null; if (args.ContainsKey("internal_ep_address")) { IPAddress.TryParse(args["internal_ep_address"].AsString(), out ip_addr); } int port = 0; if (args.ContainsKey("internal_ep_port")) { Int32.TryParse(args["internal_ep_port"].AsString(), out port); } InternalEndPoint = new IPEndPoint(ip_addr, port); if (args.ContainsKey("region_type")) m_regionType = args["region_type"].AsString(); if (args.ContainsKey("password")) Password = args["password"].AsUUID(); if (args.ContainsKey("disabled")) Disabled = args["disabled"].AsBoolean(); if (args.ContainsKey("scope_id")) ScopeID = args["scope_id"].AsUUID(); if (args.ContainsKey("all_scope_ids")) AllScopeIDs = ((OSDArray)args["all_scope_ids"]).ConvertAll<UUID>(o => o); if (args.ContainsKey("region_size_x")) RegionSizeX = args["region_size_x"].AsInteger(); if (args.ContainsKey("region_size_y")) RegionSizeY = args["region_size_y"].AsInteger(); if (args.ContainsKey("region_size_z")) RegionSizeZ = args["region_size_z"].AsInteger(); if (args.ContainsKey("object_capacity")) m_objectCapacity = args["object_capacity"].AsInteger(); if (args.ContainsKey("region_type")) RegionType = args["region_type"].AsString(); if (args.ContainsKey("see_into_this_sim_from_neighbor")) SeeIntoThisSimFromNeighbor = args["see_into_this_sim_from_neighbor"].AsBoolean(); if (args.ContainsKey("trust_binaries_from_foreign_sims")) TrustBinariesFromForeignSims = args["trust_binaries_from_foreign_sims"].AsBoolean(); if (args.ContainsKey("allow_script_crossing")) AllowScriptCrossing = args["allow_script_crossing"].AsBoolean(); if (args.ContainsKey("allow_physical_prims")) AllowPhysicalPrims = args["allow_physical_prims"].AsBoolean(); if (args.ContainsKey ("startupType")) Startup = (StartupType)args["startupType"].AsInteger(); if(args.ContainsKey("InfiniteRegion")) InfiniteRegion = args["InfiniteRegion"].AsBoolean(); if (args.ContainsKey("RegionSettings")) { RegionSettings = new RegionSettings(); RegionSettings.FromOSD((OSDMap)args["RegionSettings"]); } if (args.ContainsKey ("UDPPorts")) { OSDArray ports = (OSDArray)args["UDPPorts"]; foreach (OSD p in ports) m_UDPPorts.Add (p.AsInteger ()); } if (!m_UDPPorts.Contains (InternalEndPoint.Port)) m_UDPPorts.Add (InternalEndPoint.Port); } public override void FromOSD(OSDMap map) { UnpackRegionInfoData(map); } public override OSDMap ToOSD() { return PackRegionInfoData(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.Numerics; using System.Text; using Xunit; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void ZeroLengthIndexOf_Byte() { Span<byte> sp = new Span<byte>(Array.Empty<byte>()); int idx = sp.IndexOf(0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOf_Byte() { for (int length = 0; length <= byte.MaxValue; length++) { byte[] a = new byte[length]; Span<byte> span = new Span<byte>(a); for (int i = 0; i < length; i++) { byte target0 = default(byte); int idx = span.IndexOf(target0); Assert.Equal(0, idx); } } } [Fact] public static void TestMatch_Byte() { for (int length = 0; length <= byte.MaxValue; length++) { byte[] a = new byte[length]; for (int i = 0; i < length; i++) { a[i] = (byte)(i + 1); } Span<byte> span = new Span<byte>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { byte target = a[targetIndex]; int idx = span.IndexOf(target); Assert.Equal(targetIndex, idx); } } } [Fact] public static void TestNoMatch_Byte() { var rnd = new Random(42); for (int length = 0; length <= byte.MaxValue; length++) { byte[] a = new byte[length]; byte target = (byte)rnd.Next(0, 256); for (int i = 0; i < length; i++) { byte val = (byte)(i + 1); a[i] = val == target ? (byte)(target + 1) : val; } Span<byte> span = new Span<byte>(a); int idx = span.IndexOf(target); Assert.Equal(-1, idx); } } [Fact] public static void TestAllignmentNoMatch_Byte() { byte[] array = new byte[4 * Vector<byte>.Count]; for (var i = 0; i < Vector<byte>.Count; i++) { var span = new Span<byte>(array, i, 3 * Vector<byte>.Count); int idx = span.IndexOf((byte)'1'); Assert.Equal(-1, idx); span = new Span<byte>(array, i, 3 * Vector<byte>.Count - 3); idx = span.IndexOf((byte)'1'); Assert.Equal(-1, idx); } } [Fact] public static void TestAllignmentMatch_Byte() { byte[] array = new byte[4 * Vector<byte>.Count]; for (int i = 0; i < array.Length; i++) { array[i] = 5; } for (var i = 0; i < Vector<byte>.Count; i++) { var span = new Span<byte>(array, i, 3 * Vector<byte>.Count); int idx = span.IndexOf(5); Assert.Equal(0, idx); span = new Span<byte>(array, i, 3 * Vector<byte>.Count - 3); idx = span.IndexOf(5); Assert.Equal(0, idx); } } [Fact] public static void TestMultipleMatch_Byte() { for (int length = 2; length <= byte.MaxValue; length++) { byte[] a = new byte[length]; for (int i = 0; i < length; i++) { byte val = (byte)(i + 1); a[i] = val == 200 ? (byte)201 : val; } a[length - 1] = 200; a[length - 2] = 200; Span<byte> span = new Span<byte>(a); int idx = span.IndexOf(200); Assert.Equal(length - 2, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRange_Byte() { for (int length = 0; length <= byte.MaxValue; length++) { byte[] a = new byte[length + 2]; a[0] = 99; a[length + 1] = 99; Span<byte> span = new Span<byte>(a, 1, length); int index = span.IndexOf(99); Assert.Equal(-1, index); } } [Theory] [InlineData("a", "a", 'a', 0)] [InlineData("ab", "a", 'a', 0)] [InlineData("aab", "a", 'a', 0)] [InlineData("acab", "a", 'a', 0)] [InlineData("acab", "c", 'c', 1)] [InlineData("abcdefghijklmnopqrstuvwxyz", "lo", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "ol", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "ll", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "rml", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "mlr", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)] [InlineData("aaaaaaaaaaalmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)] [InlineData("aaaaaaaaaaacmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'm', 12)] [InlineData("aaaaaaaaaaarmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'r', 11)] [InlineData("/localhost:5000/PATH/%2FPATH2/ HTTP/1.1", " %?", '%', 21)] [InlineData("/localhost:5000/PATH/%2FPATH2/?key=value HTTP/1.1", " %?", '%', 21)] [InlineData("/localhost:5000/PATH/PATH2/?key=value HTTP/1.1", " %?", '?', 27)] [InlineData("/localhost:5000/PATH/PATH2/ HTTP/1.1", " %?", ' ', 27)] public static void IndexOfAnyStrings_Byte(string raw, string search, char expectResult, int expectIndex) { var buffers = Encoding.UTF8.GetBytes(raw); var span = new Span<byte>(buffers); var searchFor = search.ToCharArray(); var searchForBytes = Encoding.UTF8.GetBytes(searchFor); var index = -1; if (searchFor.Length == 1) { index = span.IndexOf((byte)searchFor[0]); } else if (searchFor.Length == 2) { index = span.IndexOfAny((byte)searchFor[0], (byte)searchFor[1]); } else if (searchFor.Length == 3) { index = span.IndexOfAny((byte)searchFor[0], (byte)searchFor[1], (byte)searchFor[2]); } else { index = span.IndexOfAny(new ReadOnlySpan<byte>(searchForBytes)); } var found = span[index]; Assert.Equal((byte)expectResult, (byte)found); Assert.Equal(expectIndex, index); } [Fact] public static void ZeroLengthIndexOfTwo_Byte() { Span<byte> sp = new Span<byte>(Array.Empty<byte>()); int idx = sp.IndexOfAny(0, 0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfTwo_Byte() { Random rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { byte[] a = new byte[length]; Span<byte> span = new Span<byte>(a); byte[] targets = { default(byte), 99 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 2) == 0 ? 0 : 1; byte target0 = targets[index]; byte target1 = targets[(index + 1) % 2]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchTwo_Byte() { for (int length = 0; length < byte.MaxValue; length++) { byte[] a = new byte[length]; for (int i = 0; i < length; i++) { a[i] = (byte)(i + 1); } Span<byte> span = new Span<byte>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { byte target0 = a[targetIndex]; byte target1 = 0; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { byte target0 = a[targetIndex]; byte target1 = a[targetIndex + 1]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { byte target0 = 0; byte target1 = a[targetIndex + 1]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } } } [Fact] public static void TestNoMatchTwo_Byte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { byte[] a = new byte[length]; byte target0 = (byte)rnd.Next(1, 256); byte target1 = (byte)rnd.Next(1, 256); Span<byte> span = new Span<byte>(a); int idx = span.IndexOfAny(target0, target1); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchTwo_Byte() { for (int length = 3; length < byte.MaxValue; length++) { byte[] a = new byte[length]; for (int i = 0; i < length; i++) { byte val = (byte)(i + 1); a[i] = val == 200 ? (byte)201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; Span<byte> span = new Span<byte>(a); int idx = span.IndexOfAny(200, 200); Assert.Equal(length - 3, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeTwo_Byte() { for (int length = 1; length < byte.MaxValue; length++) { byte[] a = new byte[length + 2]; a[0] = 99; a[length + 1] = 98; Span<byte> span = new Span<byte>(a, 1, length - 1); int index = span.IndexOfAny(99, 98); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { byte[] a = new byte[length + 2]; a[0] = 99; a[length + 1] = 99; Span<byte> span = new Span<byte>(a, 1, length - 1); int index = span.IndexOfAny(99, 99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfThree_Byte() { Span<byte> sp = new Span<byte>(Array.Empty<byte>()); int idx = sp.IndexOfAny(0, 0, 0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfThree_Byte() { Random rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { byte[] a = new byte[length]; Span<byte> span = new Span<byte>(a); byte[] targets = { default(byte), 99, 98 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 3); byte target0 = targets[index]; byte target1 = targets[(index + 1) % 2]; byte target2 = targets[(index + 1) % 3]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchThree_Byte() { for (int length = 0; length < byte.MaxValue; length++) { byte[] a = new byte[length]; for (int i = 0; i < length; i++) { a[i] = (byte)(i + 1); } Span<byte> span = new Span<byte>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { byte target0 = a[targetIndex]; byte target1 = 0; byte target2 = 0; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { byte target0 = a[targetIndex]; byte target1 = a[targetIndex + 1]; byte target2 = a[targetIndex + 2]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { byte target0 = 0; byte target1 = 0; byte target2 = a[targetIndex + 2]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } } } [Fact] public static void TestNoMatchThree_Byte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { byte[] a = new byte[length]; byte target0 = (byte)rnd.Next(1, 256); byte target1 = (byte)rnd.Next(1, 256); byte target2 = (byte)rnd.Next(1, 256); Span<byte> span = new Span<byte>(a); int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchThree_Byte() { for (int length = 4; length < byte.MaxValue; length++) { byte[] a = new byte[length]; for (int i = 0; i < length; i++) { byte val = (byte)(i + 1); a[i] = val == 200 ? (byte)201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; a[length - 4] = 200; Span<byte> span = new Span<byte>(a); int idx = span.IndexOfAny(200, 200, 200); Assert.Equal(length - 4, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeThree_Byte() { for (int length = 1; length < byte.MaxValue; length++) { byte[] a = new byte[length + 2]; a[0] = 99; a[length + 1] = 98; Span<byte> span = new Span<byte>(a, 1, length - 1); int index = span.IndexOfAny(99, 98, 99); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { byte[] a = new byte[length + 2]; a[0] = 99; a[length + 1] = 99; Span<byte> span = new Span<byte>(a, 1, length - 1); int index = span.IndexOfAny(99, 99, 99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfMany_Byte() { Span<byte> sp = new Span<byte>(Array.Empty<byte>()); var values = new ReadOnlySpan<byte>(new byte[] { 0, 0, 0, 0 }); int idx = sp.IndexOfAny(values); Assert.Equal(-1, idx); values = new ReadOnlySpan<byte>(new byte[] { }); idx = sp.IndexOfAny(values); Assert.Equal(0, idx); } [Fact] public static void DefaultFilledIndexOfMany_Byte() { for (int length = 0; length < byte.MaxValue; length++) { byte[] a = new byte[length]; Span<byte> span = new Span<byte>(a); var values = new ReadOnlySpan<byte>(new byte[] { default(byte), 99, 98, 0 }); for (int i = 0; i < length; i++) { int idx = span.IndexOfAny(values); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchMany_Byte() { for (int length = 0; length < byte.MaxValue; length++) { byte[] a = new byte[length]; for (int i = 0; i < length; i++) { a[i] = (byte)(i + 1); } Span<byte> span = new Span<byte>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { var values = new ReadOnlySpan<byte>(new byte[] { a[targetIndex], 0, 0, 0 }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<byte>(new byte[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<byte>(new byte[] { 0, 0, 0, a[targetIndex + 3] }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } } } [Fact] public static void TestMatchValuesLargerMany_Byte() { var rnd = new Random(42); for (int length = 2; length < byte.MaxValue; length++) { byte[] a = new byte[length]; int expectedIndex = length / 2; for (int i = 0; i < length; i++) { if (i == expectedIndex) { continue; } a[i] = 255; } Span<byte> span = new Span<byte>(a); byte[] targets = new byte[length * 2]; for (int i = 0; i < targets.Length; i++) { if (i == length + 1) { continue; } targets[i] = (byte)rnd.Next(1, 255); } var values = new ReadOnlySpan<byte>(targets); int idx = span.IndexOfAny(values); Assert.Equal(expectedIndex, idx); } } [Fact] public static void TestNoMatchMany_Byte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { byte[] a = new byte[length]; byte[] targets = new byte[length]; for (int i = 0; i < targets.Length; i++) { targets[i] = (byte)rnd.Next(1, 256); } Span<byte> span = new Span<byte>(a); var values = new ReadOnlySpan<byte>(targets); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestNoMatchValuesLargerMany_Byte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { byte[] a = new byte[length]; byte[] targets = new byte[length * 2]; for (int i = 0; i < targets.Length; i++) { targets[i] = (byte)rnd.Next(1, 256); } Span<byte> span = new Span<byte>(a); var values = new ReadOnlySpan<byte>(targets); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchMany_Byte() { for (int length = 5; length < byte.MaxValue; length++) { byte[] a = new byte[length]; for (int i = 0; i < length; i++) { byte val = (byte)(i + 1); a[i] = val == 200 ? (byte)201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; a[length - 4] = 200; a[length - 5] = 200; Span<byte> span = new Span<byte>(a); var values = new ReadOnlySpan<byte>(new byte[] { 200, 200, 200, 200, 200, 200, 200, 200, 200 }); int idx = span.IndexOfAny(values); Assert.Equal(length - 5, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeMany_Byte() { for (int length = 1; length < byte.MaxValue; length++) { byte[] a = new byte[length + 2]; a[0] = 99; a[length + 1] = 98; Span<byte> span = new Span<byte>(a, 1, length - 1); var values = new ReadOnlySpan<byte>(new byte[] { 99, 98, 99, 98, 99, 98 }); int index = span.IndexOfAny(values); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { byte[] a = new byte[length + 2]; a[0] = 99; a[length + 1] = 99; Span<byte> span = new Span<byte>(a, 1, length - 1); var values = new ReadOnlySpan<byte>(new byte[] { 99, 99, 99, 99, 99, 99 }); int index = span.IndexOfAny(values); Assert.Equal(-1, index); } } } }
using System; using System.Collections.Generic; using System.Linq; using spreadsheet = DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using Signum.Entities.DynamicQuery; using System.IO; using Signum.Utilities.DataStructures; using Signum.Utilities; using Signum.Entities; using Signum.Entities.Excel; namespace Signum.Engine.Excel { public static class ExcelGenerator { public static byte[] WriteDataInExcelFile(ResultTable queryResult, byte[] template) { using (MemoryStream ms = new MemoryStream()) { ms.WriteAllBytes(template); ms.Seek(0, SeekOrigin.Begin); ExcelGenerator.WriteDataInExcelFile(queryResult, ms); return ms.ToArray(); } } public static void WriteDataInExcelFile(ResultTable results, string fileName) { using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite)) WriteDataInExcelFile(results, fs); } public static void WriteDataInExcelFile(ResultTable results, Stream stream) { if (results == null) throw new ApplicationException(ExcelMessage.ThereAreNoResultsToWrite.NiceToString()); using (SpreadsheetDocument document = SpreadsheetDocument.Open(stream, true)) { document.PackageProperties.Creator = ""; document.PackageProperties.LastModifiedBy = ""; WorkbookPart workbookPart = document.WorkbookPart; if (workbookPart.CalculationChainPart != null) { workbookPart.Workbook.CalculationProperties.ForceFullCalculation = true; workbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true; } WorksheetPart worksheetPart = document.GetWorksheetPartByName(ExcelMessage.Data.NiceToString()); CellBuilder cb = PlainExcelGenerator.CellBuilder; SheetData sheetData = worksheetPart.Worksheet.Descendants<SheetData>().SingleEx(); List<ColumnData> columnEquivalences = GetColumnsEquivalences(document, sheetData, results); UInt32Value headerStyleIndex = worksheetPart.Worksheet.FindCell("A1").StyleIndex; //Clear sheetData from the template sample data sheetData.InnerXml = ""; sheetData.Append(new Sequence<Row>() { (from columnData in columnEquivalences select cb.Cell(columnData.Column.Column.DisplayName, headerStyleIndex)).ToRow(), from r in results.Rows select (from columnData in columnEquivalences select cb.Cell(r[columnData.Column], cb.GetDefaultStyle(columnData.Column.Column.Type), columnData.StyleIndex)).ToRow() }.Cast<OpenXmlElement>()); var pivotTableParts = workbookPart.PivotTableCacheDefinitionParts .Where(ptpart => ptpart.PivotCacheDefinition.Descendants<WorksheetSource>() .Any(wss => wss.Sheet.Value == ExcelMessage.Data.NiceToString())); foreach (PivotTableCacheDefinitionPart ptpart in pivotTableParts) { PivotCacheDefinition pcd = ptpart.PivotCacheDefinition; WorksheetSource wss = pcd.Descendants<WorksheetSource>().FirstEx(); wss.Reference.Value = "A1:" + GetExcelColumn(columnEquivalences.Count(ce => !ce.IsNew) - 1) + (results.Rows.Count() + 1).ToString(); pcd.RefreshOnLoad = true; pcd.SaveData = false; pcd.Save(); } workbookPart.Workbook.Save(); document.Close(); } } private static List<ColumnData> GetColumnsEquivalences(this SpreadsheetDocument document, SheetData sheetData, ResultTable results) { var resultsCols = results.Columns.ToDictionary(c => c.Column.DisplayName!); var headerCells = sheetData.Descendants<Row>().FirstEx().Descendants<Cell>().ToList(); var templateCols = headerCells.ToDictionary(c => document.GetCellValue(c)); var rowDataCellTemplates = sheetData.Descendants<Row>() .FirstEx(r => IsValidRowDataTemplate(r, headerCells)) .Descendants<Cell>().ToList(); var dic = templateCols.OuterJoinDictionaryCC(resultsCols, (name, cell, resultCol) => { if (resultCol == null) throw new ApplicationException(ExcelMessage.TheExcelTemplateHasAColumn0NotPresentInTheFindWindow.NiceToString().FormatWith(name)); if (cell != null) { var styleIndex = rowDataCellTemplates[headerCells.IndexOf(cell)].StyleIndex; return new ColumnData(resultCol!, styleIndex, isNew: false); } else { CellBuilder cb = PlainExcelGenerator.CellBuilder; return new ColumnData(resultCol!, 0, isNew: true); } }); return dic.Values.ToList(); } private static bool IsValidRowDataTemplate(Row row, List<Cell> headerCells) { if (row.RowIndex <= 1) //At least greater than 1 (row 1 must be the header one) return false; var cells = row.Descendants<Cell>().ToList(); if (cells.Count < headerCells.Count) //Must have at least as many cells as the header row to have a template cell for all data columns return false; string headerLastCellReference = headerCells[headerCells.Count - 1].CellReference; string dataCellReference = cells[headerCells.Count - 1].CellReference; //they must be in the same column //If cellReferences of HeaderCell and DataCell differ only in the number they are on the same column var firstDifferentCharacter = headerLastCellReference.Zip(dataCellReference).FirstEx(t => t.Item1 != t.Item2); return int.TryParse(firstDifferentCharacter.Item1.ToString(), out int number); } private static string GetExcelColumn(int columnNumberBase0) { string result = ""; int numAlphabetCharacters = 26; int numAlphabetRounds; numAlphabetRounds = Math.DivRem(columnNumberBase0, numAlphabetCharacters, out int numAlphabetCharacter); if (numAlphabetRounds > 0) result = ((char)('A' + (char)(numAlphabetRounds - 1))).ToString(); result = result + ((char)('A' + (char)numAlphabetCharacter)).ToString(); return result; } public class ColumnData { public ColumnData(ResultColumn column, UInt32Value styleIndex, bool isNew) { Column = column; IsNew = isNew; StyleIndex = styleIndex; } /// <summary> /// Column Data /// </summary> public ResultColumn Column { get; set; } /// <summary> /// Indicates the column is not present in the template excel /// </summary> public bool IsNew { get; set; } /// <summary> /// Style index of the column in the template excel /// </summary> public UInt32Value StyleIndex { get; set; } } static double GetColumnWidth(Type type) { type = type.UnNullify(); if (type == typeof(DateTime)) return 20; if (type == typeof(string)) return 50; if (type.IsLite()) return 50; return 10; } } }
// 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.ComponentModel; using System.Composition; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.Internal.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; using Microsoft.VisualStudio.Settings; using Microsoft.VisualStudio.Shell; using Microsoft.Win32; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ExportLanguageSpecificOptionSerializer( LanguageNames.CSharp, OrganizerOptions.FeatureName, CompletionOptions.FeatureName, CSharpCompletionOptions.FeatureName, CSharpCodeStyleOptions.FeatureName, SimplificationOptions.PerLanguageFeatureName, ExtractMethodOptions.FeatureName, CSharpFormattingOptions.IndentFeatureName, CSharpFormattingOptions.NewLineFormattingFeatureName, CSharpFormattingOptions.SpacingFeatureName, CSharpFormattingOptions.WrappingFeatureName, FormattingOptions.InternalTabFeatureName, FeatureOnOffOptions.OptionName, ServiceFeatureOnOffOptions.OptionName), Shared] internal sealed class CSharpSettingsManagerOptionSerializer : AbstractSettingsManagerOptionSerializer { [ImportingConstructor] public CSharpSettingsManagerOptionSerializer(SVsServiceProvider serviceProvider, IOptionService optionService) : base(serviceProvider, optionService) { } private const string WrappingIgnoreSpacesAroundBinaryOperator = nameof(AutomationObject.Wrapping_IgnoreSpacesAroundBinaryOperators); private const string SpaceAroundBinaryOperator = nameof(AutomationObject.Space_AroundBinaryOperator); private const string UnindentLabels = nameof(AutomationObject.Indent_UnindentLabels); private const string FlushLabelsLeft = nameof(AutomationObject.Indent_FlushLabelsLeft); private KeyValuePair<string, IOption> GetOptionInfoForOnOffOptions(FieldInfo fieldInfo) { var value = (IOption)fieldInfo.GetValue(obj: null); return new KeyValuePair<string, IOption>(GetStorageKeyForOption(value), value); } private bool ShouldIncludeOnOffOption(FieldInfo fieldInfo) { return SupportsOnOffOption((IOption)fieldInfo.GetValue(obj: null)); } protected override ImmutableDictionary<string, IOption> CreateStorageKeyToOptionMap() { var result = ImmutableDictionary.Create<string, IOption>(StringComparer.OrdinalIgnoreCase).ToBuilder(); result.AddRange(new[] { new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.IncludeKeywords), CompletionOptions.IncludeKeywords), new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnTypingLetters), CompletionOptions.TriggerOnTypingLetters), new KeyValuePair<string, IOption>(GetStorageKeyForOption(FormattingOptions.UseTabOnlyForIndentation), FormattingOptions.UseTabOnlyForIndentation) }); Type[] types = new[] { typeof(OrganizerOptions), typeof(CSharpCompletionOptions), typeof(SimplificationOptions), typeof(CSharpCodeStyleOptions), typeof(ExtractMethodOptions), typeof(ServiceFeatureOnOffOptions), typeof(CSharpFormattingOptions) }; var bindingFlags = BindingFlags.Public | BindingFlags.Static; result.AddRange(AbstractSettingsManagerOptionSerializer.GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfo)); types = new[] { typeof(FeatureOnOffOptions) }; result.AddRange(AbstractSettingsManagerOptionSerializer.GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfoForOnOffOptions, this.ShouldIncludeOnOffOption)); return result.ToImmutable(); } protected override string LanguageName { get { return LanguageNames.CSharp; } } protected override string SettingStorageRoot { get { return "TextEditor.CSharp.Specific."; } } protected override bool SupportsOption(IOption option, string languageName) { if (option == OrganizerOptions.PlaceSystemNamespaceFirst || option == OrganizerOptions.WarnOnBuildErrors || option == CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord || option == CSharpCompletionOptions.IncludeSnippets || option.Feature == CSharpCodeStyleOptions.FeatureName || option.Feature == CSharpFormattingOptions.WrappingFeatureName || option.Feature == CSharpFormattingOptions.IndentFeatureName || option.Feature == CSharpFormattingOptions.SpacingFeatureName || option.Feature == CSharpFormattingOptions.NewLineFormattingFeatureName) { return true; } else if (languageName == LanguageNames.CSharp) { if (option == CompletionOptions.IncludeKeywords || option == CompletionOptions.TriggerOnTypingLetters || option.Feature == SimplificationOptions.PerLanguageFeatureName || option.Feature == ExtractMethodOptions.FeatureName || option.Feature == ServiceFeatureOnOffOptions.OptionName || option.Feature == FormattingOptions.InternalTabFeatureName) { return true; } else if (option.Feature == FeatureOnOffOptions.OptionName) { return SupportsOnOffOption(option); } } return false; } private bool SupportsOnOffOption(IOption option) { return option == FeatureOnOffOptions.AutoFormattingOnCloseBrace || option == FeatureOnOffOptions.AutoFormattingOnSemicolon || option == FeatureOnOffOptions.LineSeparator || option == FeatureOnOffOptions.Outlining || option == FeatureOnOffOptions.ReferenceHighlighting || option == FeatureOnOffOptions.KeywordHighlighting || option == FeatureOnOffOptions.FormatOnPaste || option == FeatureOnOffOptions.AutoXmlDocCommentGeneration || option == FeatureOnOffOptions.RefactoringVerification || option == FeatureOnOffOptions.RenameTracking; } public override bool TryFetch(OptionKey optionKey, out object value) { value = null; if (this.Manager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator) { // Remove space -> Space_AroundBinaryOperator = 0 // Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing // Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1 object ignoreSpacesAroundBinaryObjectValue = this.Manager.GetValueOrDefault(WrappingIgnoreSpacesAroundBinaryOperator, defaultValue: 0); if (ignoreSpacesAroundBinaryObjectValue.Equals(1)) { value = BinaryOperatorSpacingOptions.Ignore; return true; } object spaceAroundBinaryOperatorObjectValue = this.Manager.GetValueOrDefault(SpaceAroundBinaryOperator, defaultValue: 1); if (spaceAroundBinaryOperatorObjectValue.Equals(0)) { value = BinaryOperatorSpacingOptions.Remove; return true; } value = BinaryOperatorSpacingOptions.Single; return true; } if (optionKey.Option == CSharpFormattingOptions.LabelPositioning) { object flushLabelLeftObjectValue = this.Manager.GetValueOrDefault(FlushLabelsLeft, defaultValue: 0); if (flushLabelLeftObjectValue.Equals(1)) { value = LabelPositionOptions.LeftMost; return true; } object unindentLabelsObjectValue = this.Manager.GetValueOrDefault(UnindentLabels, defaultValue: 1); if (unindentLabelsObjectValue.Equals(0)) { value = LabelPositionOptions.NoIndent; return true; } value = LabelPositionOptions.OneLess; return true; } return base.TryFetch(optionKey, out value); } public override bool TryPersist(OptionKey optionKey, object value) { if (this.Manager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator) { // Remove space -> Space_AroundBinaryOperator = 0 // Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing // Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1 switch ((BinaryOperatorSpacingOptions)value) { case BinaryOperatorSpacingOptions.Remove: { this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(SpaceAroundBinaryOperator, 0, isMachineLocal: false); return true; } case BinaryOperatorSpacingOptions.Ignore: { this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, 1, isMachineLocal: false); return true; } case BinaryOperatorSpacingOptions.Single: { this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false); return true; } } } else if (optionKey.Option == CSharpFormattingOptions.LabelPositioning) { switch ((LabelPositionOptions)value) { case LabelPositionOptions.LeftMost: { this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(FlushLabelsLeft, 1, isMachineLocal: false); return true; } case LabelPositionOptions.NoIndent: { this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(UnindentLabels, 0, isMachineLocal: false); return true; } case LabelPositionOptions.OneLess: { this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false); return true; } } } return base.TryPersist(optionKey, value); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public class ZLibDeflateStreamTests : DeflateStreamTests, IDisposable { public ZLibDeflateStreamTests() { Common.SetDeflaterMode("zlib"); } public void Dispose() { Common.SetDeflaterMode("unknown"); } } public class ManagedDeflateStreamTests : DeflateStreamTests, IDisposable { public ManagedDeflateStreamTests() { Common.SetDeflaterMode("managed"); } public void Dispose() { Common.SetDeflaterMode("unknown"); } } public abstract class DeflateStreamTests { static string gzTestFile(String fileName) { return Path.Combine("GZTestData", fileName); } [Fact] public void BaseStream1() { var writeStream = new MemoryStream(); var zip = new DeflateStream(writeStream, CompressionMode.Compress); Assert.Same(zip.BaseStream, writeStream); writeStream.Dispose(); } [Fact] public void BaseStream2() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Decompress); Assert.Same(zip.BaseStream, ms); ms.Dispose(); } [Fact] public async Task ModifyBaseStream() { var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz")); var newMs = StripHeaderAndFooter.Strip(ms); var zip = new DeflateStream(newMs, CompressionMode.Decompress); int size = 1024; Byte[] bytes = new Byte[size]; zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected zip.BaseStream.Position = 0; await zip.BaseStream.ReadAsync(bytes, 0, size); } [Fact] public void DecompressCanRead() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Decompress); Assert.True(zip.CanRead); zip.Dispose(); Assert.False(zip.CanRead); } [Fact] public void CompressCanWrite() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); Assert.True(zip.CanWrite); zip.Dispose(); Assert.False(zip.CanWrite); } [Fact] public void CanDisposeBaseStream() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); ms.Dispose(); // This would throw if this was invalid } [Fact] public void CanDisposeDeflateStream() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); zip.Dispose(); // Base Stream should be null after dispose Assert.Null(zip.BaseStream); zip.Dispose(); // Should be a no-op } [Fact] public async Task CanReadBaseStreamAfterDispose() { var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz")); var newMs = StripHeaderAndFooter.Strip(ms); var zip = new DeflateStream(newMs, CompressionMode.Decompress, true); var baseStream = zip.BaseStream; zip.Dispose(); int size = 1024; Byte[] bytes = new Byte[size]; baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected baseStream.Position = 0; await baseStream.ReadAsync(bytes, 0, size); } [Fact] public async Task DecompressWorks() { var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt")); var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz")); await DecompressAsync(compareStream, gzStream); } [Fact] public async Task DecompressWorksWithBinaryFile() { var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc")); var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc.gz")); await DecompressAsync(compareStream, gzStream); } // Making this async since regular read/write are tested below private async Task DecompressAsync(MemoryStream compareStream, MemoryStream gzStream) { var strippedMs = StripHeaderAndFooter.Strip(gzStream); var ms = new MemoryStream(); var zip = new DeflateStream(strippedMs, CompressionMode.Decompress); var deflateStream = new MemoryStream(); int _bufferSize = 1024; var bytes = new Byte[_bufferSize]; bool finished = false; int retCount; while (!finished) { retCount = await zip.ReadAsync(bytes, 0, _bufferSize); if (retCount != 0) await deflateStream.WriteAsync(bytes, 0, retCount); else finished = true; } deflateStream.Position = 0; compareStream.Position = 0; byte[] compareArray = compareStream.ToArray(); byte[] writtenArray = deflateStream.ToArray(); Assert.Equal(compareArray.Length, writtenArray.Length); for (int i = 0; i < compareArray.Length; i++) { Assert.Equal(compareArray[i], writtenArray[i]); } } [Fact] public async Task DecompressFailsWithRealGzStream() { String[] files = { gzTestFile("GZTestDocument.doc.gz"), gzTestFile("GZTestDocument.txt.gz") }; foreach (String fileName in files) { var baseStream = await LocalMemoryStream.readAppFileAsync(fileName); var zip = new DeflateStream(baseStream, CompressionMode.Decompress); int _bufferSize = 2048; var bytes = new Byte[_bufferSize]; Assert.Throws<InvalidDataException>(() => { zip.Read(bytes, 0, _bufferSize); }); zip.Dispose(); } } [Fact] public void DisposedBaseStreamThrows() { var ms = new MemoryStream(); ms.Dispose(); Assert.Throws<ArgumentException>(() => { var deflate = new DeflateStream(ms, CompressionMode.Decompress); }); Assert.Throws<ArgumentException>(() => { var deflate = new DeflateStream(ms, CompressionMode.Compress); }); } [Fact] public void ReadOnlyStreamThrowsOnCompress() { var ms = new LocalMemoryStream(); ms.SetCanWrite(false); Assert.Throws<ArgumentException>(() => { var gzip = new DeflateStream(ms, CompressionMode.Compress); }); } [Fact] public void WriteOnlyStreamThrowsOnDecompress() { var ms = new LocalMemoryStream(); ms.SetCanRead(false); Assert.Throws<ArgumentException>(() => { var gzip = new DeflateStream(ms, CompressionMode.Decompress); }); } [Fact] public void TestCtors() { CompressionLevel[] legalValues = new CompressionLevel[] { CompressionLevel.Optimal, CompressionLevel.Fastest, CompressionLevel.NoCompression }; foreach (CompressionLevel level in legalValues) { bool[] boolValues = new bool[] { true, false }; foreach (bool remainsOpen in boolValues) { TestCtor(level, remainsOpen); } } } [Fact] public void TestLevelOptimial() { TestCtor(CompressionLevel.Optimal); } [Fact] public void TestLevelNoCompression() { TestCtor(CompressionLevel.NoCompression); } [Fact] public void TestLevelFastest() { TestCtor(CompressionLevel.Fastest); } private static void TestCtor(CompressionLevel level, bool? leaveOpen = null) { //Create the DeflateStream int _bufferSize = 1024; var bytes = new Byte[_bufferSize]; var baseStream = new MemoryStream(bytes, true); DeflateStream ds; if (leaveOpen == null) { ds = new DeflateStream(baseStream, level); } else { ds = new DeflateStream(baseStream, level, leaveOpen ?? false); } //Write some data and Close the stream String strData = "Test Data"; var encoding = Encoding.UTF8; Byte[] data = encoding.GetBytes(strData); ds.Write(data, 0, data.Length); ds.Flush(); ds.Dispose(); if (leaveOpen != true) { //Check that Close has really closed the underlying stream Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); }); } //Read the data Byte[] data2 = new Byte[_bufferSize]; baseStream = new MemoryStream(bytes, false); ds = new DeflateStream(baseStream, CompressionMode.Decompress); int size = ds.Read(data2, 0, _bufferSize - 5); //Verify the data roundtripped for (int i = 0; i < size + 5; i++) { if (i < data.Length) { Assert.Equal(data[i], data2[i]); } else { Assert.Equal(data2[i], (byte)0); } } } [Fact] public void CtorArgumentValidation() { Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionLevel.Fastest)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Decompress)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Compress)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionLevel.Fastest, true)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Decompress, false)); Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Compress, true)); Assert.Throws<ArgumentException>(() => new DeflateStream(new MemoryStream(), (CompressionMode)42)); Assert.Throws<ArgumentException>(() => new DeflateStream(new MemoryStream(), (CompressionMode)43, true)); Assert.Throws<ArgumentException>(() => new DeflateStream(new MemoryStream(new byte[1], writable: false), CompressionLevel.Optimal)); } [Fact] public async Task Flush() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Flush(); await ds.FlushAsync(); // Just ensuring Flush doesn't throw } [Fact] public void FlushFailsAfterDispose() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Dispose(); Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); }); } [Fact] public async Task FlushAsyncFailsAfterDispose() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(async () => { await ds.FlushAsync(); }); } [Fact] public void TestSeekMethodsDecompress() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Decompress); Assert.False(zip.CanSeek, "CanSeek should be false"); Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; }); Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; }); Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; }); Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); }); Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); }); } [Fact] public void TestSeekMethodsCompress() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); Assert.False(zip.CanSeek, "CanSeek should be false"); Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; }); Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; }); Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; }); Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); }); Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); }); } [Fact] public void ReadWriteArgumentValidation() { using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress)) { Assert.Throws<ArgumentNullException>(() => ds.Write(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], 0, -1)); Assert.Throws<ArgumentException>(() => ds.Write(new byte[1], 0, 2)); Assert.Throws<ArgumentException>(() => ds.Write(new byte[1], 1, 1)); Assert.Throws<InvalidOperationException>(() => ds.Read(new byte[1], 0, 1)); ds.Write(new byte[1], 0, 0); } using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress)) { Assert.Throws<ArgumentNullException>(() => { ds.WriteAsync(null, 0, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], -1, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], 0, -1); }); Assert.Throws<ArgumentException>(() => { ds.WriteAsync(new byte[1], 0, 2); }); Assert.Throws<ArgumentException>(() => { ds.WriteAsync(new byte[1], 1, 1); }); Assert.Throws<InvalidOperationException>(() => { ds.Read(new byte[1], 0, 1); }); } using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress)) { Assert.Throws<ArgumentNullException>(() => ds.Read(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], 0, -1)); Assert.Throws<ArgumentException>(() => ds.Read(new byte[1], 0, 2)); Assert.Throws<ArgumentException>(() => ds.Read(new byte[1], 1, 1)); Assert.Throws<InvalidOperationException>(() => ds.Write(new byte[1], 0, 1)); var data = new byte[1] { 42 }; Assert.Equal(0, ds.Read(data, 0, 0)); Assert.Equal(42, data[0]); } using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress)) { Assert.Throws<ArgumentNullException>(() => { ds.ReadAsync(null, 0, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], -1, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], 0, -1); }); Assert.Throws<ArgumentException>(() => { ds.ReadAsync(new byte[1], 0, 2); }); Assert.Throws<ArgumentException>(() => { ds.ReadAsync(new byte[1], 1, 1); }); Assert.Throws<InvalidOperationException>(() => { ds.Write(new byte[1], 0, 1); }); } } [Fact] public void Precancellation() { var ms = new MemoryStream(); using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress, leaveOpen: true)) { Assert.True(ds.WriteAsync(new byte[1], 0, 1, new CancellationToken(true)).IsCanceled); Assert.True(ds.FlushAsync(new CancellationToken(true)).IsCanceled); } using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true)) { Assert.True(ds.ReadAsync(new byte[1], 0, 1, new CancellationToken(true)).IsCanceled); } } [Fact] public async Task RoundtripCompressDecompress() { await RoundtripCompressDecompress(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest); await RoundtripCompressDecompress(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal); } [OuterLoop] [Theory] [MemberData("RoundtripCompressDecompressOuterData")] public Task RoundtripCompressDecompressOuter(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level) { return RoundtripCompressDecompress(useAsync, useGzip, chunkSize, totalSize, level); } public static IEnumerable<object[]> RoundtripCompressDecompressOuterData { get { foreach (bool useAsync in new[] { true, false }) // whether to use Read/Write or ReadAsync/WriteAsync { foreach (bool useGzip in new[] { true, false }) // whether to add on gzip headers/footers { foreach (var level in new[] { CompressionLevel.Fastest, CompressionLevel.Optimal, CompressionLevel.NoCompression }) // compression level { yield return new object[] { useAsync, useGzip, 1, 5, level }; // smallest possible writes yield return new object[] { useAsync, useGzip, 1023, 1023*10, level }; // overflowing internal buffer yield return new object[] { useAsync, useGzip, 1024*1024, 1024*1024, level }; // large single write } } } } } private async Task RoundtripCompressDecompress(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level) { byte[] data = new byte[totalSize]; new Random(42).NextBytes(data); var compressed = new MemoryStream(); using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true)) { for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test { switch (useAsync) { case true: await compressor.WriteAsync(data, i, chunkSize); break; case false: compressor.Write(data, i, chunkSize); break; } } } compressed.Position = 0; var decompressed = new MemoryStream(); using (var decompressor = useGzip ? (Stream)new GZipStream(compressed, CompressionMode.Decompress, true) : new DeflateStream(compressed, CompressionMode.Decompress, true)) { if (useAsync) decompressor.CopyTo(decompressed, chunkSize); else await decompressor.CopyToAsync(decompressed, chunkSize, CancellationToken.None); } Assert.Equal<byte>(data, decompressed.ToArray()); } [Fact] public void SequentialReadsOnMemoryStream_Return_SameBytes() { byte[] data = new byte[1024*10]; new Random(42).NextBytes(data); var compressed = new MemoryStream(); using (var compressor = new DeflateStream(compressed, CompressionMode.Compress, true)) { for (int i = 0; i < data.Length; i += 1024) { compressor.Write(data, i, 1024); } } compressed.Position = 0; var decompressed = new MemoryStream(); using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true)) { int i, j; byte[] array = new byte[100]; byte[] array2 = new byte[100]; // only read in the first 100 bytes decompressor.Read(array, 0, array.Length); for (i = 0; i < array.Length; i++) Assert.Equal(data[i], array[i]); // read in the next 100 bytes and make sure nothing is missing decompressor.Read(array2, 0, array2.Length); for (j = 0; j < array2.Length; j++) Assert.Equal(data[j], array[j]); } } [Fact] public async Task WrapNullReturningTasksStream() { using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnNullTasks), CompressionMode.Decompress)) await Assert.ThrowsAsync<InvalidOperationException>(() => ds.ReadAsync(new byte[1024], 0, 1024)); } [Fact] public async Task WrapStreamReturningBadReadValues() { using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress)) Assert.Throws<InvalidDataException>(() => ds.Read(new byte[1024], 0, 1024)); using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress)) await Assert.ThrowsAsync<InvalidDataException>(() => ds.ReadAsync(new byte[1024], 0, 1024)); using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress)) Assert.Equal(0, ds.Read(new byte[1024], 0, 1024)); using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress)) Assert.Equal(0, await ds.ReadAsync(new byte[1024], 0, 1024)); } private sealed class BadWrappedStream : Stream { public enum Mode { Default, ReturnNullTasks, ReturnTooSmallCounts, ReturnTooLargeCounts, } private readonly Mode _mode; public BadWrappedStream(Mode mode) { _mode = mode; } public override int Read(byte[] buffer, int offset, int count) { switch (_mode) { case Mode.ReturnTooSmallCounts: return -1; case Mode.ReturnTooLargeCounts: return buffer.Length + 1; default: return 0; } } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _mode == Mode.ReturnNullTasks ? null : base.ReadAsync(buffer, offset, count, cancellationToken); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _mode == Mode.ReturnNullTasks ? null : base.WriteAsync(buffer, offset, count, cancellationToken); } public override void Write(byte[] buffer, int offset, int count) { } public override void Flush() { } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } } }
// // NamedPermissionSetTest.cs - NUnit Test Cases for NamedPermissionSet // // Author: // Sebastien Pouliot <[email protected]> // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Security; using System.Security.Permissions; namespace MonoTests.System.Security { [TestFixture] public class NamedPermissionSetTest : Assertion { private static string name = "mono"; private static string sentinel = "go mono!"; [Test] [ExpectedException (typeof (ArgumentException))] public void ConstructorNameNull () { string s = null; // we don't want to confuse the compiler NamedPermissionSet nps = new NamedPermissionSet (s); } [Test] [ExpectedException (typeof (ArgumentException))] public void ConstructorNameEmpty () { NamedPermissionSet nps = new NamedPermissionSet (""); } [Test] public void Description () { NamedPermissionSet nps = new NamedPermissionSet (name); // null by default (not empty) AssertNull ("Description", nps.Description); // is null-able (without exception) nps.Description = null; AssertNull ("Description(null)", nps.Description); nps.Description = sentinel; AssertEquals ("Description", sentinel, nps.Description); } [Test] [ExpectedException (typeof (ArgumentException))] public void NameNull () { NamedPermissionSet nps = new NamedPermissionSet (name); nps.Name = null; // strangely this isn't a ArgumentNullException (but so says the doc) } [Test] [ExpectedException (typeof (ArgumentException))] public void NameEmpty () { NamedPermissionSet nps = new NamedPermissionSet (name); nps.Name = ""; } [Test] public void Name () { NamedPermissionSet nps = new NamedPermissionSet (name); nps.Name = sentinel; AssertEquals ("Name", sentinel, nps.Name); } [Test] public void Copy () { NamedPermissionSet nps = new NamedPermissionSet (name); nps.Description = sentinel; nps.AddPermission (new SecurityPermission (SecurityPermissionFlag.Assertion)); NamedPermissionSet copy = (NamedPermissionSet)nps.Copy (); AssertEquals ("Name", nps.Name, copy.Name); AssertEquals ("Description", nps.Description, copy.Description); AssertEquals ("Count", nps.Count, copy.Count); } [Test] public void Copy_Name () { NamedPermissionSet nps = new NamedPermissionSet (name); nps.Description = sentinel; nps.AddPermission (new SecurityPermission (SecurityPermissionFlag.Assertion)); NamedPermissionSet copy = (NamedPermissionSet)nps.Copy ("Copy"); AssertEquals ("Name", "Copy", copy.Name); AssertEquals ("Description", nps.Description, copy.Description); AssertEquals ("Count", nps.Count, copy.Count); } [Test] [ExpectedException (typeof (ArgumentException))] public void Copy_Name_Null () { NamedPermissionSet nps = new NamedPermissionSet (name); NamedPermissionSet copy = (NamedPermissionSet)nps.Copy (null); } [Test] [ExpectedException (typeof (ArgumentException))] public void Copy_Name_Empty () { NamedPermissionSet nps = new NamedPermissionSet (name); NamedPermissionSet copy = (NamedPermissionSet)nps.Copy (String.Empty); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void FromXml_Null () { NamedPermissionSet nps = new NamedPermissionSet (name, PermissionState.None); nps.FromXml (null); } [Test] [ExpectedException (typeof (ArgumentException))] public void FromXml_InvalidPermission () { NamedPermissionSet nps = new NamedPermissionSet (name, PermissionState.None); SecurityElement se = nps.ToXml (); // can't modify - so we create our own SecurityElement se2 = new SecurityElement ("InvalidPermissionSet", se.Text); se2.AddAttribute ("class", se.Attribute ("class")); se2.AddAttribute ("version", se.Attribute ("version")); se2.AddAttribute ("Name", se.Attribute ("Name")); nps.FromXml (se2); } [Test] [ExpectedException (typeof (ArgumentException))] public void FromXml_WrongTagCase () { NamedPermissionSet nps = new NamedPermissionSet (name, PermissionState.None); SecurityElement se = nps.ToXml (); se.Tag = se.Tag.ToUpper (); // instead of PermissionSet nps.FromXml (se); } [Test] public void FromXml_WrongClass () { NamedPermissionSet nps = new NamedPermissionSet (name, PermissionState.None); SecurityElement se = nps.ToXml (); SecurityElement w = new SecurityElement (se.Tag); w.AddAttribute ("class", "Wrong" + se.Attribute ("class")); w.AddAttribute ("version", se.Attribute ("version")); w.AddAttribute ("Name", se.Attribute ("Name")); nps.FromXml (w); // doesn't care of the class name at that stage // anyway the class has already be created so... } [Test] public void FromXml_NoClass () { NamedPermissionSet nps = new NamedPermissionSet (name, PermissionState.None); SecurityElement se = nps.ToXml (); SecurityElement w = new SecurityElement (se.Tag); w.AddAttribute ("version", se.Attribute ("version")); nps.FromXml (w); // doesn't even care of the class attribute presence } [Test] // [ExpectedException (typeof (ArgumentException))] public void FromXml_WrongVersion () { NamedPermissionSet nps = new NamedPermissionSet (name, PermissionState.None); SecurityElement se = nps.ToXml (); // can't modify - so we create our own SecurityElement se2 = new SecurityElement (se.Tag, se.Text); se2.AddAttribute ("class", se.Attribute ("class")); se2.AddAttribute ("version", "2"); se2.AddAttribute ("Name", se.Attribute ("Name")); nps.FromXml (se2); // wow - here we accept a version 2 !!! } [Test] public void FromXml_NoVersion () { NamedPermissionSet nps = new NamedPermissionSet (name, PermissionState.None); SecurityElement se = nps.ToXml (); SecurityElement w = new SecurityElement (se.Tag); w.AddAttribute ("class", se.Attribute ("class")); w.AddAttribute ("Name", se.Attribute ("Name")); nps.FromXml (w); } [Test] public void FromXml_NoName () { NamedPermissionSet nps = new NamedPermissionSet (name, PermissionState.None); SecurityElement se = nps.ToXml (); SecurityElement w = new SecurityElement (se.Tag); w.AddAttribute ("class", se.Attribute ("class")); w.AddAttribute ("version", "1"); nps.FromXml (w); // having a null name can badly influence the rest of the class code AssertNull ("Name", nps.Name); NamedPermissionSet copy = (NamedPermissionSet) nps.Copy (); AssertNull ("Copy.Name", copy.Name); copy = nps.Copy ("name"); AssertEquals ("Copy(Name).Name", "name", copy.Name); se = nps.ToXml (); AssertNull ("Name attribute", se.Attribute ("Name")); #if NET_2_0 AssertEquals ("GetHashCode", 0, nps.GetHashCode ()); Assert ("Equals-self", nps.Equals (nps)); #endif } [Test] public void FromXml () { NamedPermissionSet nps = new NamedPermissionSet (name, PermissionState.None); SecurityElement se = nps.ToXml (); AssertNotNull ("ToXml()", se); NamedPermissionSet nps2 = (NamedPermissionSet) nps.Copy (); nps2.FromXml (se); AssertEquals ("FromXml-Copy.Name", name, nps2.Name); // strangely it's empty when converted from XML (but null when created) AssertEquals ("FromXml-Copy.Description", "", nps2.Description); Assert ("FromXml-Copy.IsUnrestricted", !nps2.IsUnrestricted ()); se.AddAttribute ("Description", sentinel); nps2.FromXml (se); AssertEquals ("FromXml-Add1.Name", name, nps2.Name); AssertEquals ("FromXml-Add1.Description", sentinel, nps2.Description); Assert ("FromXml-Add1.IsUnrestricted", !nps2.IsUnrestricted ()); se.AddAttribute ("Unrestricted", "true"); nps2.FromXml (se); AssertEquals ("FromXml-Add2.Name", name, nps2.Name); AssertEquals ("FromXml-Add2.Description", sentinel, nps2.Description); Assert ("FromXml-Add2.IsUnrestricted", nps2.IsUnrestricted ()); } [Test] public void ToXml_None () { NamedPermissionSet ps = new NamedPermissionSet (name, PermissionState.None); ps.Description = sentinel; SecurityElement se = ps.ToXml (); Assert ("None.ToString().StartsWith", ps.ToString().StartsWith ("<PermissionSet")); AssertEquals ("None.class", "System.Security.NamedPermissionSet", (se.Attributes ["class"] as string)); AssertEquals ("None.version", "1", (se.Attributes ["version"] as string)); AssertEquals ("None.Name", name, (se.Attributes ["Name"] as string)); AssertEquals ("None.Description", sentinel, (se.Attributes ["Description"] as string)); AssertNull ("None.Unrestricted", (se.Attributes ["Unrestricted"] as string)); } [Test] public void ToXml_Unrestricted () { NamedPermissionSet ps = new NamedPermissionSet (name, PermissionState.Unrestricted); SecurityElement se = ps.ToXml (); Assert ("Unrestricted.ToString().StartsWith", ps.ToString().StartsWith ("<PermissionSet")); AssertEquals ("Unrestricted.class", "System.Security.NamedPermissionSet", (se.Attributes ["class"] as string)); AssertEquals ("Unrestricted.version", "1", (se.Attributes ["version"] as string)); AssertEquals ("Unrestricted.Name", name, (se.Attributes ["Name"] as string)); AssertNull ("Unrestricted.Description", (se.Attributes ["Description"] as string)); AssertEquals ("Unrestricted.Unrestricted", "true", (se.Attributes ["Unrestricted"] as string)); } #if NET_2_0 [Test] public void Equals () { NamedPermissionSet psn = new NamedPermissionSet (name, PermissionState.None); NamedPermissionSet psu = new NamedPermissionSet (name, PermissionState.Unrestricted); Assert ("psn!=psu", !psn.Equals (psu)); Assert ("psu!=psn", !psu.Equals (psn)); NamedPermissionSet cpsn = (NamedPermissionSet) psn.Copy (); Assert ("cpsn==psn", cpsn.Equals (psn)); Assert ("psn==cpsn", psn.Equals (cpsn)); NamedPermissionSet cpsu = (NamedPermissionSet) psu.Copy (); Assert ("cpsu==psu", cpsu.Equals (psu)); Assert ("psu==cpsu", psu.Equals (cpsu)); cpsn.Description = sentinel; Assert ("cpsn+desc==psn", cpsn.Equals (psn)); Assert ("psn==cpsn+desc", psn.Equals (cpsn)); cpsn.Description = sentinel; Assert ("cpsu+desc==psu", cpsu.Equals (psu)); Assert ("psu==cpsu+desc", psu.Equals (cpsu)); } [Test] public void GetHashCode_ () { NamedPermissionSet psn = new NamedPermissionSet (name, PermissionState.None); int nhc = psn.GetHashCode (); NamedPermissionSet psu = new NamedPermissionSet (name, PermissionState.Unrestricted); int uhc = psu.GetHashCode (); Assert ("GetHashCode-1", nhc != uhc); psn.Description = sentinel; Assert ("GetHashCode-2", psn.GetHashCode () == nhc); psu.Description = sentinel; Assert ("GetHashCode-3", psu.GetHashCode () == uhc); } #endif } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Collections.Specialized; using Sensus.Concurrent; using Sensus.Extensions; using Sensus.UI.UiProperties; using Sensus.Probes.Location; using Sensus.Context; using Sensus.Callbacks; using Newtonsoft.Json; using Sensus.UI.Inputs; using Plugin.Permissions.Abstractions; using Plugin.Geolocator.Abstractions; using System.ComponentModel; namespace Sensus.Probes.User.Scripts { public class ScriptRunner : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; #region Fields private string _name; private bool _enabled; private readonly Dictionary<Trigger, EventHandler<Tuple<Datum, Datum>>> _triggerHandlers; private TimeSpan? _maxAge; private DateTime? _maxScheduledDate; private readonly List<ScheduledCallback> _scriptRunCallbacks; private readonly ScheduleTrigger _scheduleTrigger; private readonly object _locker = new object(); #endregion #region Properties public ScriptProbe Probe { get; set; } public Script Script { get; set; } /// <summary> /// Name of the survey. If you would like to use the value of a /// survey-triggering <see cref="Script.CurrentDatum"/> within the survey's name, you can do so /// by placing a <c>{0}</c> within <see cref="Name"/> as a placeholder. The placeholder will be replaced with /// the value of the triggering <see cref="Datum"/> at runtime. You can read more about the format of the /// placeholder [here](https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx). /// </summary> /// <value>The name.</value> [EntryStringUiProperty("Name:", true, 1)] public string Name { get { return _name; } set { if(value != _name) { _name = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Caption))); } } } /// <summary> /// Whether or not the survey is enabled. /// </summary> /// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value> [OnOffUiProperty("Enabled:", true, 2)] public bool Enabled { get { return _enabled; } set { if (value != _enabled) { _enabled = value; if (Probe != null && Probe.Running && _enabled) // probe can be null when deserializing, if set after this property. { Start(); } else if (SensusServiceHelper.Get() != null) // service helper is null when deserializing { Stop(); } } } } /// <summary> /// Whether or not the user should be allowed to cancel the survey after starting it. /// </summary> /// <value><c>true</c> if allow cancel; otherwise, <c>false</c>.</value> [OnOffUiProperty("Allow Cancel:", true, 3)] public bool AllowCancel { get; set; } public ConcurrentObservableCollection<Trigger> Triggers { get; } /// <summary> /// The maximum number of minutes, following delivery to the user, that this survey should remain available for completion. /// </summary> /// <value>The max age minutes.</value> [EntryDoubleUiProperty("Maximum Age (Mins.):", true, 7)] public double? MaxAgeMinutes { get { return _maxAge?.TotalMinutes; } set { _maxAge = value == null ? default(TimeSpan?) : TimeSpan.FromMinutes(value.Value <= 0 ? 10 : value.Value); } } /// <summary> /// Whether or not the survey should be removed from availability when the survey's window ends. See <see cref="TriggerWindowsString"/> for more information. /// </summary> /// <value><c>true</c> if window expiration should be used; otherwise, <c>false</c>.</value> [OnOffUiProperty("Expire Script When Window Ends:", true, 15)] public bool WindowExpiration { get { return _scheduleTrigger.WindowExpiration; } set { _scheduleTrigger.WindowExpiration = value; } } /// <summary> /// /// A comma-separated list of times at (in the case of exact times) or during (in the case of time windows) which the survey should /// be delievered. For example, if you want the survey to be delivered twice per day, once randomly between 9am-10am (e.g., 9:32am) /// and once randomly between 1pm-2pm (e.g., 1:56pm), then you would enter the following into this field: /// /// 9:00-10:00,13:00-14:00 /// /// Note that the survey will be deployed at a random time during each future window (e.g., 9:32am and 1:56pm on day 1, 9:57am and /// 1:28pm on day 2, etc.). Alternatively, you may specify an exact time as follows: /// /// 9:00-10:00,11:32,13:00-14:00 /// /// The survey thus configured will also fire exactly at 11:32am each day. See <see cref="NonDowTriggerIntervalDays"/> /// for how to put additional days between each survey. /// /// If you want the survey to be fired on particular days of the week, you can prepend the day of week ("Su", "Mo", "Tu", "We", "Th", /// "Fr", "Sa") to the time as follows: /// /// 9:00-10:00,Su-11:32,13:00-14:00 /// /// In contrast to the previous example, this one would would only fire at 11:32am on Sundays. /// /// </summary> /// <value>The trigger windows string.</value> [EntryStringUiProperty("Trigger Windows:", true, 8)] public string TriggerWindowsString { get { return _scheduleTrigger.WindowsString; } set { _scheduleTrigger.WindowsString = value; } } /// <summary> /// For surveys that are not associated with a specific day of the week, this field indicates how /// many days to should pass between subsequent surveys. For example, if this is set to 1 and /// <see cref="TriggerWindowsString"/> is set to `9:00-10:00`, then the survey would be fired each /// day at some time between 9am and 10am. If this field were set to 2, then the survey would be /// fired every other day at some time between 9am and 10am. /// </summary> /// <value>The non-DOW trigger interval days.</value> [EntryIntegerUiProperty("Non-DOW Trigger Interval (Days):", true, 9)] public int NonDowTriggerIntervalDays { get { return _scheduleTrigger.NonDowTriggerIntervalDays; } set { if (value < 1) { value = 1; } _scheduleTrigger.NonDowTriggerIntervalDays = value; } } [JsonIgnore] public string ScheduleTriggerReadableDescription { get { string description = _scheduleTrigger.ReadableDescription; if (!string.IsNullOrWhiteSpace(description)) { description = char.ToUpper(description[0]) + (description.Length > 1 ? description.Substring(1) : ""); } return description; } } public List<DateTime> RunTimes { get; set; } public List<DateTime> CompletionTimes { get; set; } /// <summary> /// Whether or not to run the survey exactly once. /// </summary> /// <value><c>true</c> if one shot; otherwise, <c>false</c>.</value> [OnOffUiProperty("One Shot:", true, 10)] public bool OneShot { get; set; } /// <summary> /// Whether or not to run the survey immediately upon starting the <see cref="Protocol"/>. /// </summary> /// <value><c>true</c> if run on start; otherwise, <c>false</c>.</value> [OnOffUiProperty("Run On Start:", true, 11)] public bool RunOnStart { get; set; } /// <summary> /// Whether or not to display progress (% complete) to the user when they are working on the survey. /// </summary> /// <value><c>true</c> if display progress; otherwise, <c>false</c>.</value> [OnOffUiProperty("Display Progress:", true, 13)] public bool DisplayProgress { get; set; } /// <summary> /// How to handle multiple instances of the survey. Options are <see cref="RunMode.Multiple"/>, /// <see cref="RunMode.SingleKeepNewest"/>, and <see cref="RunMode.SingleKeepOldest"/>. /// </summary> /// <value>The run mode.</value> [ListUiProperty("Run Mode:", true, 14, new object[] { RunMode.Multiple, RunMode.SingleKeepNewest, RunMode.SingleKeepOldest })] public RunMode RunMode { get; set; } /// <summary> /// The message to display to the user if a required field is invalid. /// </summary> /// <value>The incomplete submission confirmation.</value> [EntryStringUiProperty("Incomplete Submission Confirmation:", true, 15)] public string IncompleteSubmissionConfirmation { get; set; } /// <summary> /// Whether or not to shuffle the order of the survey's input groups prior to displaying them to the user. /// </summary> /// <value><c>true</c> if shuffle input groups; otherwise, <c>false</c>.</value> [OnOffUiProperty("Shuffle Input Groups:", true, 16)] public bool ShuffleInputGroups { get; set; } /// <summary> /// Whether or not to use the triggering <see cref="Datum.Timestamp"/> within the subcaption text /// displayed for surveys deployed by this <see cref="ScriptRunner"/>. This is important in scenarios /// where <see cref="Script.Birthdate"/> differs from <see cref="Datum.Timestamp"/> (e.g., as is the /// case in iOS where readings collected by the activity probe lag by several minutes). /// </summary> /// <value><c>true</c> if use trigger datum timestamp in subcaption; otherwise, <c>false</c>.</value> [OnOffUiProperty("Use Trigger Timestamp In Subcaption:", true, 17)] public bool UseTriggerDatumTimestampInSubcaption { get; set; } [JsonIgnore] public string Caption { get { return _name; } } #endregion #region Constructor private ScriptRunner() { _scheduleTrigger = new ScheduleTrigger(); //this needs to be above _enabled = false; _maxAge = null; _triggerHandlers = new Dictionary<Trigger, EventHandler<Tuple<Datum, Datum>>>(); _scriptRunCallbacks = new List<ScheduledCallback>(); Script = new Script(this); Triggers = new ConcurrentObservableCollection<Trigger>(new LockConcurrent()); RunTimes = new List<DateTime>(); CompletionTimes = new List<DateTime>(); AllowCancel = true; OneShot = false; RunOnStart = false; DisplayProgress = true; RunMode = RunMode.SingleKeepNewest; IncompleteSubmissionConfirmation = "You have not completed all required fields. Do you want to continue?"; ShuffleInputGroups = false; Triggers.CollectionChanged += (o, e) => { if (e.Action == NotifyCollectionChangedAction.Add) { foreach (Trigger trigger in e.NewItems) { // ignore duplicate triggers -- the user should delete and re-add them instead. if (_triggerHandlers.ContainsKey(trigger)) { return; } // create a handler to be called each time the triggering probe stores a datum EventHandler<Tuple<Datum, Datum>> handler = async (oo, previousCurrentDatum) => { // must be running and must have a current datum lock (_locker) { if (!Probe.Running || !_enabled || previousCurrentDatum.Item2 == null) { trigger.FireValueConditionMetOnPreviousCall = false; // this covers the case when the current datum is null. for some probes, the null datum is meaningful and is emitted in order for their state to be tracked appropriately (e.g., POI probe). return; } } Datum previousDatum = previousCurrentDatum.Item1; Datum currentDatum = previousCurrentDatum.Item2; // get the value that might trigger the script -- it might be null in the case where the property is nullable and is not set (e.g., facebook fields, input locations, etc.) object currentDatumValue = trigger.DatumProperty.GetValue(currentDatum); if (currentDatumValue == null) { return; } // if we're triggering based on datum value changes/differences instead of absolute values, calculate the change now. if (trigger.Change) { // don't need to set ConditionSatisfiedLastTime = false here, since it cannot be the case that it's true and prevDatum == null (we must have had a currDatum last time in order to set ConditionSatisfiedLastTime = true). if (previousDatum == null) { return; } try { currentDatumValue = Convert.ToDouble(currentDatumValue) - Convert.ToDouble(trigger.DatumProperty.GetValue(previousDatum)); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Trigger error: Failed to convert datum values to doubles for change calculation: " + ex.Message, LoggingLevel.Normal, GetType()); return; } } // run the script if the current datum's value satisfies the trigger if (trigger.FireFor(currentDatumValue)) { await RunAsync(previousDatum, currentDatum); } }; trigger.Probe.MostRecentDatumChanged += handler; _triggerHandlers.Add(trigger, handler); } } else if (e.Action == NotifyCollectionChangedAction.Remove) { foreach (Trigger trigger in e.OldItems) { if (_triggerHandlers.ContainsKey(trigger)) { trigger.Probe.MostRecentDatumChanged -= _triggerHandlers[trigger]; _triggerHandlers.Remove(trigger); } } } }; } public ScriptRunner(string name, ScriptProbe probe) : this() { Name = name; Probe = probe; } #endregion #region Public Methods public void Initialize() { foreach (var trigger in Triggers) { trigger.Reset(); } // ensure all variables defined by inputs are listed on the protocol List<string> unknownVariables = Script.InputGroups.SelectMany(inputGroup => inputGroup.Inputs) .OfType<IVariableDefiningInput>() .Where(input => !string.IsNullOrWhiteSpace(input.DefinedVariable)) .Select(input => input.DefinedVariable) .Where(definedVariable => !Probe.Protocol.VariableValue.ContainsKey(definedVariable)) .ToList(); if (unknownVariables.Count > 0) { throw new Exception("The following input-defined variables are not listed on the protocol: " + string.Join(", ", unknownVariables)); } if (Script.InputGroups.Any(inputGroup => inputGroup.Geotag)) { SensusServiceHelper.Get().ObtainPermission(Permission.Location); } } public void Start() { Task.Run(() => { UnscheduleCallbacks(); ScheduleScriptRuns(); }); // use the async version below for a couple reasons. first, we're in a non-async method and we want to ensure // that the script won't be running on the UI thread. second, from the caller's perspective the prompt should // not need to finish running in order for the runner to be considered started. if (RunOnStart) { RunAsync(); } } public void Reset() { UnscheduleCallbacks(); RunTimes.Clear(); CompletionTimes.Clear(); } public void Restart() { Stop(); Start(); } public void Stop() { UnscheduleCallbacks(); SensusServiceHelper.Get().RemoveScriptRunner(this); } #endregion #region Private Methods private void ScheduleScriptRuns() { if (_scheduleTrigger.WindowCount == 0 || SensusServiceHelper.Get() == null || Probe == null || !Probe.Protocol.Running || !_enabled) { return; } // get trigger times with respect to the current time occurring after the maximum previously scheduled trigger time. foreach (ScriptTriggerTime triggerTime in _scheduleTrigger.GetTriggerTimes(DateTime.Now, _maxScheduledDate.Max(DateTime.Now), _maxAge)) { // don't schedule scripts past the end of the protocol if there's a scheduled end date. if (!Probe.Protocol.ContinueIndefinitely && triggerTime.Trigger > Probe.Protocol.EndDate) { break; } // we should always allow at least one future script to be scheduled. this is why the _scheduledCallbackIds collection // is a member of the current instance and not global within the script probe. beyond this single scheduled script, // only allow a maximum of 32 script-run callbacks to be scheduled. android's limit is 500, and ios 9 has a limit of 64. // not sure about ios 10+. as long as we have just a few script runners, each one will be able to schedule a few future // script runs. this will help mitigate the problem of users ignoring surveys and losing touch with the study. lock (_scriptRunCallbacks) { if (_scriptRunCallbacks.Count > 32 / Probe.ScriptRunners.Count) { break; } } ScheduleScriptRun(triggerTime); } } private void ScheduleScriptRun(ScriptTriggerTime triggerTime) { // don't bother with the script if it's coming too soon. if (triggerTime.ReferenceTillTrigger.TotalMinutes <= 1) { return; } ScheduledCallback callback = CreateScriptRunCallback(triggerTime); // there is a race condition, so far only seen in ios, in which multiple script runner notifications // accumulate and are executed concurrently when the user opens the app. when these script runners // execute they add their scripts to the pending scripts collection and concurrently attempt to // schedule all future scripts. because two such attempts are made concurrently, they may race to // schedule the same future script. each script callback id is functional in the sense that it is // a string denoting the script to run and the time window to run within. thus, the callback ids can // duplicate. the callback scheduler checks for such duplicate ids and will return unscheduled on the next // line when a duplicate is detected. in the case of a duplicate we can simply abort scheduling the // script run since it was already scheduled. this issue is much less common in android because all // scripts are run immediately in the background, producing little opportunity for the race condition. if (SensusContext.Current.CallbackScheduler.ScheduleCallback(callback) == ScheduledCallbackState.Scheduled) { lock (_scriptRunCallbacks) { _scriptRunCallbacks.Add(callback); } SensusServiceHelper.Get().Logger.Log($"Scheduled for {triggerTime.Trigger} ({callback.Id})", LoggingLevel.Normal, GetType()); _maxScheduledDate = _maxScheduledDate.Max(triggerTime.Trigger); } } private ScheduledCallback CreateScriptRunCallback(ScriptTriggerTime triggerTime) { Script scriptToRun = Script.Copy(true); scriptToRun.ExpirationDate = triggerTime.Expiration; scriptToRun.ScheduledRunTime = triggerTime.Trigger; ScheduledCallback callback = new ScheduledCallback((callbackId, cancellationToken, letDeviceSleepCallback) => { return Task.Run(() => { SensusServiceHelper.Get().Logger.Log($"Running script on callback ({callbackId})", LoggingLevel.Normal, GetType()); if (!Probe.Running || !_enabled) { return; } Run(scriptToRun); lock (_scriptRunCallbacks) { _scriptRunCallbacks.RemoveAll(c => c.Id == callbackId); } // on android, the callback alarm has fired and the script has been run. on ios, the notification has been // delivered (1) either to the app in the foreground or (2) to the notification tray where the user has opened // it -- either way on ios the app is in the foreground and the script has been run. now is a good time to update // the scheduled callbacks to run this script. ScheduleScriptRuns(); }, cancellationToken); // Be careful to use Script.Id rather than script.Id for the callback domain. Using the former means that callbacks are tied to the script runner and not the script copies (the latter) that we will be running. The latter would always be unique. }, triggerTime.ReferenceTillTrigger, GetType().FullName + "-" + ((long)(triggerTime.Trigger - DateTime.MinValue).TotalDays) + "-" + triggerTime.Window, Script.Id, Probe.Protocol); #if __IOS__ // all scheduled scripts with an expiration should show an expiration date to the user. on iOS this will be the only notification for // scheduled surveys, since we don't have a way to update the "you have X pending surveys" notification (generated by triggered // surveys) without executing code in the background. if (scriptToRun.ExpirationDate.HasValue) { callback.UserNotificationMessage = "Survey expires on " + scriptToRun.ExpirationDate.Value.ToShortDateString() + " at " + scriptToRun.ExpirationDate.Value.ToShortTimeString() + "."; } // on iOS, even if we don't have an expiration date we should show some additional notification, again because we don't have a way // to update the "you have X pending surveys" notification from the background. else { callback.UserNotificationMessage = "Please open to take survey."; } callback.DisplayPage = DisplayPage.PendingSurveys; #endif return callback; } private void UnscheduleCallbacks() { lock (_scriptRunCallbacks) { if (_scriptRunCallbacks.Count == 0 || SensusServiceHelper.Get() == null) { return; } foreach (ScheduledCallback callback in _scriptRunCallbacks) { SensusContext.Current.CallbackScheduler.UnscheduleCallback(callback); } _scriptRunCallbacks.Clear(); _maxScheduledDate = null; } } private Task RunAsync(Datum previousDatum = null, Datum currentDatum = null) { return Task.Run(() => { Run(Script.Copy(true), previousDatum, currentDatum); }); } /// <summary> /// Run the specified script. /// </summary> /// <param name="script">Script.</param> /// <param name="previousDatum">Previous datum.</param> /// <param name="currentDatum">Current datum.</param> private void Run(Script script, Datum previousDatum = null, Datum currentDatum = null) { SensusServiceHelper.Get().Logger.Log($"Running \"{Name}\".", LoggingLevel.Normal, GetType()); script.RunTime = DateTimeOffset.UtcNow; // scheduled scripts have their expiration dates set when they're scheduled. scripts triggered by other probes // as well as on-start scripts will not yet have their expiration dates set. so check the script we've been // given and set the expiration date if needed. triggered scripts don't have windows, so the only expiration // condition comes from the maximum age. if (script.ExpirationDate == null && _maxAge.HasValue) { script.ExpirationDate = script.Birthdate + _maxAge.Value; } // script could have already expired (e.g., if user took too long to open notification). if (script.ExpirationDate.HasValue && script.ExpirationDate.Value < DateTime.Now) { SensusServiceHelper.Get().Logger.Log("Script expired before it was run.", LoggingLevel.Normal, GetType()); return; } // do not run a one-shot script if it has already been run if (OneShot && RunTimes.Count > 0) { SensusServiceHelper.Get().Logger.Log("Not running one-shot script multiple times.", LoggingLevel.Normal, GetType()); return; } lock (RunTimes) { // track participation by recording the current time. use this instead of the script's run timestamp, since // the latter is the time of notification on ios rather than the time that the user actually viewed the script. RunTimes.Add(DateTime.Now); RunTimes.RemoveAll(r => r < Probe.Protocol.ParticipationHorizon); } #region submit a separate datum indicating each time the script was run. Task.Run(async () => { // geotag the script-run datum if any of the input groups are also geotagged. if none of the groups are geotagged, then // it wouldn't make sense to gather location data from a user. double? latitude = null; double? longitude = null; DateTimeOffset? locationTimestamp = null; if (script.InputGroups.Any(inputGroup => inputGroup.Geotag)) { try { Position currentPosition = GpsReceiver.Get().GetReading(new CancellationToken(), false); if (currentPosition == null) { throw new Exception("GPS receiver returned null position."); } latitude = currentPosition.Latitude; longitude = currentPosition.Longitude; locationTimestamp = currentPosition.Timestamp; } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to get position for script-run datum: " + ex.Message, LoggingLevel.Normal, GetType()); } } await Probe.StoreDatumAsync(new ScriptRunDatum(script.RunTime.Value, Script.Id, Name, script.Id, script.ScheduledRunTime, script.CurrentDatum?.Id, latitude, longitude, locationTimestamp), default(CancellationToken)); }); #endregion // this method can be called with previous / current datum values (e.g., when the script is first triggered). it // can also be called without previous / current datum values (e.g., when triggering on a schedule). if // we have such values, set them on the script. if (previousDatum != null) { script.PreviousDatum = previousDatum; } if (currentDatum != null) { script.CurrentDatum = currentDatum; } SensusServiceHelper.Get().AddScriptToRun(script, RunMode); } #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; using System.Runtime.InteropServices; using System.Text; namespace System { // Provides Windows-based support for System.Console. internal static class ConsolePal { private static IntPtr InvalidHandleValue => new IntPtr(-1); private static bool IsWindows7() { // Version lies for all apps from the OS kick in starting with Windows 8 (6.2). They can // also be added via appcompat (by the OS or the users) so this can only be used as a hint. Version version = Environment.OSVersion.Version; return version.Major == 6 && version.Minor == 1; } public static Stream OpenStandardInput() { return GetStandardFile(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE, FileAccess.Read); } public static Stream OpenStandardOutput() { return GetStandardFile(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE, FileAccess.Write); } public static Stream OpenStandardError() { return GetStandardFile(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE, FileAccess.Write); } private static IntPtr InputHandle { get { return Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE); } } private static IntPtr OutputHandle { get { return Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE); } } private static IntPtr ErrorHandle { get { return Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE); } } private static Stream GetStandardFile(int handleType, FileAccess access) { IntPtr handle = Interop.Kernel32.GetStdHandle(handleType); // If someone launches a managed process via CreateProcess, stdout, // stderr, & stdin could independently be set to INVALID_HANDLE_VALUE. // Additionally they might use 0 as an invalid handle. We also need to // ensure that if the handle is meant to be writable it actually is. if (handle == IntPtr.Zero || handle == InvalidHandleValue || (access != FileAccess.Read && !ConsoleHandleIsWritable(handle))) { return Stream.Null; } return new WindowsConsoleStream(handle, access, GetUseFileAPIs(handleType)); } // Checks whether stdout or stderr are writable. Do NOT pass // stdin here! The console handles are set to values like 3, 7, // and 11 OR if you've been created via CreateProcess, possibly -1 // or 0. -1 is definitely invalid, while 0 is probably invalid. // Also note each handle can independently be invalid or good. // For Windows apps, the console handles are set to values like 3, 7, // and 11 but are invalid handles - you may not write to them. However, // you can still spawn a Windows app via CreateProcess and read stdout // and stderr. So, we always need to check each handle independently for validity // by trying to write or read to it, unless it is -1. private static unsafe bool ConsoleHandleIsWritable(IntPtr outErrHandle) { // Windows apps may have non-null valid looking handle values for // stdin, stdout and stderr, but they may not be readable or // writable. Verify this by calling WriteFile in the // appropriate modes. This must handle console-less Windows apps. int bytesWritten; byte junkByte = 0x41; int r = Interop.Kernel32.WriteFile(outErrHandle, &junkByte, 0, out bytesWritten, IntPtr.Zero); return r != 0; // In Win32 apps w/ no console, bResult should be 0 for failure. } public static Encoding InputEncoding { get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.Kernel32.GetConsoleCP()); } } public static void SetConsoleInputEncoding(Encoding enc) { if (enc.CodePage != Encoding.Unicode.CodePage) { if (!Interop.Kernel32.SetConsoleCP(enc.CodePage)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static Encoding OutputEncoding { get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); } } public static void SetConsoleOutputEncoding(Encoding enc) { if (enc.CodePage != Encoding.Unicode.CodePage) { if (!Interop.Kernel32.SetConsoleOutputCP(enc.CodePage)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } private static bool GetUseFileAPIs(int handleType) { switch (handleType) { case Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE: return Console.InputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsInputRedirected; case Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE: return Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsOutputRedirected; case Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE: return Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsErrorRedirected; default: // This can never happen. Debug.Fail("Unexpected handleType value (" + handleType + ")"); return true; } } /// <summary>Gets whether Console.In is targeting a terminal display.</summary> public static bool IsInputRedirectedCore() { return IsHandleRedirected(InputHandle); } /// <summary>Gets whether Console.Out is targeting a terminal display.</summary> public static bool IsOutputRedirectedCore() { return IsHandleRedirected(OutputHandle); } /// <summary>Gets whether Console.In is targeting a terminal display.</summary> public static bool IsErrorRedirectedCore() { return IsHandleRedirected(ErrorHandle); } private static bool IsHandleRedirected(IntPtr handle) { // If handle is not to a character device, we must be redirected: uint fileType = Interop.Kernel32.GetFileType(handle); if ((fileType & Interop.Kernel32.FileTypes.FILE_TYPE_CHAR) != Interop.Kernel32.FileTypes.FILE_TYPE_CHAR) return true; // We are on a char device if GetConsoleMode succeeds and so we are not redirected. return (!Interop.Kernel32.IsGetConsoleModeCallSuccessful(handle)); } internal static TextReader GetOrCreateReader() { Stream inputStream = OpenStandardInput(); return SyncTextReader.GetSynchronizedTextReader(inputStream == Stream.Null ? StreamReader.Null : new StreamReader( stream: inputStream, encoding: new ConsoleEncoding(Console.InputEncoding), detectEncodingFromByteOrderMarks: false, bufferSize: Console.ReadBufferSize, leaveOpen: true)); } // Use this for blocking in Console.ReadKey, which needs to protect itself in case multiple threads call it simultaneously. // Use a ReadKey-specific lock though, to allow other fields to be initialized on this type. private static readonly object s_readKeySyncObject = new object(); // ReadLine & Read can't use this because they need to use ReadFile // to be able to handle redirected input. We have to accept that // we will lose repeated keystrokes when someone switches from // calling ReadKey to calling Read or ReadLine. Those methods should // ideally flush this cache as well. private static Interop.InputRecord _cachedInputRecord; // Skip non key events. Generally we want to surface only KeyDown event // and suppress KeyUp event from the same Key press but there are cases // where the assumption of KeyDown-KeyUp pairing for a given key press // is invalid. For example in IME Unicode keyboard input, we often see // only KeyUp until the key is released. private static bool IsKeyDownEvent(Interop.InputRecord ir) { return (ir.eventType == Interop.KEY_EVENT && ir.keyEvent.keyDown != Interop.BOOL.FALSE); } private static bool IsModKey(Interop.InputRecord ir) { // We should also skip over Shift, Control, and Alt, as well as caps lock. // Apparently we don't need to check for 0xA0 through 0xA5, which are keys like // Left Control & Right Control. See the ConsoleKey enum for these values. short keyCode = ir.keyEvent.virtualKeyCode; return ((keyCode >= 0x10 && keyCode <= 0x12) || keyCode == 0x14 || keyCode == 0x90 || keyCode == 0x91); } [Flags] internal enum ControlKeyState { RightAltPressed = 0x0001, LeftAltPressed = 0x0002, RightCtrlPressed = 0x0004, LeftCtrlPressed = 0x0008, ShiftPressed = 0x0010, NumLockOn = 0x0020, ScrollLockOn = 0x0040, CapsLockOn = 0x0080, EnhancedKey = 0x0100 } // For tracking Alt+NumPad unicode key sequence. When you press Alt key down // and press a numpad unicode decimal sequence and then release Alt key, the // desired effect is to translate the sequence into one Unicode KeyPress. // We need to keep track of the Alt+NumPad sequence and surface the final // unicode char alone when the Alt key is released. private static bool IsAltKeyDown(Interop.InputRecord ir) { return (((ControlKeyState)ir.keyEvent.controlKeyState) & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0; } private const int NumberLockVKCode = 0x90; private const int CapsLockVKCode = 0x14; public static bool NumberLock { get { try { short s = Interop.User32.GetKeyState(NumberLockVKCode); return (s & 1) == 1; } catch (Exception) { // Since we depend on an extension api-set here // it is not guaranteed to work across the board. // In case of exception we simply throw PNSE throw new PlatformNotSupportedException(); } } } public static bool CapsLock { get { try { short s = Interop.User32.GetKeyState(CapsLockVKCode); return (s & 1) == 1; } catch (Exception) { // Since we depend on an extension api-set here // it is not guaranteed to work across the board. // In case of exception we simply throw PNSE throw new PlatformNotSupportedException(); } } } public static bool KeyAvailable { get { if (_cachedInputRecord.eventType == Interop.KEY_EVENT) return true; Interop.InputRecord ir = new Interop.InputRecord(); int numEventsRead = 0; while (true) { bool r = Interop.Kernel32.PeekConsoleInput(InputHandle, out ir, 1, out numEventsRead); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE) throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile); throw Win32Marshal.GetExceptionForWin32Error(errorCode, "stdin"); } if (numEventsRead == 0) return false; // Skip non key-down && mod key events. if (!IsKeyDownEvent(ir) || IsModKey(ir)) { r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } else { return true; } } } // get } private const short AltVKCode = 0x12; public static ConsoleKeyInfo ReadKey(bool intercept) { Interop.InputRecord ir; int numEventsRead = -1; bool r; lock (s_readKeySyncObject) { if (_cachedInputRecord.eventType == Interop.KEY_EVENT) { // We had a previous keystroke with repeated characters. ir = _cachedInputRecord; if (_cachedInputRecord.keyEvent.repeatCount == 0) _cachedInputRecord.eventType = -1; else { _cachedInputRecord.keyEvent.repeatCount--; } // We will return one key from this method, so we decrement the // repeatCount here, leaving the cachedInputRecord in the "queue". } else { // We did NOT have a previous keystroke with repeated characters: while (true) { r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead); if (!r || numEventsRead == 0) { // This will fail when stdin is redirected from a file or pipe. // We could theoretically call Console.Read here, but I // think we might do some things incorrectly then. throw new InvalidOperationException(SR.InvalidOperation_ConsoleReadKeyOnFile); } short keyCode = ir.keyEvent.virtualKeyCode; // First check for non-keyboard events & discard them. Generally we tap into only KeyDown events and ignore the KeyUp events // but it is possible that we are dealing with a Alt+NumPad unicode key sequence, the final unicode char is revealed only when // the Alt key is released (i.e when the sequence is complete). To avoid noise, when the Alt key is down, we should eat up // any intermediate key strokes (from NumPad) that collectively forms the Unicode character. if (!IsKeyDownEvent(ir)) { // REVIEW: Unicode IME input comes through as KeyUp event with no accompanying KeyDown. if (keyCode != AltVKCode) continue; } char ch = (char)ir.keyEvent.uChar; // In a Alt+NumPad unicode sequence, when the alt key is released uChar will represent the final unicode character, we need to // surface this. VirtualKeyCode for this event will be Alt from the Alt-Up key event. This is probably not the right code, // especially when we don't expose ConsoleKey.Alt, so this will end up being the hex value (0x12). VK_PACKET comes very // close to being useful and something that we could look into using for this purpose... if (ch == 0) { // Skip mod keys. if (IsModKey(ir)) continue; } // When Alt is down, it is possible that we are in the middle of a Alt+NumPad unicode sequence. // Escape any intermediate NumPad keys whether NumLock is on or not (notepad behavior) ConsoleKey key = (ConsoleKey)keyCode; if (IsAltKeyDown(ir) && ((key >= ConsoleKey.NumPad0 && key <= ConsoleKey.NumPad9) || (key == ConsoleKey.Clear) || (key == ConsoleKey.Insert) || (key >= ConsoleKey.PageUp && key <= ConsoleKey.DownArrow))) { continue; } if (ir.keyEvent.repeatCount > 1) { ir.keyEvent.repeatCount--; _cachedInputRecord = ir; } break; } } // we did NOT have a previous keystroke with repeated characters. } ControlKeyState state = (ControlKeyState)ir.keyEvent.controlKeyState; bool shift = (state & ControlKeyState.ShiftPressed) != 0; bool alt = (state & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0; bool control = (state & (ControlKeyState.LeftCtrlPressed | ControlKeyState.RightCtrlPressed)) != 0; ConsoleKeyInfo info = new ConsoleKeyInfo((char)ir.keyEvent.uChar, (ConsoleKey)ir.keyEvent.virtualKeyCode, shift, alt, control); if (!intercept) Console.Write(ir.keyEvent.uChar); return info; } public static bool TreatControlCAsInput { get { IntPtr handle = InputHandle; if (handle == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); int mode = 0; if (!Interop.Kernel32.GetConsoleMode(handle, out mode)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); return (mode & Interop.Kernel32.ENABLE_PROCESSED_INPUT) == 0; } set { IntPtr handle = InputHandle; if (handle == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); int mode = 0; Interop.Kernel32.GetConsoleMode(handle, out mode); // failure ignored in full framework if (value) { mode &= ~Interop.Kernel32.ENABLE_PROCESSED_INPUT; } else { mode |= Interop.Kernel32.ENABLE_PROCESSED_INPUT; } if (!Interop.Kernel32.SetConsoleMode(handle, mode)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } // For ResetColor private static volatile bool _haveReadDefaultColors; private static volatile byte _defaultColors; public static ConsoleColor BackgroundColor { get { bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); return succeeded ? ColorAttributeToConsoleColor((Interop.Kernel32.Color)csbi.wAttributes & Interop.Kernel32.Color.BackgroundMask) : ConsoleColor.Black; // for code that may be used from Windows app w/ no console } set { Interop.Kernel32.Color c = ConsoleColorToColorAttribute(value, true); bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); // For code that may be used from Windows app w/ no console if (!succeeded) return; Debug.Assert(_haveReadDefaultColors, "Setting the background color before we've read the default foreground color!"); short attrs = csbi.wAttributes; attrs &= ~((short)Interop.Kernel32.Color.BackgroundMask); // C#'s bitwise-or sign-extends to 32 bits. attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c)); // Ignore errors here - there are some scenarios for running code that wants // to print in colors to the console in a Windows application. Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, attrs); } } public static ConsoleColor ForegroundColor { get { bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); // For code that may be used from Windows app w/ no console return succeeded ? ColorAttributeToConsoleColor((Interop.Kernel32.Color)csbi.wAttributes & Interop.Kernel32.Color.ForegroundMask) : ConsoleColor.Gray; } set { Interop.Kernel32.Color c = ConsoleColorToColorAttribute(value, false); bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); // For code that may be used from Windows app w/ no console if (!succeeded) return; Debug.Assert(_haveReadDefaultColors, "Setting the foreground color before we've read the default foreground color!"); short attrs = csbi.wAttributes; attrs &= ~((short)Interop.Kernel32.Color.ForegroundMask); // C#'s bitwise-or sign-extends to 32 bits. attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c)); // Ignore errors here - there are some scenarios for running code that wants // to print in colors to the console in a Windows application. Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, attrs); } } public static void ResetColor() { if (!_haveReadDefaultColors) // avoid the costs of GetBufferInfo if we already know we checked it { bool succeeded; GetBufferInfo(false, out succeeded); if (!succeeded) return; // For code that may be used from Windows app w/ no console Debug.Assert(_haveReadDefaultColors, "Resetting color before we've read the default foreground color!"); } // Ignore errors here - there are some scenarios for running code that wants // to print in colors to the console in a Windows application. Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, (short)(ushort)_defaultColors); } public static int CursorSize { get { Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); return cci.dwSize; } set { // Value should be a percentage from [1, 100]. if (value < 1 || value > 100) throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_CursorSize); Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); cci.dwSize = value; if (!Interop.Kernel32.SetConsoleCursorInfo(OutputHandle, ref cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static bool CursorVisible { get { Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); return cci.bVisible; } set { Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); cci.bVisible = value; if (!Interop.Kernel32.SetConsoleCursorInfo(OutputHandle, ref cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static int CursorLeft { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwCursorPosition.X; } } public static int CursorTop { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwCursorPosition.Y; } } public unsafe static string Title { get { Span<char> initialBuffer = stackalloc char[256]; ValueStringBuilder builder = new ValueStringBuilder(initialBuffer); while (true) { uint result = Interop.Errors.ERROR_SUCCESS; fixed (char* c = &builder.GetPinnableReference()) { result = Interop.Kernel32.GetConsoleTitleW(c, (uint)builder.Capacity); } // The documentation asserts that the console's title is stored in a shared 64KB buffer. // The magic number that used to exist here (24500) is likely related to that. // A full UNICODE_STRING is 32K chars... Debug.Assert(result <= short.MaxValue, "shouldn't be possible to grow beyond UNICODE_STRING size"); if (result == 0) { int error = Marshal.GetLastWin32Error(); switch (error) { case Interop.Errors.ERROR_INSUFFICIENT_BUFFER: // Typically this API truncates but there was a bug in RS2 so we'll make an attempt to handle builder.EnsureCapacity(builder.Capacity * 2); continue; case Interop.Errors.ERROR_SUCCESS: // The title is empty. break; default: throw Win32Marshal.GetExceptionForWin32Error(error, string.Empty); } } else if (result >= builder.Capacity - 1 || (IsWindows7() && result >= builder.Capacity / sizeof(char) - 1)) { // Our buffer was full. As this API truncates we need to increase our size and reattempt. // Note that Windows 7 copies count of bytes into the output buffer but returns count of chars // and as such our buffer is only "half" its actual size. // // (If we're Windows 10 with a version lie to 7 this will be inefficient so we'll want to remove // this workaround when we no longer support Windows 7) builder.EnsureCapacity(builder.Capacity * 2); continue; } builder.Length = (int)result; break; } return builder.ToString(); } set { if (!Interop.Kernel32.SetConsoleTitle(value)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static void Beep() { const int BeepFrequencyInHz = 800; const int BeepDurationInMs = 200; Interop.Kernel32.Beep(BeepFrequencyInHz, BeepDurationInMs); } public static void Beep(int frequency, int duration) { const int MinBeepFrequency = 37; const int MaxBeepFrequency = 32767; if (frequency < MinBeepFrequency || frequency > MaxBeepFrequency) throw new ArgumentOutOfRangeException(nameof(frequency), frequency, SR.Format(SR.ArgumentOutOfRange_BeepFrequency, MinBeepFrequency, MaxBeepFrequency)); if (duration <= 0) throw new ArgumentOutOfRangeException(nameof(duration), duration, SR.ArgumentOutOfRange_NeedPosNum); Interop.Kernel32.Beep(frequency, duration); } public static unsafe void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { if (sourceForeColor < ConsoleColor.Black || sourceForeColor > ConsoleColor.White) throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceForeColor)); if (sourceBackColor < ConsoleColor.Black || sourceBackColor > ConsoleColor.White) throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceBackColor)); Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); Interop.Kernel32.COORD bufferSize = csbi.dwSize; if (sourceLeft < 0 || sourceLeft > bufferSize.X) throw new ArgumentOutOfRangeException(nameof(sourceLeft), sourceLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (sourceTop < 0 || sourceTop > bufferSize.Y) throw new ArgumentOutOfRangeException(nameof(sourceTop), sourceTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (sourceWidth < 0 || sourceWidth > bufferSize.X - sourceLeft) throw new ArgumentOutOfRangeException(nameof(sourceWidth), sourceWidth, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (sourceHeight < 0 || sourceTop > bufferSize.Y - sourceHeight) throw new ArgumentOutOfRangeException(nameof(sourceHeight), sourceHeight, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); // Note: if the target range is partially in and partially out // of the buffer, then we let the OS clip it for us. if (targetLeft < 0 || targetLeft > bufferSize.X) throw new ArgumentOutOfRangeException(nameof(targetLeft), targetLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (targetTop < 0 || targetTop > bufferSize.Y) throw new ArgumentOutOfRangeException(nameof(targetTop), targetTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); // If we're not doing any work, bail out now (Windows will return // an error otherwise) if (sourceWidth == 0 || sourceHeight == 0) return; // Read data from the original location, blank it out, then write // it to the new location. This will handle overlapping source and // destination regions correctly. // Read the old data Interop.Kernel32.CHAR_INFO[] data = new Interop.Kernel32.CHAR_INFO[sourceWidth * sourceHeight]; bufferSize.X = (short)sourceWidth; bufferSize.Y = (short)sourceHeight; Interop.Kernel32.COORD bufferCoord = new Interop.Kernel32.COORD(); Interop.Kernel32.SMALL_RECT readRegion = new Interop.Kernel32.SMALL_RECT(); readRegion.Left = (short)sourceLeft; readRegion.Right = (short)(sourceLeft + sourceWidth - 1); readRegion.Top = (short)sourceTop; readRegion.Bottom = (short)(sourceTop + sourceHeight - 1); bool r; fixed (Interop.Kernel32.CHAR_INFO* pCharInfo = data) r = Interop.Kernel32.ReadConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref readRegion); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); // Overwrite old section Interop.Kernel32.COORD writeCoord = new Interop.Kernel32.COORD(); writeCoord.X = (short)sourceLeft; Interop.Kernel32.Color c = ConsoleColorToColorAttribute(sourceBackColor, true); c |= ConsoleColorToColorAttribute(sourceForeColor, false); short attr = (short)c; int numWritten; for (int i = sourceTop; i < sourceTop + sourceHeight; i++) { writeCoord.Y = (short)i; r = Interop.Kernel32.FillConsoleOutputCharacter(OutputHandle, sourceChar, sourceWidth, writeCoord, out numWritten); Debug.Assert(numWritten == sourceWidth, "FillConsoleOutputCharacter wrote the wrong number of chars!"); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); r = Interop.Kernel32.FillConsoleOutputAttribute(OutputHandle, attr, sourceWidth, writeCoord, out numWritten); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } // Write text to new location Interop.Kernel32.SMALL_RECT writeRegion = new Interop.Kernel32.SMALL_RECT(); writeRegion.Left = (short)targetLeft; writeRegion.Right = (short)(targetLeft + sourceWidth); writeRegion.Top = (short)targetTop; writeRegion.Bottom = (short)(targetTop + sourceHeight); fixed (Interop.Kernel32.CHAR_INFO* pCharInfo = data) Interop.Kernel32.WriteConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref writeRegion); } public static void Clear() { Interop.Kernel32.COORD coordScreen = new Interop.Kernel32.COORD(); Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi; bool success; int conSize; IntPtr hConsole = OutputHandle; if (hConsole == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); // get the number of character cells in the current buffer // Go through my helper method for fetching a screen buffer info // to correctly handle default console colors. csbi = GetBufferInfo(); conSize = csbi.dwSize.X * csbi.dwSize.Y; // fill the entire screen with blanks int numCellsWritten = 0; success = Interop.Kernel32.FillConsoleOutputCharacter(hConsole, ' ', conSize, coordScreen, out numCellsWritten); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); // now set the buffer's attributes accordingly numCellsWritten = 0; success = Interop.Kernel32.FillConsoleOutputAttribute(hConsole, csbi.wAttributes, conSize, coordScreen, out numCellsWritten); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); // put the cursor at (0, 0) success = Interop.Kernel32.SetConsoleCursorPosition(hConsole, coordScreen); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } public static void SetCursorPosition(int left, int top) { IntPtr hConsole = OutputHandle; Interop.Kernel32.COORD coords = new Interop.Kernel32.COORD(); coords.X = (short)left; coords.Y = (short)top; if (!Interop.Kernel32.SetConsoleCursorPosition(hConsole, coords)) { // Give a nice error message for out of range sizes int errorCode = Marshal.GetLastWin32Error(); Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); if (left >= csbi.dwSize.X) throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (top >= csbi.dwSize.Y) throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } public static int BufferWidth { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwSize.X; } set { SetBufferSize(value, BufferHeight); } } public static int BufferHeight { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwSize.Y; } set { SetBufferSize(BufferWidth, value); } } public static void SetBufferSize(int width, int height) { // Ensure the new size is not smaller than the console window Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow; if (width < srWindow.Right + 1 || width >= short.MaxValue) throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize); if (height < srWindow.Bottom + 1 || height >= short.MaxValue) throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize); Interop.Kernel32.COORD size = new Interop.Kernel32.COORD(); size.X = (short)width; size.Y = (short)height; if (!Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, size)) { throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static int LargestWindowWidth { get { // Note this varies based on current screen resolution and // current console font. Do not cache this value. Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle); return bounds.X; } } public static int LargestWindowHeight { get { // Note this varies based on current screen resolution and // current console font. Do not cache this value. Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle); return bounds.Y; } } public static int WindowLeft { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Left; } set { SetWindowPosition(value, WindowTop); } } public static int WindowTop { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Top; } set { SetWindowPosition(WindowLeft, value); } } public static int WindowWidth { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Right - csbi.srWindow.Left + 1; } set { SetWindowSize(value, WindowHeight); } } public static int WindowHeight { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; } set { SetWindowSize(WindowWidth, value); } } public static unsafe void SetWindowPosition(int left, int top) { // Get the size of the current console window Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow; // Check for arithmetic underflows & overflows. int newRight = left + srWindow.Right - srWindow.Left + 1; if (left < 0 || newRight > csbi.dwSize.X || newRight < 0) throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleWindowPos); int newBottom = top + srWindow.Bottom - srWindow.Top + 1; if (top < 0 || newBottom > csbi.dwSize.Y || newBottom < 0) throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleWindowPos); // Preserve the size, but move the position. srWindow.Bottom -= (short)(srWindow.Top - top); srWindow.Right -= (short)(srWindow.Left - left); srWindow.Left = (short)left; srWindow.Top = (short)top; bool r = Interop.Kernel32.SetConsoleWindowInfo(OutputHandle, true, &srWindow); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } public static unsafe void SetWindowSize(int width, int height) { if (width <= 0) throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_NeedPosNum); if (height <= 0) throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_NeedPosNum); // Get the position of the current console window Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); // If the buffer is smaller than this new window size, resize the // buffer to be large enough. Include window position. bool resizeBuffer = false; Interop.Kernel32.COORD size = new Interop.Kernel32.COORD(); size.X = csbi.dwSize.X; size.Y = csbi.dwSize.Y; if (csbi.dwSize.X < csbi.srWindow.Left + width) { if (csbi.srWindow.Left >= short.MaxValue - width) throw new ArgumentOutOfRangeException(nameof(width), SR.Format(SR.ArgumentOutOfRange_ConsoleWindowBufferSize, short.MaxValue - width)); size.X = (short)(csbi.srWindow.Left + width); resizeBuffer = true; } if (csbi.dwSize.Y < csbi.srWindow.Top + height) { if (csbi.srWindow.Top >= short.MaxValue - height) throw new ArgumentOutOfRangeException(nameof(height), SR.Format(SR.ArgumentOutOfRange_ConsoleWindowBufferSize, short.MaxValue - height)); size.Y = (short)(csbi.srWindow.Top + height); resizeBuffer = true; } if (resizeBuffer) { if (!Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, size)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow; // Preserve the position, but change the size. srWindow.Bottom = (short)(srWindow.Top + height - 1); srWindow.Right = (short)(srWindow.Left + width - 1); if (!Interop.Kernel32.SetConsoleWindowInfo(OutputHandle, true, &srWindow)) { int errorCode = Marshal.GetLastWin32Error(); // If we resized the buffer, un-resize it. if (resizeBuffer) { Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, csbi.dwSize); } // Try to give a better error message here Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle); if (width > bounds.X) throw new ArgumentOutOfRangeException(nameof(width), width, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.X)); if (height > bounds.Y) throw new ArgumentOutOfRangeException(nameof(height), height, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.Y)); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } private static Interop.Kernel32.Color ConsoleColorToColorAttribute(ConsoleColor color, bool isBackground) { if ((((int)color) & ~0xf) != 0) throw new ArgumentException(SR.Arg_InvalidConsoleColor); Interop.Kernel32.Color c = (Interop.Kernel32.Color)color; // Make these background colors instead of foreground if (isBackground) c = (Interop.Kernel32.Color)((int)c << 4); return c; } private static ConsoleColor ColorAttributeToConsoleColor(Interop.Kernel32.Color c) { // Turn background colors into foreground colors. if ((c & Interop.Kernel32.Color.BackgroundMask) != 0) { c = (Interop.Kernel32.Color)(((int)c) >> 4); } return (ConsoleColor)c; } private static Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo() { bool unused; return GetBufferInfo(true, out unused); } // For apps that don't have a console (like Windows apps), they might // run other code that includes color console output. Allow a mechanism // where that code won't throw an exception for simple errors. private static Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded) { succeeded = false; IntPtr outputHandle = OutputHandle; if (outputHandle == InvalidHandleValue) { if (throwOnNoConsole) { throw new IOException(SR.IO_NoConsole); } return new Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO(); } // Note that if stdout is redirected to a file, the console handle may be a file. // First try stdout; if this fails, try stderr and then stdin. Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi; if (!Interop.Kernel32.GetConsoleScreenBufferInfo(outputHandle, out csbi) && !Interop.Kernel32.GetConsoleScreenBufferInfo(ErrorHandle, out csbi) && !Interop.Kernel32.GetConsoleScreenBufferInfo(InputHandle, out csbi)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE && !throwOnNoConsole) return new Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } if (!_haveReadDefaultColors) { // Fetch the default foreground and background color for the ResetColor method. Debug.Assert((int)Interop.Kernel32.Color.ColorMask == 0xff, "Make sure one byte is large enough to store a Console color value!"); _defaultColors = (byte)(csbi.wAttributes & (short)Interop.Kernel32.Color.ColorMask); _haveReadDefaultColors = true; // also used by ResetColor to know when GetBufferInfo has been called successfully } succeeded = true; return csbi; } private sealed class WindowsConsoleStream : ConsoleStream { // We know that if we are using console APIs rather than file APIs, then the encoding // is Encoding.Unicode implying 2 bytes per character: const int BytesPerWChar = 2; private readonly bool _isPipe; // When reading from pipes, we need to properly handle EOF cases. private IntPtr _handle; private readonly bool _useFileAPIs; internal WindowsConsoleStream(IntPtr handle, FileAccess access, bool useFileAPIs) : base(access) { Debug.Assert(handle != IntPtr.Zero && handle != InvalidHandleValue, "ConsoleStream expects a valid handle!"); _handle = handle; _isPipe = Interop.Kernel32.GetFileType(handle) == Interop.Kernel32.FileTypes.FILE_TYPE_PIPE; _useFileAPIs = useFileAPIs; } protected override void Dispose(bool disposing) { // We're probably better off not closing the OS handle here. First, // we allow a program to get multiple instances of ConsoleStreams // around the same OS handle, so closing one handle would invalidate // them all. Additionally, we want a second AppDomain to be able to // write to stdout if a second AppDomain quits. _handle = IntPtr.Zero; base.Dispose(disposing); } public override int Read(byte[] buffer, int offset, int count) { ValidateRead(buffer, offset, count); int bytesRead; int errCode = ReadFileNative(_handle, buffer, offset, count, _isPipe, out bytesRead, _useFileAPIs); if (Interop.Errors.ERROR_SUCCESS != errCode) throw Win32Marshal.GetExceptionForWin32Error(errCode); return bytesRead; } public override void Write(byte[] buffer, int offset, int count) { ValidateWrite(buffer, offset, count); int errCode = WriteFileNative(_handle, buffer, offset, count, _useFileAPIs); if (Interop.Errors.ERROR_SUCCESS != errCode) throw Win32Marshal.GetExceptionForWin32Error(errCode); } public override void Flush() { if (_handle == IntPtr.Zero) throw Error.GetFileNotOpen(); base.Flush(); } // P/Invoke wrappers for writing to and from a file, nearly identical // to the ones on FileStream. These are duplicated to save startup/hello // world working set and to avoid requiring a reference to the // System.IO.FileSystem contract. private static unsafe int ReadFileNative(IntPtr hFile, byte[] bytes, int offset, int count, bool isPipe, out int bytesRead, bool useFileAPIs) { Debug.Assert(offset >= 0, "offset >= 0"); Debug.Assert(count >= 0, "count >= 0"); Debug.Assert(bytes != null, "bytes != null"); // Don't corrupt memory when multiple threads are erroneously writing // to this stream simultaneously. if (bytes.Length - offset < count) throw new IndexOutOfRangeException(SR.IndexOutOfRange_IORaceCondition); // You can't use the fixed statement on an array of length 0. if (bytes.Length == 0) { bytesRead = 0; return Interop.Errors.ERROR_SUCCESS; } bool readSuccess; fixed (byte* p = &bytes[0]) { if (useFileAPIs) { readSuccess = (0 != Interop.Kernel32.ReadFile(hFile, p + offset, count, out bytesRead, IntPtr.Zero)); } else { // If the code page could be Unicode, we should use ReadConsole instead, e.g. int charsRead; readSuccess = Interop.Kernel32.ReadConsole(hFile, p + offset, count / BytesPerWChar, out charsRead, IntPtr.Zero); bytesRead = charsRead * BytesPerWChar; } } if (readSuccess) return Interop.Errors.ERROR_SUCCESS; // For pipes that are closing or broken, just stop. // (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing; // ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.) int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_NO_DATA || errorCode == Interop.Errors.ERROR_BROKEN_PIPE) return Interop.Errors.ERROR_SUCCESS; return errorCode; } private static unsafe int WriteFileNative(IntPtr hFile, byte[] bytes, int offset, int count, bool useFileAPIs) { Debug.Assert(offset >= 0, "offset >= 0"); Debug.Assert(count >= 0, "count >= 0"); Debug.Assert(bytes != null, "bytes != null"); Debug.Assert(bytes.Length >= offset + count, "bytes.Length >= offset + count"); // You can't use the fixed statement on an array of length 0. if (bytes.Length == 0) return Interop.Errors.ERROR_SUCCESS; bool writeSuccess; fixed (byte* p = &bytes[0]) { if (useFileAPIs) { int numBytesWritten; writeSuccess = (0 != Interop.Kernel32.WriteFile(hFile, p + offset, count, out numBytesWritten, IntPtr.Zero)); // In some cases we have seen numBytesWritten returned that is twice count; // so we aren't asserting the value of it. See corefx #24508 } else { // If the code page could be Unicode, we should use ReadConsole instead, e.g. // Note that WriteConsoleW has a max limit on num of chars to write (64K) // [https://docs.microsoft.com/en-us/windows/console/writeconsole] // However, we do not need to worry about that because the StreamWriter in Console has // a much shorter buffer size anyway. int charsWritten; writeSuccess = Interop.Kernel32.WriteConsole(hFile, p + offset, count / BytesPerWChar, out charsWritten, IntPtr.Zero); Debug.Assert(!writeSuccess || count / BytesPerWChar == charsWritten); } } if (writeSuccess) return Interop.Errors.ERROR_SUCCESS; // For pipes that are closing or broken, just stop. // (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing; // ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is not an error, but EOF.) int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_NO_DATA || errorCode == Interop.Errors.ERROR_BROKEN_PIPE) return Interop.Errors.ERROR_SUCCESS; return errorCode; } } internal sealed class ControlCHandlerRegistrar { private bool _handlerRegistered; private Interop.Kernel32.ConsoleCtrlHandlerRoutine _handler; internal ControlCHandlerRegistrar() { _handler = new Interop.Kernel32.ConsoleCtrlHandlerRoutine(BreakEvent); } internal void Register() { Debug.Assert(!_handlerRegistered); bool r = Interop.Kernel32.SetConsoleCtrlHandler(_handler, true); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(); } _handlerRegistered = true; } internal void Unregister() { Debug.Assert(_handlerRegistered); bool r = Interop.Kernel32.SetConsoleCtrlHandler(_handler, false); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(); } _handlerRegistered = false; } private static bool BreakEvent(int controlType) { if (controlType != Interop.Kernel32.CTRL_C_EVENT && controlType != Interop.Kernel32.CTRL_BREAK_EVENT) { return false; } return Console.HandleBreakEvent(controlType == Interop.Kernel32.CTRL_C_EVENT ? ConsoleSpecialKey.ControlC : ConsoleSpecialKey.ControlBreak); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Runtime; using Orleans.Transactions.Abstractions; using Orleans.Storage; using Orleans.Configuration; using Orleans.Timers.Internal; namespace Orleans.Transactions.State { internal class TransactionQueue<TState> where TState : class, new() { private readonly TransactionalStateOptions options; private readonly ParticipantId resource; private readonly Action deactivate; private readonly ITransactionalStateStorage<TState> storage; private readonly BatchWorker storageWorker; protected readonly ILogger logger; private readonly IActivationLifetime activationLifetime; private readonly ConfirmationWorker<TState> confirmationWorker; private CommitQueue<TState> commitQueue; private Task readyTask; protected StorageBatch<TState> storageBatch; private int failCounter; // collection tasks private Dictionary<DateTime, PreparedMessages> unprocessedPreparedMessages; private class PreparedMessages { public PreparedMessages(TransactionalStatus status) { this.Status = status; } public int Count; public TransactionalStatus Status; } private TState stableState; private long stableSequenceNumber; public ReadWriteLock<TState> RWLock { get; } public CausalClock Clock { get; } public TransactionQueue( IOptions<TransactionalStateOptions> options, ParticipantId resource, Action deactivate, ITransactionalStateStorage<TState> storage, IClock clock, ILogger logger, ITimerManager timerManager, IActivationLifetime activationLifetime) { this.options = options.Value; this.resource = resource; this.deactivate = deactivate; this.storage = storage; this.Clock = new CausalClock(clock); this.logger = logger; this.activationLifetime = activationLifetime; this.storageWorker = new BatchWorkerFromDelegate(StorageWork, this.activationLifetime.OnDeactivating); this.RWLock = new ReadWriteLock<TState>(options, this, this.storageWorker, logger, activationLifetime); this.confirmationWorker = new ConfirmationWorker<TState>(options, this.resource, this.storageWorker, () => this.storageBatch, this.logger, timerManager, activationLifetime); this.unprocessedPreparedMessages = new Dictionary<DateTime, PreparedMessages>(); this.commitQueue = new CommitQueue<TState>(); this.readyTask = Task.CompletedTask; } public async Task EnqueueCommit(TransactionRecord<TState> record) { try { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace($"start two-phase-commit {record.TransactionId} {record.Timestamp:o}"); commitQueue.Add(record); // additional actions for each commit type switch (record.Role) { case CommitRole.ReadOnly: { // no extra actions needed break; } case CommitRole.LocalCommit: { // process prepared messages received ahead of time if (unprocessedPreparedMessages.TryGetValue(record.Timestamp, out PreparedMessages info)) { if (info.Status == TransactionalStatus.Ok) { record.WaitCount -= info.Count; } else { await AbortCommits(info.Status, commitQueue.Count - 1); this.RWLock.Notify(); } unprocessedPreparedMessages.Remove(record.Timestamp); } break; } case CommitRole.RemoteCommit: { // optimization: can immediately proceed if dependency is implied bool behindRemoteEntryBySameTM = false; /* disabled - jbragg - TODO - revisit commitQueue.Count >= 2 && commitQueue[commitQueue.Count - 2] is TransactionRecord<TState> rce && rce.Role == CommitRole.RemoteCommit && rce.TransactionManager.Equals(record.TransactionManager); */ if (record.NumberWrites > 0) { this.storageBatch.Prepare(record.SequenceNumber, record.TransactionId, record.Timestamp, record.TransactionManager, record.State); } else { this.storageBatch.Read(record.Timestamp); } this.storageBatch.FollowUpAction(() => { if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("persisted {Record}", record); } record.PrepareIsPersisted = true; if (behindRemoteEntryBySameTM) { if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("Sending immediate prepared {Record}", record); } // can send prepared message immediately after persisting prepare record record.TransactionManager.Reference.AsReference<ITransactionManagerExtension>() .Prepared(record.TransactionManager.Name, record.TransactionId, record.Timestamp, this.resource, TransactionalStatus.Ok) .Ignore(); record.LastSent = DateTime.UtcNow; } }); break; } default: { logger.LogError(777, "internal error: impossible case {CommitRole}", record.Role); throw new NotSupportedException($"{record.Role} is not a supported CommitRole."); } } } catch (Exception exception) { logger.Error(666, $"transaction abort due to internal error in {nameof(EnqueueCommit)}: ", exception); await NotifyOfAbort(record, TransactionalStatus.UnknownException, exception); } } public async Task NotifyOfPrepared(Guid transactionId, DateTime timeStamp, TransactionalStatus status) { var pos = commitQueue.Find(transactionId, timeStamp); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("NotifyOfPrepared - TransactionId:{TransactionId} Timestamp:{Timestamp}, TransactionalStatus{TransactionalStatus}", transactionId, timeStamp, status); if (pos != -1) { var localEntry = commitQueue[pos]; if (localEntry.Role != CommitRole.LocalCommit) { logger.Error(666, $"transaction abort due to internal error in {nameof(NotifyOfPrepared)}: Wrong commit type"); throw new InvalidOperationException($"Wrong commit type: {localEntry.Role}"); } if (status == TransactionalStatus.Ok) { localEntry.WaitCount--; storageWorker.Notify(); } else { await AbortCommits(status, pos); this.RWLock.Notify(); } } else { // this message has arrived ahead of the commit request - we need to remember it if (!this.unprocessedPreparedMessages.TryGetValue(timeStamp, out PreparedMessages info)) { this.unprocessedPreparedMessages[timeStamp] = info = new PreparedMessages(status); } if (status == TransactionalStatus.Ok) { info.Count++; } else { info.Status = status; } // TODO fix memory leak if corresponding commit messages never arrive } } public async Task NotifyOfPrepare(Guid transactionId, AccessCounter accessCount, DateTime timeStamp, ParticipantId transactionManager) { var locked = await this.RWLock.ValidateLock(transactionId, accessCount); var status = locked.Item1; var record = locked.Item2; var valid = status == TransactionalStatus.Ok; record.Timestamp = timeStamp; record.Role = CommitRole.RemoteCommit; // we are not the TM record.TransactionManager = transactionManager; record.LastSent = null; record.PrepareIsPersisted = false; if (!valid) { await this.NotifyOfAbort(record, status, exception: null); } else { this.Clock.Merge(record.Timestamp); } this.RWLock.Notify(); } public async Task NotifyOfAbort(TransactionRecord<TState> entry, TransactionalStatus status, Exception exception) { switch (entry.Role) { case CommitRole.NotYetDetermined: { // cannot notify anyone. TA will detect broken lock during prepare. break; } case CommitRole.RemoteCommit: { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("aborting status={Status} {Entry}", status, entry); entry.ConfirmationResponsePromise?.TrySetException(new OrleansException($"Confirm failed: Status {status}")); if (entry.LastSent.HasValue) return; // cannot abort anymore if we already sent prepare-ok message if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("aborting via Prepared. Status={Status} Entry={Entry}", status, entry); entry.TransactionManager.Reference.AsReference<ITransactionManagerExtension>() .Prepared(entry.TransactionManager.Name, entry.TransactionId, entry.Timestamp, resource, status) .Ignore(); break; } case CommitRole.LocalCommit: { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("aborting status={Status} {Entry}", status, entry); try { // tell remote participants await Task.WhenAll(entry.WriteParticipants .Where(p => !p.Equals(resource)) .Select(p => p.Reference.AsReference<ITransactionalResourceExtension>() .Cancel(p.Name, entry.TransactionId, entry.Timestamp, status))); } catch(Exception ex) { this.logger.LogWarning(ex, "Failed to notify all transaction participants of cancellation. TransactionId: {TransactionId}, Timestamp: {Timestamp}, Status: {Status}", entry.TransactionId, entry.Timestamp, status); } // reply to transaction agent if (exception is object) { entry.PromiseForTA.TrySetException(exception); } else { entry.PromiseForTA.TrySetResult(status); } break; } case CommitRole.ReadOnly: { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("aborting status={Status} {Entry}", status, entry); // reply to transaction agent if (exception is object) { entry.PromiseForTA.TrySetException(exception); } else { entry.PromiseForTA.TrySetResult(status); } break; } default: { logger.LogError(777, "internal error: impossible case {CommitRole}", entry.Role); throw new NotSupportedException($"{entry.Role} is not a supported CommitRole."); } } } public async Task NotifyOfPing(Guid transactionId, DateTime timeStamp, ParticipantId resource) { if (this.commitQueue.Find(transactionId, timeStamp) != -1) { // no need to take special action now - the transaction is still // in the commit queue and its status is not yet determined. // confirmation or cancellation will be sent after committing or aborting. if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("received ping for {TransactionId}, irrelevant (still processing)", transactionId); this.storageWorker.Notify(); // just in case the worker fell asleep or something } else { if (!this.confirmationWorker.IsConfirmed(transactionId)) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("received ping for {TransactionId}, unknown - presumed abort", transactionId); // we never heard of this transaction - so it must have aborted await resource.Reference.AsReference<ITransactionalResourceExtension>() .Cancel(resource.Name, transactionId, timeStamp, TransactionalStatus.PresumedAbort); } } } public async Task NotifyOfConfirm(Guid transactionId, DateTime timeStamp) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace($"NotifyOfConfirm: {transactionId} {timeStamp}"); // find in queue var pos = commitQueue.Find(transactionId, timeStamp); if (pos == -1) return; // must have already been confirmed var remoteEntry = commitQueue[pos]; if (remoteEntry.Role != CommitRole.RemoteCommit) { logger.Error(666, $"internal error in {nameof(NotifyOfConfirm)}: wrong commit type"); throw new InvalidOperationException($"Wrong commit type: {remoteEntry.Role}"); } // setting this field makes this entry ready for batching remoteEntry.ConfirmationResponsePromise = remoteEntry.ConfirmationResponsePromise ?? new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); storageWorker.Notify(); // now we wait for the batch to finish await remoteEntry.ConfirmationResponsePromise.Task; } public async Task NotifyOfCancel(Guid transactionId, DateTime timeStamp, TransactionalStatus status) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("{MethodName}. TransactionId: {TransactionId}, TimeStamp: {TimeStamp} Status: {TransactionalStatus}", nameof(NotifyOfCancel), transactionId, timeStamp, status); // find in queue var pos = commitQueue.Find(transactionId, timeStamp); if (pos == -1) return; this.storageBatch.Cancel(commitQueue[pos].SequenceNumber); await AbortCommits(status, pos); storageWorker.Notify(); this.RWLock.Notify(); } /// <summary> /// called on activation, and when recovering from storage conflicts or other exceptions. /// </summary> public async Task NotifyOfRestore() { try { await Ready(); } finally { this.readyTask = Restore(); } await this.readyTask; } /// <summary> /// Ensures queue is ready to process requests. /// </summary> /// <returns></returns> public Task Ready() { return this.readyTask; } private async Task Restore() { TransactionalStorageLoadResponse<TState> loadresponse = await storage.Load(); this.storageBatch = new StorageBatch<TState>(loadresponse); this.stableState = loadresponse.CommittedState; this.stableSequenceNumber = loadresponse.CommittedSequenceId; if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"Load v{this.stableSequenceNumber} {loadresponse.PendingStates.Count}p {storageBatch.MetaData.CommitRecords.Count}c"); // ensure clock is consistent with loaded state this.Clock.Merge(storageBatch.MetaData.TimeStamp); // resume prepared transactions (not TM) foreach (var pr in loadresponse.PendingStates.OrderBy(ps => ps.TimeStamp)) { if (pr.SequenceId > loadresponse.CommittedSequenceId && pr.TransactionManager.Reference != null) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"recover two-phase-commit {pr.TransactionId}"); ParticipantId tm = pr.TransactionManager; commitQueue.Add(new TransactionRecord<TState>() { Role = CommitRole.RemoteCommit, TransactionId = Guid.Parse(pr.TransactionId), Timestamp = pr.TimeStamp, State = pr.State, SequenceNumber = pr.SequenceId, TransactionManager = tm, PrepareIsPersisted = true, LastSent = default(DateTime), ConfirmationResponsePromise = null, NumberWrites = 1 // was a writing transaction }); this.stableSequenceNumber = pr.SequenceId; } } // resume committed transactions (on TM) foreach (var kvp in storageBatch.MetaData.CommitRecords) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"recover commit confirmation {kvp.Key}"); this.confirmationWorker.Add(kvp.Key, kvp.Value.Timestamp, kvp.Value.WriteParticipants); } // check for work this.storageWorker.Notify(); this.RWLock.Notify(); } public void GetMostRecentState(out TState state, out long sequenceNumber) { if (commitQueue.Count == 0) { state = this.stableState; sequenceNumber = this.stableSequenceNumber; } else { var record = commitQueue.Last; state = record.State; sequenceNumber = record.SequenceNumber; } } public int BatchableOperationsCount() { int count = 0; int pos = commitQueue.Count - 1; while (pos >= 0 && commitQueue[pos].Batchable) { pos--; count++; } return count; } private async Task StorageWork() { // Stop if this activation is stopping/stopped. if (this.activationLifetime.OnDeactivating.IsCancellationRequested) return; using (this.activationLifetime.BlockDeactivation()) { try { // count committable entries at the bottom of the commit queue int committableEntries = 0; while (committableEntries < commitQueue.Count && commitQueue[committableEntries].ReadyToCommit) { committableEntries++; } // process all committable entries, assembling a storage batch if (committableEntries > 0) { // process all committable entries, adding storage events to the storage batch CollectEventsForBatch(committableEntries); if (logger.IsEnabled(LogLevel.Debug)) { var r = commitQueue.Count > committableEntries ? commitQueue[committableEntries].ToString() : ""; logger.Debug($"batchcommit={committableEntries} leave={commitQueue.Count - committableEntries} {r}"); } } else { // send or re-send messages and detect timeouts await CheckProgressOfCommitQueue(); } // store the current storage batch, if it is not empty StorageBatch<TState> batchBeingSentToStorage = null; if (this.storageBatch.BatchSize > 0) { // get the next batch in place so it can be filled while we store the old one batchBeingSentToStorage = this.storageBatch; this.storageBatch = new StorageBatch<TState>(batchBeingSentToStorage); try { if (await batchBeingSentToStorage.CheckStorePreConditions()) { // perform the actual store, and record the e-tag this.storageBatch.ETag = await batchBeingSentToStorage.Store(storage); failCounter = 0; } else { logger.LogWarning("Store pre conditions not met."); await AbortAndRestore(TransactionalStatus.CommitFailure, exception: null); return; } } catch (InconsistentStateException exception) { logger.LogWarning(888, exception, "Reload from storage triggered by e-tag mismatch."); await AbortAndRestore(TransactionalStatus.StorageConflict, exception, true); return; } catch (Exception exception) { logger.Warn(888, $"Storage exception in storageWorker.", exception); await AbortAndRestore(TransactionalStatus.UnknownException, exception); return; } } if (committableEntries > 0) { // update stable state var lastCommittedEntry = commitQueue[committableEntries - 1]; this.stableState = lastCommittedEntry.State; this.stableSequenceNumber = lastCommittedEntry.SequenceNumber; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace($"Stable state version: {this.stableSequenceNumber}"); // remove committed entries from commit queue commitQueue.RemoveFromFront(committableEntries); storageWorker.Notify(); // we have to re-check for work } if (batchBeingSentToStorage != null) { batchBeingSentToStorage.RunFollowUpActions(); storageWorker.Notify(); // we have to re-check for work } } catch (Exception exception) { logger.LogWarning(888, exception, "Exception in storageWorker. Retry {FailCounter}", failCounter); await AbortAndRestore(TransactionalStatus.UnknownException, exception); } } } private Task AbortAndRestore(TransactionalStatus status, Exception exception, bool force = false) { this.readyTask = Bail(status, exception, force); return this.readyTask; } private async Task Bail(TransactionalStatus status, Exception exception, bool force = false) { List<Task> pending = new List<Task>(); pending.Add(RWLock.AbortExecutingTransactions(exception)); this.RWLock.AbortQueuedTransactions(); // abort all entries in the commit queue foreach (var entry in commitQueue.Elements) { pending.Add(NotifyOfAbort(entry, status, exception: exception)); } commitQueue.Clear(); await Task.WhenAll(pending); if (++failCounter >= 10 || force) { logger.Debug("StorageWorker triggering grain Deactivation"); this.deactivate(); } await this.Restore(); } private async Task CheckProgressOfCommitQueue() { if (commitQueue.Count > 0) { var bottom = commitQueue[0]; var now = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("{CommitQueueSize} entries in queue waiting for bottom: {BottomEntry}", commitQueue.Count, bottom); switch (bottom.Role) { case CommitRole.LocalCommit: { // check for timeout periodically if (bottom.WaitingSince + this.options.PrepareTimeout <= now) { await AbortCommits(TransactionalStatus.PrepareTimeout); this.RWLock.Notify(); } else { storageWorker.Notify(bottom.WaitingSince + this.options.PrepareTimeout); } break; } case CommitRole.RemoteCommit: { if (bottom.PrepareIsPersisted && !bottom.LastSent.HasValue) { // send PreparedMessage to remote TM bottom.TransactionManager.Reference.AsReference<ITransactionManagerExtension>() .Prepared(bottom.TransactionManager.Name, bottom.TransactionId, bottom.Timestamp, resource, TransactionalStatus.Ok) .Ignore(); bottom.LastSent = now; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("sent prepared {BottomEntry}", bottom); if (bottom.IsReadOnly) { storageWorker.Notify(); // we are ready to batch now } else { storageWorker.Notify(bottom.LastSent.Value + this.options.RemoteTransactionPingFrequency); } } else if (!bottom.IsReadOnly && bottom.LastSent.HasValue) { // send ping messages periodically to reactivate crashed TMs if (bottom.LastSent + this.options.RemoteTransactionPingFrequency <= now) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("sent ping {BottomEntry}", bottom); bottom.TransactionManager.Reference.AsReference<ITransactionManagerExtension>() .Ping(bottom.TransactionManager.Name, bottom.TransactionId, bottom.Timestamp, resource).Ignore(); bottom.LastSent = now; } storageWorker.Notify(bottom.LastSent.Value + this.options.RemoteTransactionPingFrequency); } break; } default: { logger.LogError(777, "internal error: impossible case {CommitRole}", bottom.Role); throw new NotSupportedException($"{bottom.Role} is not a supported CommitRole."); } } } } private void CollectEventsForBatch(int batchsize) { // collect events for batch for (int i = 0; i < batchsize; i++) { TransactionRecord<TState> entry = commitQueue[i]; if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("committing {Entry}", entry); } switch (entry.Role) { case CommitRole.LocalCommit: { OnLocalCommit(entry); break; } case CommitRole.RemoteCommit: { if (entry.ConfirmationResponsePromise == null) { // this is a read-only participant that has sent // its prepared message. // So we are really done and need not store or do anything. } else { // we must confirm in storage, and then respond to TM so it can collect this.storageBatch.Confirm(entry.SequenceNumber); this.storageBatch.FollowUpAction(() => { entry.ConfirmationResponsePromise.TrySetResult(true); if (this.logger.IsEnabled(LogLevel.Trace)) { this.logger.Trace("Confirmed remote commit v{SequenceNumber}. TransactionId:{TransactionId} Timestamp:{Timestamp} TransactionManager:{TransactionManager}", entry.SequenceNumber, entry.TransactionId, entry.Timestamp, entry.TransactionManager); } }); } break; } case CommitRole.ReadOnly: { // we are a participant of a read-only transaction. Must store timestamp and then respond. this.storageBatch.Read(entry.Timestamp); this.storageBatch.FollowUpAction(() => { entry.PromiseForTA.TrySetResult(TransactionalStatus.Ok); }); break; } default: { logger.LogError(777, "internal error: impossible case {CommitRole}", entry.Role); throw new NotSupportedException($"{entry.Role} is not a supported CommitRole."); } } } } protected virtual void OnLocalCommit(TransactionRecord<TState> entry) { this.storageBatch.Prepare(entry.SequenceNumber, entry.TransactionId, entry.Timestamp, entry.TransactionManager, entry.State); this.storageBatch.Commit(entry.TransactionId, entry.Timestamp, entry.WriteParticipants); this.storageBatch.Confirm(entry.SequenceNumber); // after store, send response back to TA this.storageBatch.FollowUpAction(() => { if (this.logger.IsEnabled(LogLevel.Trace)) { this.logger.Trace($"locally committed {entry.TransactionId} {entry.Timestamp:o}"); } entry.PromiseForTA.TrySetResult(TransactionalStatus.Ok); }); if (entry.WriteParticipants.Count > 1) { // after committing, we need to run a task to confirm and collect this.storageBatch.FollowUpAction(() => { if (this.logger.IsEnabled(LogLevel.Trace)) { this.logger.Trace($"Adding confirmation to worker for {entry.TransactionId} {entry.Timestamp:o}"); } this.confirmationWorker.Add(entry.TransactionId, entry.Timestamp, entry.WriteParticipants); }); } else { // there are no remote write participants to notify, so we can finish it all in one shot this.storageBatch.Collect(entry.TransactionId); } } private async Task AbortCommits(TransactionalStatus status, int from = 0) { List<Task> pending = new List<Task>(); // emtpy the back of the commit queue, starting at specified position for (int i = from; i < commitQueue.Count; i++) { pending.Add(NotifyOfAbort(commitQueue[i], i == from ? status : TransactionalStatus.CascadingAbort, exception: null)); } commitQueue.RemoveFromBack(commitQueue.Count - from); pending.Add(this.RWLock.AbortExecutingTransactions(exception: null)); await Task.WhenAll(pending); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; using System; namespace Microsoft.MixedReality.Toolkit.Input { public class SimulatedHandPose { private static readonly int jointCount = Enum.GetNames(typeof(TrackedHandJoint)).Length; // TODO Right now animation is just lerping joint offsets // For better transitions, esp. when wrist is rotating, use hierarchical bone rotations! private Vector3[] jointOffsets; public SimulatedHandPose() { jointOffsets = new Vector3[jointCount]; SetZero(); } public SimulatedHandPose(Vector3[] _jointOffsets) { jointOffsets = new Vector3[jointCount]; Array.Copy(_jointOffsets, jointOffsets, jointCount); } public void ComputeJointPositions(Handedness handedness, Quaternion rotation, Vector3 position, Vector3[] jointsOut) { // Initialize from local offsets for (int i = 0; i < jointCount; i++) { jointsOut[i] = -jointOffsets[i]; } // Pose offset are for right hand, flip if left hand is needed if (handedness == Handedness.Left) { for (int i = 0; i < jointCount; i++) { jointsOut[i].x = -jointsOut[i].x; } } // Apply camera transform for (int i = 0; i < jointCount; i++) { jointsOut[i] = Camera.main.transform.TransformDirection(jointsOut[i]); } for (int i = 0; i < jointCount; i++) { jointsOut[i] = position + rotation * jointsOut[i]; } } public void ParseFromJointPositions(Vector3[] joints, Handedness handedness, Quaternion rotation, Vector3 position) { for (int i = 0; i < jointCount; i++) { jointOffsets[i] = Quaternion.Inverse(rotation) * (joints[i] - position); } // To camera space for (int i = 0; i < jointCount; i++) { jointOffsets[i] = Camera.main.transform.InverseTransformDirection(jointOffsets[i]); } // Pose offset are for right hand, flip if left hand is given if (handedness == Handedness.Left) { for (int i = 0; i < jointCount; i++) { jointOffsets[i].x = -jointOffsets[i].x; } } for (int i = 0; i < jointCount; i++) { jointOffsets[i] = -jointOffsets[i]; } } public void SetZero() { for (int i = 0; i < jointCount; i++) { jointOffsets[i] = Vector3.zero; } } public void Copy(SimulatedHandPose other) { Array.Copy(other.jointOffsets, jointOffsets, jointCount); } public void InterpolateOffsets(SimulatedHandPose poseA, SimulatedHandPose poseB, float value) { for (int i = 0; i < jointCount; i++) { jointOffsets[i] = Vector3.Lerp(poseA.jointOffsets[i], poseB.jointOffsets[i], value); } } public void TransitionTo(SimulatedHandPose other, float lastAnim, float currentAnim) { if (currentAnim <= lastAnim) { return; } float range = Mathf.Clamp01(1.0f - lastAnim); float lerpFactor = range > 0.0f ? (currentAnim - lastAnim) / range : 1.0f; for (int i = 0; i < jointCount; i++) { jointOffsets[i] = Vector3.Lerp(jointOffsets[i], other.jointOffsets[i], lerpFactor); } } public enum GestureId { None = 0, Flat, Open, Pinch, Poke, Grab, ThumbsUp, Victory, } static public SimulatedHandPose GetGesturePose(GestureId gesture) { switch (gesture) { case GestureId.None: return null; case GestureId.Flat: return HandFlat; case GestureId.Open: return HandOpened; case GestureId.Pinch: return HandPinch; case GestureId.Poke: return HandPoke; case GestureId.Grab: return HandGrab; case GestureId.ThumbsUp: return HandThumbsUp; case GestureId.Victory: return HandVictory; } return null; } public string GenerateInitializerCode() { string[] names = Enum.GetNames(typeof(TrackedHandJoint)); string s = ""; s += "new Vector3[]\n"; s += "{\n"; for (int i = 0; i < jointCount; ++i) { Vector3 v = jointOffsets[i]; s += $" new Vector3({v.x:F5}f, {v.y:F5}f, {v.z:F5}f), // {names[i]}\n"; } s += "}\n"; return s; } static private SimulatedHandPose HandOpened = new SimulatedHandPose(new Vector3[] { // Right palm is duplicate of right thumb metacarpal and right pinky metacarpal new Vector3(0.0f,0.0f,0.0f), // None new Vector3(-0.036f,0.165f,0.061f), // Wrist new Vector3(-0.036f,0.10f,0.051f), // Palm new Vector3(-0.020f,0.159f,0.061f), // ThumbMetacarpal new Vector3(0.018f,0.126f,0.047f), new Vector3(0.044f,0.107f,0.041f), new Vector3(0.063f,0.097f,0.040f), // ThumbTip new Vector3(-0.027f,0.159f,0.061f), // IndexMetacarpal new Vector3(-0.009f,0.075f,0.033f), new Vector3(-0.005f,0.036f,0.017f), new Vector3(-0.002f,0.015f,0.007f), new Vector3(0.000f,0.000f,0.000f), // IndexTip new Vector3(-0.035f,0.159f,0.061f), // MiddleMetacarpal new Vector3(-0.032f,0.073f,0.032f), new Vector3(-0.017f,0.077f,-0.002f), new Vector3(-0.017f,0.104f,-0.001f), new Vector3(-0.021f,0.119f,0.008f), new Vector3(-0.043f,0.159f,0.061f), // RingMetacarpal new Vector3(-0.055f,0.078f,0.032f), new Vector3(-0.041f,0.080f,0.001f), new Vector3(-0.037f,0.106f,0.003f), new Vector3(-0.038f,0.121f,0.012f), new Vector3(-0.050f,0.159f,0.061f), // PinkyMetacarpal new Vector3(-0.074f,0.087f,0.031f), // PinkyProximal new Vector3(-0.061f,0.084f,0.006f), // PinkyIntermediate new Vector3(-0.054f,0.101f,0.005f), // PinkyDistal new Vector3(-0.054f,0.116f,0.013f), // PinkyTip }); static private SimulatedHandPose HandFlat = new SimulatedHandPose(new Vector3[] { new Vector3(-0.06300f, 0.15441f, 0.00097f), // None new Vector3(-0.06300f, 0.15441f, 0.00097f), // Wrist new Vector3(-0.04323f, 0.08708f, -0.00732f), // Palm new Vector3(-0.04323f, 0.08708f, -0.00732f), // ThumbMetacarpalJoint new Vector3(0.00233f, 0.10868f, 0.00007f), // ThumbProximalJoint new Vector3(0.02282f, 0.08608f, 0.00143f), // ThumbDistalJoint new Vector3(0.03249f, 0.07318f, 0.00075f), // ThumbTip new Vector3(-0.06300f, 0.15441f, 0.00097f), // IndexMetacarpal new Vector3(-0.01960f, 0.06668f, 0.00068f), // IndexKnuckle new Vector3(-0.00923f, 0.02973f, 0.00216f), // IndexMiddleJoint new Vector3(-0.00289f, 0.00912f, 0.00130f), // IndexDistalJoint new Vector3(0.00075f, -0.00198f, 0.00011f), // IndexTip new Vector3(-0.06300f, 0.15441f, 0.00097f), // MiddleMetacarpal new Vector3(-0.03941f, 0.06396f, -0.00371f), // MiddleKnuckle new Vector3(-0.03483f, 0.02113f, -0.00446f), // MiddleMiddleJoint new Vector3(-0.03101f, -0.00381f, -0.00731f), // MiddleDistalJoint new Vector3(-0.02906f, -0.01649f, -0.00879f), // MiddleTip new Vector3(-0.06300f, 0.15441f, 0.00097f), // RingMetacarpal new Vector3(-0.05859f, 0.06795f, -0.01061f), // RingKnuckle new Vector3(-0.06179f, 0.02820f, -0.01284f), // RingMiddleJoint new Vector3(-0.06302f, 0.00366f, -0.01568f), // RingDistalJoint new Vector3(-0.06334f, -0.00900f, -0.01776f), // RingTip new Vector3(-0.06300f, 0.15441f, 0.00097f), // PinkyMetacarpal new Vector3(-0.07492f, 0.07446f, -0.01953f), // PinkyKnuckle new Vector3(-0.08529f, 0.04472f, -0.02228f), // PinkyMiddleJoint new Vector3(-0.08974f, 0.02819f, -0.02572f), // PinkyDistalJoint new Vector3(-0.09266f, 0.01696f, -0.02819f), // PinkyTip }); static private SimulatedHandPose HandPinch = new SimulatedHandPose(new Vector3[] { // Right palm is duplicate of right thumb metacarpal and right pinky metacarpal new Vector3(0.0f,0.0f,0.0f), // None new Vector3(-0.042f,0.111f,0.060f), // Wrist new Vector3(-0.042f,0.051f,0.060f), // Palm new Vector3(-0.032f,0.091f,0.060f), // ThumbMetacarpal new Vector3(-0.013f,0.052f,0.044f), new Vector3(0.002f,0.026f,0.030f), new Vector3(0.007f,0.007f,0.017f), // ThumbTip new Vector3(-0.038f,0.091f,0.060f), // IndexMetacarpal new Vector3(-0.029f,0.008f,0.050f), new Vector3(-0.009f,-0.016f,0.025f), new Vector3(-0.002f,-0.011f,0.008f), new Vector3(0.000f,0.000f,0.000f), new Vector3(-0.042f,0.091f,0.060f), // MiddleMetacarpal new Vector3(-0.050f,0.004f,0.046f), new Vector3(-0.026f,0.004f,0.014f), new Vector3(-0.028f,0.031f,0.014f), new Vector3(-0.034f,0.048f,0.020f), new Vector3(-0.048f,0.091f,0.060f), // RingMetacarpal new Vector3(-0.071f,0.008f,0.041f), new Vector3(-0.048f,0.009f,0.012f), new Vector3(-0.046f,0.036f,0.014f), new Vector3(-0.050f,0.052f,0.022f), new Vector3(-0.052f,0.091f,0.060f), // PinkyMetacarpal new Vector3(-0.088f,0.014f,0.034f), new Vector3(-0.067f,0.012f,0.013f), new Vector3(-0.061f,0.031f,0.014f), new Vector3(-0.062f,0.046f,0.021f), }); static private SimulatedHandPose HandPoke = new SimulatedHandPose(new Vector3[] { new Vector3(-0.06209f, 0.07595f, 0.07231f), // None new Vector3(-0.06209f, 0.07595f, 0.07231f), // Wrist new Vector3(-0.03259f, 0.03268f, 0.02552f), // Palm new Vector3(-0.03259f, 0.03268f, 0.02552f), // ThumbMetacarpalJoint new Vector3(-0.00118f, 0.05920f, 0.03279f), // ThumbProximalJoint new Vector3(0.00171f, 0.05718f, 0.00273f), // ThumbDistalJoint new Vector3(-0.00877f, 0.05977f, -0.00905f), // ThumbTip new Vector3(-0.06209f, 0.07595f, 0.07231f), // IndexMetacarpal new Vector3(-0.00508f, 0.01676f, 0.02067f), // IndexKnuckle new Vector3(0.00320f, -0.00908f, -0.00469f), // IndexMiddleJoint new Vector3(0.00987f, -0.01695f, -0.02251f), // IndexDistalJoint new Vector3(0.01363f, -0.02002f, -0.03255f), // IndexTip new Vector3(-0.06209f, 0.07595f, 0.07231f), // MiddleMetacarpal new Vector3(-0.02474f, 0.01422f, 0.01270f), // MiddleKnuckle new Vector3(-0.00556f, 0.03787f, -0.01700f), // MiddleMiddleJoint new Vector3(-0.00648f, 0.06095f, -0.00658f), // MiddleDistalJoint new Vector3(-0.01209f, 0.06180f, 0.00499f), // MiddleTip new Vector3(-0.06209f, 0.07595f, 0.07231f), // RingMetacarpal new Vector3(-0.04422f, 0.01955f, 0.00797f), // RingKnuckle new Vector3(-0.02535f, 0.04385f, -0.01667f), // RingMiddleJoint new Vector3(-0.02465f, 0.06521f, -0.00440f), // RingDistalJoint new Vector3(-0.02953f, 0.06711f, 0.00726f), // RingTip new Vector3(-0.06209f, 0.07595f, 0.07231f), // PinkyMetacarpal new Vector3(-0.06218f, 0.02740f, 0.00434f), // PinkyKnuckle new Vector3(-0.04335f, 0.04456f, -0.01437f), // PinkyMiddleJoint new Vector3(-0.03864f, 0.06018f, -0.00822f), // PinkyDistalJoint new Vector3(-0.04340f, 0.06202f, 0.00248f), // PinkyTip }); static private SimulatedHandPose HandGrab = new SimulatedHandPose(new Vector3[] { new Vector3(-0.05340f, 0.02059f, 0.05460f), // None new Vector3(-0.05340f, 0.02059f, 0.05460f), // Wrist new Vector3(-0.02248f, -0.03254f, 0.01987f), // Palm new Vector3(-0.02248f, -0.03254f, 0.01987f), // ThumbMetacarpalJoint new Vector3(0.01379f, -0.00633f, 0.02738f), // ThumbProximalJoint new Vector3(0.02485f, -0.02278f, 0.00441f), // ThumbDistalJoint new Vector3(0.01847f, -0.02790f, -0.00937f), // ThumbTip new Vector3(-0.05340f, 0.02059f, 0.05460f), // IndexMetacarpal new Vector3(0.00565f, -0.04883f, 0.01896f), // IndexKnuckle new Vector3(0.01153f, -0.02915f, -0.01358f), // IndexMiddleJoint new Vector3(0.00547f, -0.00864f, -0.01074f), // IndexDistalJoint new Vector3(0.00098f, -0.00265f, -0.00172f), // IndexTip new Vector3(-0.05340f, 0.02059f, 0.05460f), // MiddleMetacarpal new Vector3(-0.01343f, -0.05324f, 0.01296f), // MiddleKnuckle new Vector3(-0.00060f, -0.03063f, -0.02099f), // MiddleMiddleJoint new Vector3(-0.00567f, -0.00696f, -0.01334f), // MiddleDistalJoint new Vector3(-0.01080f, -0.00381f, -0.00193f), // MiddleTip new Vector3(-0.05340f, 0.02059f, 0.05460f), // RingMetacarpal new Vector3(-0.03363f, -0.05134f, 0.00849f), // RingKnuckle new Vector3(-0.02000f, -0.02888f, -0.02123f), // RingMiddleJoint new Vector3(-0.02304f, -0.00675f, -0.01062f), // RingDistalJoint new Vector3(-0.02754f, -0.00310f, 0.00082f), // RingTip new Vector3(-0.05340f, 0.02059f, 0.05460f), // PinkyMetacarpal new Vector3(-0.05225f, -0.04629f, 0.00384f), // PinkyKnuckle new Vector3(-0.03698f, -0.03051f, -0.01900f), // PinkyMiddleJoint new Vector3(-0.03617f, -0.01485f, -0.01130f), // PinkyDistalJoint new Vector3(-0.03902f, -0.00873f, -0.00159f), // PinkyTip }); static private SimulatedHandPose HandThumbsUp = new SimulatedHandPose(new Vector3[] { new Vector3(-0.05754f, 0.04969f, -0.01566f), // None new Vector3(-0.05754f, 0.04969f, -0.01566f), // Wrist new Vector3(0.00054f, 0.01716f, -0.03472f), // Palm new Vector3(0.00054f, 0.01716f, -0.03472f), // ThumbMetacarpalJoint new Vector3(-0.03106f, -0.02225f, -0.00120f), // ThumbProximalJoint new Vector3(-0.02123f, -0.04992f, 0.00199f), // ThumbDistalJoint new Vector3(-0.01793f, -0.06510f, 0.00358f), // ThumbTip new Vector3(-0.05754f, 0.04969f, -0.01566f), // IndexMetacarpal new Vector3(0.01284f, -0.01185f, -0.03795f), // IndexKnuckle new Vector3(0.03290f, -0.00608f, -0.00720f), // IndexMiddleJoint new Vector3(0.01647f, 0.00258f, 0.00238f), // IndexDistalJoint new Vector3(0.00559f, 0.00502f, 0.00017f), // IndexTip new Vector3(-0.05754f, 0.04969f, -0.01566f), // MiddleMetacarpal new Vector3(0.01777f, 0.00604f, -0.04572f), // MiddleKnuckle new Vector3(0.03731f, 0.00686f, -0.00898f), // MiddleMiddleJoint new Vector3(0.01713f, 0.01536f, 0.00219f), // MiddleDistalJoint new Vector3(0.00542f, 0.01846f, -0.00091f), // MiddleTip new Vector3(-0.05754f, 0.04969f, -0.01566f), // RingMetacarpal new Vector3(0.01836f, 0.02624f, -0.04858f), // RingKnuckle new Vector3(0.03987f, 0.02388f, -0.01663f), // RingMiddleJoint new Vector3(0.02182f, 0.02969f, -0.00200f), // RingDistalJoint new Vector3(0.00978f, 0.03257f, -0.00310f), // RingTip new Vector3(-0.05754f, 0.04969f, -0.01566f), // PinkyMetacarpal new Vector3(0.01784f, 0.04561f, -0.04763f), // PinkyKnuckle new Vector3(0.03771f, 0.03986f, -0.02511f), // PinkyMiddleJoint new Vector3(0.02634f, 0.04067f, -0.01262f), // PinkyDistalJoint new Vector3(0.01505f, 0.04267f, -0.01241f), // PinkyTip }); static private SimulatedHandPose HandVictory = new SimulatedHandPose(new Vector3[] { new Vector3(-0.08835f, 0.13334f, 0.02745f), // None new Vector3(-0.08835f, 0.13334f, 0.02745f), // Wrist new Vector3(-0.05800f, 0.07626f, 0.00397f), // Palm new Vector3(-0.05800f, 0.07626f, 0.00397f), // ThumbMetacarpalJoint new Vector3(-0.03418f, 0.10243f, -0.00761f), // ThumbProximalJoint new Vector3(-0.03570f, 0.08857f, -0.03347f), // ThumbDistalJoint new Vector3(-0.04603f, 0.08584f, -0.04472f), // ThumbTip new Vector3(-0.08835f, 0.13334f, 0.02745f), // IndexMetacarpal new Vector3(-0.03200f, 0.05950f, 0.00836f), // IndexKnuckle new Vector3(-0.01535f, 0.02702f, 0.00475f), // IndexMiddleJoint new Vector3(-0.00577f, 0.00904f, 0.00218f), // IndexDistalJoint new Vector3(-0.00046f, -0.00064f, 0.00053f), // IndexTip new Vector3(-0.08835f, 0.13334f, 0.02745f), // MiddleMetacarpal new Vector3(-0.05017f, 0.05484f, 0.00171f), // MiddleKnuckle new Vector3(-0.04307f, 0.01754f, -0.01398f), // MiddleMiddleJoint new Vector3(-0.03889f, -0.00439f, -0.02321f), // MiddleDistalJoint new Vector3(-0.03677f, -0.01553f, -0.02789f), // MiddleTip new Vector3(-0.08835f, 0.13334f, 0.02745f), // RingMetacarpal new Vector3(-0.06885f, 0.05706f, -0.00568f), // RingKnuckle new Vector3(-0.05015f, 0.04311f, -0.03622f), // RingMiddleJoint new Vector3(-0.04307f, 0.06351f, -0.04646f), // RingDistalJoint new Vector3(-0.04840f, 0.07039f, -0.03760f), // RingTip new Vector3(-0.08835f, 0.13334f, 0.02745f), // PinkyMetacarpal new Vector3(-0.08544f, 0.06253f, -0.01371f), // PinkyKnuckle new Vector3(-0.06657f, 0.07318f, -0.03519f), // PinkyMiddleJoint new Vector3(-0.06393f, 0.08967f, -0.03293f), // PinkyDistalJoint new Vector3(-0.06748f, 0.09752f, -0.02542f), // PinkyTip }); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SubtractScalarSingle() { var test = new SimpleBinaryOpTest__SubtractScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractScalarSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static SimpleBinaryOpTest__SubtractScalarSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__SubtractScalarSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.SubtractScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.SubtractScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.SubtractScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.SubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.SubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.SubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.SubtractScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.SubtractScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.SubtractScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.SubtractScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractScalarSingle(); var result = Sse.SubtractScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.SubtractScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(left[0] - right[0]) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.SubtractScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>ClickView</c> resource.</summary> public sealed partial class ClickViewName : gax::IResourceName, sys::IEquatable<ClickViewName> { /// <summary>The possible contents of <see cref="ClickViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/clickViews/{date}~{gclid}</c>. /// </summary> CustomerDateGclid = 1, } private static gax::PathTemplate s_customerDateGclid = new gax::PathTemplate("customers/{customer_id}/clickViews/{date_gclid}"); /// <summary>Creates a <see cref="ClickViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ClickViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ClickViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ClickViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ClickViewName"/> with the pattern <c>customers/{customer_id}/clickViews/{date}~{gclid}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dateId">The <c>Date</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="gclidId">The <c>Gclid</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ClickViewName"/> constructed from the provided ids.</returns> public static ClickViewName FromCustomerDateGclid(string customerId, string dateId, string gclidId) => new ClickViewName(ResourceNameType.CustomerDateGclid, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), dateId: gax::GaxPreconditions.CheckNotNullOrEmpty(dateId, nameof(dateId)), gclidId: gax::GaxPreconditions.CheckNotNullOrEmpty(gclidId, nameof(gclidId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ClickViewName"/> with pattern /// <c>customers/{customer_id}/clickViews/{date}~{gclid}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dateId">The <c>Date</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="gclidId">The <c>Gclid</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ClickViewName"/> with pattern /// <c>customers/{customer_id}/clickViews/{date}~{gclid}</c>. /// </returns> public static string Format(string customerId, string dateId, string gclidId) => FormatCustomerDateGclid(customerId, dateId, gclidId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ClickViewName"/> with pattern /// <c>customers/{customer_id}/clickViews/{date}~{gclid}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dateId">The <c>Date</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="gclidId">The <c>Gclid</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ClickViewName"/> with pattern /// <c>customers/{customer_id}/clickViews/{date}~{gclid}</c>. /// </returns> public static string FormatCustomerDateGclid(string customerId, string dateId, string gclidId) => s_customerDateGclid.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(dateId, nameof(dateId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(gclidId, nameof(gclidId)))}"); /// <summary>Parses the given resource name string into a new <see cref="ClickViewName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/clickViews/{date}~{gclid}</c></description></item> /// </list> /// </remarks> /// <param name="clickViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ClickViewName"/> if successful.</returns> public static ClickViewName Parse(string clickViewName) => Parse(clickViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ClickViewName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/clickViews/{date}~{gclid}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="clickViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ClickViewName"/> if successful.</returns> public static ClickViewName Parse(string clickViewName, bool allowUnparsed) => TryParse(clickViewName, allowUnparsed, out ClickViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ClickViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/clickViews/{date}~{gclid}</c></description></item> /// </list> /// </remarks> /// <param name="clickViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ClickViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string clickViewName, out ClickViewName result) => TryParse(clickViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ClickViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/clickViews/{date}~{gclid}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="clickViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ClickViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string clickViewName, bool allowUnparsed, out ClickViewName result) { gax::GaxPreconditions.CheckNotNull(clickViewName, nameof(clickViewName)); gax::TemplatedResourceName resourceName; if (s_customerDateGclid.TryParseName(clickViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerDateGclid(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(clickViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private ClickViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string dateId = null, string gclidId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; DateId = dateId; GclidId = gclidId; } /// <summary> /// Constructs a new instance of a <see cref="ClickViewName"/> class from the component parts of pattern /// <c>customers/{customer_id}/clickViews/{date}~{gclid}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dateId">The <c>Date</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="gclidId">The <c>Gclid</c> ID. Must not be <c>null</c> or empty.</param> public ClickViewName(string customerId, string dateId, string gclidId) : this(ResourceNameType.CustomerDateGclid, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), dateId: gax::GaxPreconditions.CheckNotNullOrEmpty(dateId, nameof(dateId)), gclidId: gax::GaxPreconditions.CheckNotNullOrEmpty(gclidId, nameof(gclidId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Date</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DateId { get; } /// <summary> /// The <c>Gclid</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string GclidId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerDateGclid: return s_customerDateGclid.Expand(CustomerId, $"{DateId}~{GclidId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ClickViewName); /// <inheritdoc/> public bool Equals(ClickViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ClickViewName a, ClickViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ClickViewName a, ClickViewName b) => !(a == b); } public partial class ClickView { /// <summary> /// <see cref="ClickViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal ClickViewName ResourceNameAsClickViewName { get => string.IsNullOrEmpty(ResourceName) ? null : ClickViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupAdName"/>-typed view over the <see cref="AdGroupAd"/> resource name property. /// </summary> internal AdGroupAdName AdGroupAdAsAdGroupAdName { get => string.IsNullOrEmpty(AdGroupAd) ? null : AdGroupAdName.Parse(AdGroupAd, allowUnparsed: true); set => AdGroupAd = value?.ToString() ?? ""; } /// <summary> /// <see cref="GeoTargetConstantName"/>-typed view over the <see cref="CampaignLocationTarget"/> resource name /// property. /// </summary> internal GeoTargetConstantName CampaignLocationTargetAsGeoTargetConstantName { get => string.IsNullOrEmpty(CampaignLocationTarget) ? null : GeoTargetConstantName.Parse(CampaignLocationTarget, allowUnparsed: true); set => CampaignLocationTarget = value?.ToString() ?? ""; } /// <summary> /// <see cref="UserListName"/>-typed view over the <see cref="UserList"/> resource name property. /// </summary> internal UserListName UserListAsUserListName { get => string.IsNullOrEmpty(UserList) ? null : UserListName.Parse(UserList, allowUnparsed: true); set => UserList = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupCriterionName"/>-typed view over the <see cref="Keyword"/> resource name property. /// </summary> internal AdGroupCriterionName KeywordAsAdGroupCriterionName { get => string.IsNullOrEmpty(Keyword) ? null : AdGroupCriterionName.Parse(Keyword, allowUnparsed: true); set => Keyword = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Engine.Maps; using Signum.Engine.DynamicQuery; using Signum.Entities.Processes; using Signum.Entities; using Signum.Engine.Operations; using Signum.Engine.Authorization; using Signum.Utilities; using System.Threading; using Signum.Entities.Basics; using Signum.Engine.Basics; using System.Reflection; using Signum.Utilities.Reflection; using Signum.Entities.Authorization; using System.Linq.Expressions; namespace Signum.Engine.Processes { public static class ProcessLogic { public static bool JustMyProcesses = true; public static Func<ProcessEntity, IDisposable?>? ApplySession; [AutoExpressionField] public static IQueryable<ProcessEntity> Processes(this ProcessAlgorithmSymbol p) => As.Expression(() => Database.Query<ProcessEntity>().Where(a => a.Algorithm == p)); [AutoExpressionField] public static ProcessEntity? LastProcess(this ProcessAlgorithmSymbol p) => As.Expression(() => p.Processes().OrderByDescending(a => a.ExecutionStart).FirstOrDefault()); [AutoExpressionField] public static IQueryable<ProcessExceptionLineEntity> ExceptionLines(this ProcessEntity p) => As.Expression(() => Database.Query<ProcessExceptionLineEntity>().Where(a => a.Process.Is(p))); [AutoExpressionField] public static IQueryable<ProcessExceptionLineEntity> ExceptionLines(this IProcessLineDataEntity pl) => As.Expression(() => Database.Query<ProcessExceptionLineEntity>().Where(a => a.Line.Is(pl))); [AutoExpressionField] public static ExceptionEntity? Exception(this IProcessLineDataEntity pl, ProcessEntity p) => As.Expression(() => p.ExceptionLines().SingleOrDefault(el => el.Line.Is(pl))!.Exception.Entity); [AutoExpressionField] public static IQueryable<ProcessEntity> Processes(this IProcessDataEntity e) => As.Expression(() => Database.Query<ProcessEntity>().Where(a => a.Data == e)); [AutoExpressionField] public static ProcessEntity? LastProcess(this IProcessDataEntity e) => As.Expression(() => e.Processes().OrderByDescending(a => a.ExecutionStart).FirstOrDefault()); static Dictionary<ProcessAlgorithmSymbol, IProcessAlgorithm> registeredProcesses = new Dictionary<ProcessAlgorithmSymbol, IProcessAlgorithm>(); public static void AssertStarted(SchemaBuilder sb) { sb.AssertDefined(ReflectionTools.GetMethodInfo(() => ProcessLogic.Start(null!))); } public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Include<ProcessAlgorithmSymbol>() .WithQuery(() => pa => new { Entity = pa, pa.Id, pa.Key }); sb.Include<ProcessEntity>() .WithQuery(() => p => new { Entity = p, p.Id, p.Algorithm, p.Data, p.State, p.MachineName, p.ApplicationName, p.CreationDate, p.PlannedDate, p.CancelationDate, p.QueuedDate, p.ExecutionStart, p.ExecutionEnd, p.SuspendDate, p.ExceptionDate, }); sb.Include<ProcessExceptionLineEntity>() .WithQuery(() => p => new { Entity = p, p.Process, p.Line, ((PackageLineEntity)p.Line!.Entity).Target, ((PackageLineEntity)p.Line!.Entity).Result, p.ElementInfo, p.Exception, }); PermissionAuthLogic.RegisterPermissions(ProcessPermission.ViewProcessPanel); SymbolLogic<ProcessAlgorithmSymbol>.Start(sb, () => registeredProcesses.Keys.ToHashSet()); OperationLogic.AssertStarted(sb); ProcessGraph.Register(); QueryLogic.Expressions.Register((ProcessAlgorithmSymbol p) => p.Processes(), () => typeof(ProcessEntity).NicePluralName()); QueryLogic.Expressions.Register((ProcessAlgorithmSymbol p) => p.LastProcess(), () => ProcessMessage.LastProcess.NiceToString()); QueryLogic.Expressions.Register((IProcessDataEntity p) => p.Processes(), () => typeof(ProcessEntity).NicePluralName()); QueryLogic.Expressions.Register((IProcessDataEntity p) => p.LastProcess(), () => ProcessMessage.LastProcess.NiceToString()); QueryLogic.Expressions.Register((ProcessEntity p) => p.ExceptionLines(), () => ProcessMessage.ExceptionLines.NiceToString()); QueryLogic.Expressions.Register((IProcessLineDataEntity p) => p.ExceptionLines(), () => ProcessMessage.ExceptionLines.NiceToString()); PropertyAuthLogic.SetMaxAutomaticUpgrade(PropertyRoute.Construct((ProcessEntity p) => p.User), PropertyAllowed.Read); ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs; } } public static void ExceptionLogic_DeleteLogs(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token) { void Remove(ProcessState processState, DateTime dateLimit, bool withExceptions) { var query = Database.Query<ProcessEntity>().Where(p => p.State == processState && p.CreationDate < dateLimit); if (withExceptions) query = query.Where(p => p.Exception != null); query.SelectMany(a => a.ExceptionLines()).UnsafeDeleteChunksLog(parameters, sb, token); query.Where(a => !a.ExceptionLines().Any()).UnsafeDeleteChunksLog(parameters, sb, token); } var dateLimit = parameters.GetDateLimitDelete(typeof(ProcessEntity).ToTypeEntity()); if (dateLimit != null) { Remove(ProcessState.Canceled, dateLimit.Value, withExceptions: false); Remove(ProcessState.Finished, dateLimit.Value, withExceptions: false); Remove(ProcessState.Error, dateLimit.Value, withExceptions: false); } dateLimit = parameters.GetDateLimitDeleteWithExceptions(typeof(ProcessEntity).ToTypeEntity()); if (dateLimit != null) { Remove(ProcessState.Canceled, dateLimit.Value, withExceptions: true); Remove(ProcessState.Finished, dateLimit.Value, withExceptions: true); Remove(ProcessState.Error, dateLimit.Value, withExceptions: true); } } public static IDisposable? OnApplySession(ProcessEntity process) { return Disposable.Combine(ApplySession, f => f(process)); } public static void Register(ProcessAlgorithmSymbol processAlgorithm, Action<ExecutingProcess> action) => Register(processAlgorithm, new ActionProcessAlgorithm(action)); public static void Register(ProcessAlgorithmSymbol processAlgorithm, IProcessAlgorithm algorithm) { if (processAlgorithm == null) throw AutoInitAttribute.ArgumentNullException(typeof(ProcessAlgorithmSymbol), nameof(processAlgorithm)); if (algorithm == null) throw new ArgumentNullException(nameof(algorithm)); registeredProcesses.Add(processAlgorithm, algorithm); } public class ProcessGraph : Graph<ProcessEntity, ProcessState> { public static void Register() { GetState = e => e.State; new Execute(ProcessOperation.Save) { FromStates = { ProcessState.Created }, ToStates = { ProcessState.Created }, CanBeNew = true, CanBeModified = true, Execute = (p, args) => { p.Save(); } }.Register(); new Execute(ProcessOperation.Plan) { FromStates = { ProcessState.Created, ProcessState.Canceled, ProcessState.Planned, ProcessState.Suspended }, ToStates = { ProcessState.Planned }, Execute = (p, args) => { p.MachineName = JustMyProcesses ? Environment.MachineName : ProcessEntity.None; p.ApplicationName = JustMyProcesses ? Schema.Current.ApplicationName : ProcessEntity.None; p.State = ProcessState.Planned; p.PlannedDate = args.GetArg<DateTime>(); } }.Register(); new Execute(ProcessOperation.Cancel) { FromStates = { ProcessState.Planned, ProcessState.Created, ProcessState.Suspended, ProcessState.Queued, ProcessState.Executing, ProcessState.Suspending }, ToStates = { ProcessState.Canceled }, Execute = (p, _) => { p.State = ProcessState.Canceled; p.CancelationDate = TimeZoneManager.Now; } }.Register(); new Execute(ProcessOperation.Execute) { FromStates = { ProcessState.Created, ProcessState.Planned, ProcessState.Canceled, ProcessState.Suspended }, ToStates = { ProcessState.Queued }, Execute = (p, _) => { p.MachineName = JustMyProcesses ? Environment.MachineName : ProcessEntity.None; p.ApplicationName = JustMyProcesses ? Schema.Current.ApplicationName : ProcessEntity.None; p.SetAsQueued(); ProcessRunnerLogic.WakeUp("Execute in this machine", null); } }.Register(); new Execute(ProcessOperation.Suspend) { FromStates = { ProcessState.Executing }, ToStates = { ProcessState.Suspending }, Execute = (p, _) => { p.State = ProcessState.Suspending; p.SuspendDate = TimeZoneManager.Now; } }.Register(); new ConstructFrom<ProcessEntity>(ProcessOperation.Retry) { CanConstruct = p => p.State.InState(ProcessState.Error, ProcessState.Canceled, ProcessState.Finished, ProcessState.Suspended), ToStates = { ProcessState.Created }, Construct = (p, _) => p.Algorithm.Create(p.Data, p) }.Register(); } } public static ProcessEntity Create(this ProcessAlgorithmSymbol process, IProcessDataEntity? processData, Entity? copyMixinsFrom = null) { using (OperationLogic.AllowSave<ProcessEntity>()) { var result = new ProcessEntity(process) { State = ProcessState.Created, Data = processData, MachineName = JustMyProcesses ? Environment.MachineName : ProcessEntity.None, ApplicationName = JustMyProcesses ? Schema.Current.ApplicationName : ProcessEntity.None, User = UserHolder.Current.ToLite(), }; if (copyMixinsFrom != null) process.CopyMixinsFrom(copyMixinsFrom); return result.Save(); } } public static void ExecuteTest(this ProcessEntity p, bool writeToConsole = false) { p.QueuedDate = TimeZoneManager.Now; var ep = new ExecutingProcess(GetProcessAlgorithm(p.Algorithm), p) { WriteToConsole = writeToConsole }; ep.TakeForThisMachine(); ep.Execute(); } public static IProcessAlgorithm GetProcessAlgorithm(ProcessAlgorithmSymbol processAlgorithm) { return registeredProcesses.GetOrThrow(processAlgorithm, "The process algorithm {0} is not registered"); } public static void ForEachLine<T>(this ExecutingProcess executingProcess, IQueryable<T> remainingLines, Action<T> action, int groupsOf = 100) where T : Entity, IProcessLineDataEntity, new() { var remainingNotExceptionsLines = remainingLines.Where(li => li.Exception(executingProcess.CurrentProcess) == null); var totalCount = remainingNotExceptionsLines.Count(); int j = 0; while (true) { List<T> lines = remainingNotExceptionsLines.Take(groupsOf).ToList(); if (lines.IsEmpty()) return; for (int i = 0; i < lines.Count; i++) { executingProcess.CancellationToken.ThrowIfCancellationRequested(); T pl = lines[i]; using (HeavyProfiler.Log("ProcessLine", () => pl.ToString())) { try { Transaction.ForceNew().EndUsing(tr => { action(pl); tr.Commit(); }); } catch (Exception e) { if (Transaction.InTestTransaction) throw; var exLog = e.LogException(); Transaction.ForceNew().EndUsing(tr => { new ProcessExceptionLineEntity { Exception = exLog.ToLite(), Line = pl.ToLite(), Process = executingProcess.CurrentProcess.ToLite() }.Save(); tr.Commit(); }); } executingProcess.ProgressChanged(j++, totalCount); } } } } public static void ForEach<T>(this ExecutingProcess executingProcess, List<T> collection, Func<T, string> elementInfo, Action<T> action, string? status = null) { if (executingProcess == null) { collection.ProgressForeach(elementInfo, action); } else { executingProcess.ForEachNonTransactional(collection, elementInfo, item => { using (Transaction tr = Transaction.ForceNew()) { action(item); tr.Commit(); } }, status); } } public static void ForEachNonTransactional<T>(this ExecutingProcess executingProcess, List<T> collection, Func<T, string> elementInfo, Action<T> action, string? status = null) { if (executingProcess == null) { collection.ProgressForeach(elementInfo, action, transactional: false); } else { var totalCount = collection.Count; int j = 0; foreach (var item in collection) { executingProcess.CancellationToken.ThrowIfCancellationRequested(); using (HeavyProfiler.Log("ProgressForeach", () => elementInfo(item))) { try { action(item); } catch (Exception e) { if (Transaction.InTestTransaction) throw; var exLog = e.LogException(); Transaction.ForceNew().EndUsing(tr => { new ProcessExceptionLineEntity { Exception = exLog.ToLite(), ElementInfo = elementInfo(item), Process = executingProcess.CurrentProcess.ToLite() }.Save(); tr.Commit(); }); } executingProcess.ProgressChanged(j++, totalCount, status); } } } } public static void Synchronize<K, N, O>(this ExecutingProcess ep, Dictionary<K, N> newDictionary, Dictionary<K, O> oldDictionary, Action<K, N> createNew, Action<K, O> removeOld, Action<K, N, O> merge) where K : notnull { HashSet<K> keys = new HashSet<K>(); keys.UnionWith(oldDictionary.Keys); keys.UnionWith(newDictionary.Keys); foreach (var key in keys) { var oldExists = oldDictionary.TryGetValue(key, out var oldVal); var newExists = newDictionary.TryGetValue(key, out var newVal); if (!oldExists) { createNew?.Invoke(key, newVal!); } else if (!newExists) { removeOld?.Invoke(key, oldVal!); } else { merge?.Invoke(key, newVal!, oldVal!); } } } public static void WriteLineColor(this ExecutingProcess? ep, ConsoleColor color, string? str) { if (ep != null) { ep.WriteMessage(str); } else { if (!Console.IsOutputRedirected) { SafeConsole.WriteLineColor(color, str); } } } public static void SynchronizeProgressForeach<K, N, O>(this ExecutingProcess ep, Dictionary<K, N> newDictionary, Dictionary<K, O> oldDictionary, Action<K, N> createNew, Action<K, O> removeOld, Action<K, N, O> merge, string? status = null) where O : class where N : class where K : notnull { if (ep == null) { ep.WriteLineColor(ConsoleColor.Green, status); Synchronizer.SynchronizeProgressForeach(newDictionary, oldDictionary, createNew, removeOld, merge); } else { HashSet<K> keys = new HashSet<K>(); keys.UnionWith(oldDictionary.Keys); keys.UnionWith(newDictionary.Keys); ep.ForEach(keys.ToList(), key => key.ToString()!, key => { var oldVal = oldDictionary.TryGetC(key); var newVal = newDictionary.TryGetC(key); if (oldVal == null) { createNew?.Invoke(key, newVal!); } else if (newVal == null) { removeOld?.Invoke(key, oldVal); } else { merge?.Invoke(key, newVal, oldVal); } }, status); } } public static void SynchronizeProgressForeachNonTransactional<K, N, O>(this ExecutingProcess ep, Dictionary<K, N> newDictionary, Dictionary<K, O> oldDictionary, Action<K, N> createNew, Action<K, O> removeOld, Action<K, N, O> merge) where O : class where N : class where K : notnull { if (ep == null) Synchronizer.SynchronizeProgressForeach(newDictionary, oldDictionary, createNew, removeOld, merge, transactional: false); else { HashSet<K> keys = new HashSet<K>(); keys.UnionWith(oldDictionary.Keys); keys.UnionWith(newDictionary.Keys); ep.ForEachNonTransactional(keys.ToList(), key => key.ToString()!, key => { var oldVal = oldDictionary.TryGetC(key); var newVal = newDictionary.TryGetC(key); if (oldVal == null) { createNew?.Invoke(key, newVal!); } else if (newVal == null) { removeOld?.Invoke(key, oldVal); } else { merge?.Invoke(key, newVal, oldVal); } }); } } } public interface IProcessAlgorithm { void Execute(ExecutingProcess executingProcess); } public class ActionProcessAlgorithm : IProcessAlgorithm { Action<ExecutingProcess> Action; public ActionProcessAlgorithm(Action<ExecutingProcess> action) { Action = action ?? throw new ArgumentNullException(nameof(action)); } public void Execute(ExecutingProcess executingProcess) => Action(executingProcess); } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #pragma warning disable 1634, 1691 #pragma warning disable 56506 namespace System.Management.Automation.Runspaces { /// <summary> /// Define class for runspace configuration entry. /// </summary> /// <remarks> /// This abstract class is to be derived internally by Monad for different /// runspace configuration entries only. Developers should not derive from /// this class. /// </remarks> #if CORECLR internal #else public #endif abstract class RunspaceConfigurationEntry { /// <summary> /// Initiate an instance of runspace configuration entry. /// </summary> /// <param name="name">Name for the runspace configuration entry</param> /// <!-- /// This is meant to be called by derived class only. It doesn't make sense to /// directly create an instance of this class. /// --> protected RunspaceConfigurationEntry(string name) { if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(name.Trim())) { throw PSTraceSource.NewArgumentNullException("name"); } Name = name.Trim(); } /// <summary> /// Initiate an instance of runspace configuration entry. /// </summary> /// <param name="name">Name for the runspace configuration entry</param> /// <param name="psSnapin">The name of the PSSnapin the entry comes from.</param> /// <!-- /// This is meant to be called by derived class only. It doesn't make sense to /// directly create an instance of this class. /// --> internal RunspaceConfigurationEntry(string name, PSSnapInInfo psSnapin) { if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(name.Trim())) { throw PSTraceSource.NewArgumentNullException("name"); } Name = name.Trim(); if (psSnapin == null) { throw PSTraceSource.NewArgumentException("psSnapin"); } PSSnapIn = psSnapin; } /// <summary> /// Gets name of configuration entry /// </summary> public string Name { get; } /// <summary> /// Gets name of PSSnapin that this configuration entry belongs to. /// </summary> public PSSnapInInfo PSSnapIn { get; } = null; internal bool _builtIn = false; /// <summary> /// Get whether this entry is a built-in entry. /// </summary> public bool BuiltIn { get { return _builtIn; } } internal UpdateAction _action = UpdateAction.None; internal UpdateAction Action { get { return _action; } } } /// <summary> /// Defines class for type configuration entry. /// </summary> #if CORECLR internal #else public #endif sealed class TypeConfigurationEntry : RunspaceConfigurationEntry { /// <summary> /// Initiate an instance for type configuration entry. /// </summary> /// <param name="name">Name of the type configuration entry</param> /// <param name="fileName">File name that contains the types configuration information.</param> /// <exception cref="ArgumentException">when <paramref name="fileName"/> is null or empty</exception> public TypeConfigurationEntry(string name, string fileName) : base(name) { if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileName.Trim())) { throw PSTraceSource.NewArgumentException("fileName"); } FileName = fileName.Trim(); } /// <summary> /// Initiate an instance for type configuration entry. /// </summary> /// <param name="typeData">TypeData instance</param> /// <param name="isRemove">Specify the operation with the typedata</param> public TypeConfigurationEntry(TypeData typeData, bool isRemove) : base("*") { if (typeData == null) { throw PSTraceSource.NewArgumentException("typeData"); } TypeData = typeData; IsRemove = isRemove; } /// <summary> /// Initiate an instance for type configuration entry. /// </summary> /// <param name="name">Name of the type configuration entry</param> /// <param name="fileName">File name that contains the types configuration information.</param> /// <param name="psSnapinInfo">PSSnapin from which type info comes.</param> /// <exception cref="ArgumentException">when <paramref name="fileName"/> is null, empty or does not end in .ps1xml</exception> internal TypeConfigurationEntry(string name, string fileName, PSSnapInInfo psSnapinInfo) : base(name, psSnapinInfo) { if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileName.Trim())) { throw PSTraceSource.NewArgumentException("fileName"); } FileName = fileName.Trim(); } /// <summary> /// Initiate an instance for type configuration entry. /// </summary> /// <param name="fileName">File name that contains the types configuration information.</param> /// <exception cref="ArgumentException">when <paramref name="fileName"/> is null, empty or does not end in .ps1xml</exception> public TypeConfigurationEntry(string fileName) : base(fileName) { if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileName.Trim())) { throw PSTraceSource.NewArgumentException("fileName"); } #pragma warning suppress 56506 FileName = fileName.Trim(); } /// <summary> /// Gets file name that contains the types configuration information. /// </summary> /// <value></value> public string FileName { get; } /// <summary> /// Get the strong type data contains the type configuration information /// </summary> public TypeData TypeData { get; } /// <summary> /// Set to true if the strong type data is to be removed /// </summary> public bool IsRemove { get; } } /// <summary> /// Defines class for type configuration entry. /// </summary> #if CORECLR internal #else public #endif sealed class FormatConfigurationEntry : RunspaceConfigurationEntry { /// <summary> /// Initiate an instance for type configuration entry. /// </summary> /// <param name="name">Name of the format configuration entry</param> /// <param name="fileName">File name that contains the format configuration information.</param> /// <exception cref="ArgumentException">when <paramref name="fileName"/> is null or empty</exception> public FormatConfigurationEntry(string name, string fileName) : base(name) { if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileName.Trim())) { throw PSTraceSource.NewArgumentException("fileName"); } FileName = fileName.Trim(); } /// <summary> /// Initiate an instance for Format configuration entry. /// </summary> /// <param name="name">Name of the Format configuration entry</param> /// <param name="fileName">File name that contains the Formats configuration information.</param> /// <param name="psSnapinInfo">PSSnapin from which the format comes.</param> /// <exception cref="ArgumentException">when <paramref name="fileName"/> is null, empty or does not end in .ps1xml</exception> internal FormatConfigurationEntry(string name, string fileName, PSSnapInInfo psSnapinInfo) : base(name, psSnapinInfo) { if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileName.Trim())) { throw PSTraceSource.NewArgumentException("fileName"); } FileName = fileName.Trim(); } /// <summary> /// Initiate an instance for type configuration entry. /// </summary> /// <param name="fileName">File name that contains the format configuration information.</param> /// <exception cref="ArgumentException">when <paramref name="fileName"/> is null or empty</exception> public FormatConfigurationEntry(string fileName) : base(fileName) { if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileName.Trim())) { throw PSTraceSource.NewArgumentException("fileName"); } #pragma warning suppress 56506 FileName = fileName.Trim(); } /// <summary> /// Initiate an instance for type configuration entry. /// </summary> /// <param name="typeDefinition"></param> public FormatConfigurationEntry(ExtendedTypeDefinition typeDefinition) : base("*") { if (typeDefinition == null) { throw PSTraceSource.NewArgumentNullException("typeDefinition"); } FormatData = typeDefinition; } /// <summary> /// Gets file name that contains the format configuration information. /// </summary> /// <value>File name that contains the format configuration information.</value> public string FileName { get; } /// <summary> /// Get the typeDefinition that contains the format configuration information /// </summary> public ExtendedTypeDefinition FormatData { get; } } /// <summary> /// Class to define configuration data for cmdlets /// </summary> #if CORECLR internal #else public #endif sealed class CmdletConfigurationEntry : RunspaceConfigurationEntry { /// <summary> /// Initiate an instance for cmdlet configuration entry. /// </summary> /// <param name="name">Name of the cmdlet configuration entry</param> /// <param name="implementingType">Class that include implementation of the cmdlet</param> /// <param name="helpFileName">Name of the help file that include help information for the cmdlet</param> public CmdletConfigurationEntry(string name, Type implementingType, string helpFileName) : base(name) { if (implementingType == null) { throw PSTraceSource.NewArgumentNullException("implementingType"); } ImplementingType = implementingType; if (!String.IsNullOrEmpty(helpFileName)) { HelpFileName = helpFileName.Trim(); } else { HelpFileName = helpFileName; } } /// <summary> /// Initiate an instance for cmdlet configuration entry. /// </summary> /// <param name="name">Name of the cmdlet configuration entry</param> /// <param name="implementingType">Class that include implementation of the cmdlet</param> /// <param name="psSnapinInfo">PSSnapin from which the cmdlet comes.</param> /// <param name="helpFileName">Name of the help file that include help information for the cmdlet</param> internal CmdletConfigurationEntry(string name, Type implementingType, string helpFileName, PSSnapInInfo psSnapinInfo) : base(name, psSnapinInfo) { if (implementingType == null) { throw PSTraceSource.NewArgumentNullException("implementingType"); } ImplementingType = implementingType; if (!String.IsNullOrEmpty(helpFileName)) { HelpFileName = helpFileName.Trim(); } else { HelpFileName = helpFileName; } } /// <summary> /// Get class that include implementation of the cmdlet /// </summary> public Type ImplementingType { get; } /// <summary> /// Get name of the help file that include help information for the cmdlet /// </summary> /// <value></value> public string HelpFileName { get; } } /// <summary> /// Define class for provider configuration entry /// </summary> #if CORECLR internal #else public #endif sealed class ProviderConfigurationEntry : RunspaceConfigurationEntry { /// <summary> /// Initiate an instance for provider configuration entry. /// </summary> /// <param name="name">Name of the provider configuration entry</param> /// <param name="implementingType">Class that include implementation of the provider</param> /// <param name="helpFileName">Name of the help file that include help information for the provider</param> public ProviderConfigurationEntry(string name, Type implementingType, string helpFileName) : base(name) { if (implementingType == null) { throw PSTraceSource.NewArgumentNullException("implementingType"); } ImplementingType = implementingType; if (!String.IsNullOrEmpty(helpFileName)) { HelpFileName = helpFileName.Trim(); } else { HelpFileName = helpFileName; } } /// <summary> /// Initiate an instance for provider configuration entry. /// </summary> /// <param name="name">Name of the provider configuration entry</param> /// <param name="implementingType">Class that include implementation of the provider</param> /// <param name="helpFileName">Name of the help file that include help information for the provider</param> /// <param name="psSnapinInfo">PSSnapin from which provider comes from.</param> internal ProviderConfigurationEntry(string name, Type implementingType, string helpFileName, PSSnapInInfo psSnapinInfo) : base(name, psSnapinInfo) { if (implementingType == null) { throw PSTraceSource.NewArgumentNullException("implementingType"); } ImplementingType = implementingType; if (!String.IsNullOrEmpty(helpFileName)) { HelpFileName = helpFileName.Trim(); } else { HelpFileName = helpFileName; } } /// <summary> /// Get class that include implementation of the provider. /// </summary> /// <value></value> public Type ImplementingType { get; } /// <summary> /// Get name of the help file that include help information for the provider /// </summary> public string HelpFileName { get; } } /// <summary> /// Define class for script configuration entry /// </summary> #if CORECLR internal #else public #endif sealed class ScriptConfigurationEntry : RunspaceConfigurationEntry { /// <summary> /// Initiate an instance for script configuration entry. /// </summary> /// <param name="name">Name of the script configuration entry</param> /// <param name="definition">Content of the script</param> public ScriptConfigurationEntry(string name, string definition) : base(name) { if (String.IsNullOrEmpty(definition) || String.IsNullOrEmpty(definition.Trim())) { throw PSTraceSource.NewArgumentNullException("definition"); } Definition = definition.Trim(); } /// <summary> /// Get content for the script. /// </summary> public string Definition { get; } } /// <summary> /// Configuration data for assemblies. /// </summary> #if CORECLR internal #else public #endif sealed class AssemblyConfigurationEntry : RunspaceConfigurationEntry { /// <summary> /// Initiate an instance for assembly configuration entry. /// </summary> /// <param name="name">Strong name of the assembly</param> /// <param name="fileName">Name of the assembly file</param> public AssemblyConfigurationEntry(string name, string fileName) : base(name) { if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileName.Trim())) { throw PSTraceSource.NewArgumentNullException("fileName"); } FileName = fileName.Trim(); } /// <summary> /// Initiate an instance for assembly configuration entry. /// </summary> /// <param name="name">Strong name of the assembly</param> /// <param name="fileName">Name of the assembly file</param> /// <param name="psSnapinInfo">PSSnapin information.</param> /// <exception cref="ArgumentException">when <paramref name="fileName"/> is null, empty or does not end in .ps1xml</exception> internal AssemblyConfigurationEntry(string name, string fileName, PSSnapInInfo psSnapinInfo) : base(name, psSnapinInfo) { if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileName.Trim())) { throw PSTraceSource.NewArgumentNullException("fileName"); } FileName = fileName.Trim(); } /// <summary> /// Get name of the assembly file /// </summary> /// <value>Name of the assembly file</value> public string FileName { get; } } internal enum UpdateAction { Add, Remove, None } } #pragma warning restore 56506
// GtkSharp.Generation.FieldBase.cs - base class for struct and object // fields // // Copyright (c) 2004 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 namespace GtkSharp.Generation { using System; using System.Collections; using System.IO; using System.Xml; public abstract class FieldBase : PropertyBase { public FieldBase (XmlElement elem, ClassBase container_type) : base (elem, container_type) {} public bool Validate () { if (!Ignored && !Hidden && CSType == "") { Console.Write("Field {0} has unknown Type {1} ", Name, CType); Statistics.ThrottledCount++; return false; } return true; } protected virtual bool Readable { get { return elem.GetAttribute ("readable") != "false"; } } protected virtual bool Writable { get { return elem.GetAttribute ("writeable") != "false"; } } protected abstract string DefaultAccess { get; } protected string Access { get { return elem.HasAttribute ("access") ? elem.GetAttribute ("access") : DefaultAccess; } } public bool IsArray { get { return elem.HasAttribute("array_len") || elem.HasAttribute("array"); } } public bool IsBitfield { get { return elem.HasAttribute("bits"); } } public bool Ignored { get { if (container_type.GetProperty (Name) != null) return true; if (IsArray) return true; if (Access == "private" && (Getter == null) && (Setter == null)) return true; return false; } } string getterName, setterName; string getOffsetName, offsetName; void CheckGlue () { getterName = setterName = getOffsetName = null; if (Access != "public") return; string prefix = (container_type.NS + "Sharp_" + container_type.NS + "_" + container_type.Name).ToLower (); if (IsBitfield) { if (Readable && Getter == null) getterName = prefix + "_get_" + CName; if (Writable && Setter == null) setterName = prefix + "_set_" + CName; } else { if ((Readable && Getter == null) || (Writable && Setter == null)) { offsetName = CName + "_offset"; getOffsetName = prefix + "_get_" + offsetName; } } } protected override void GenerateImports (GenerationInfo gen_info, string indent) { StreamWriter sw = gen_info.Writer; SymbolTable table = SymbolTable.Table; if (getterName != null) { sw.WriteLine (indent + "[DllImport (\"{0}\")]", gen_info.GluelibName); sw.WriteLine (indent + "extern static {0} {1} ({2} raw);", table.GetMarshalReturnType (CType), getterName, container_type.MarshalType); } if (setterName != null) { sw.WriteLine (indent + "[DllImport (\"{0}\")]", gen_info.GluelibName); sw.WriteLine (indent + "extern static void {0} ({1} raw, {2} value);", setterName, container_type.MarshalType, table.GetMarshalType (CType)); } if (getOffsetName != null) { sw.WriteLine (indent + "[DllImport (\"{0}\")]", gen_info.GluelibName); sw.WriteLine (indent + "extern static uint {0} ();", getOffsetName); sw.WriteLine (); sw.WriteLine (indent + "static uint " + offsetName + " = " + getOffsetName + " ();"); } base.GenerateImports (gen_info, indent); } public virtual void Generate (GenerationInfo gen_info, string indent) { if (Ignored || Hidden) return; CheckGlue (); if ((getterName != null || setterName != null || getOffsetName != null) && gen_info.GlueWriter == null) { Console.WriteLine ("No glue-filename specified, can't create glue for {0}.{1}", container_type.Name, Name); return; } GenerateImports (gen_info, indent); SymbolTable table = SymbolTable.Table; StreamWriter sw = gen_info.Writer; string modifiers = elem.HasAttribute ("new_flag") ? "new " : ""; bool is_struct = table.IsStruct (CType) || table.IsBoxed (CType); sw.WriteLine (indent + "public " + modifiers + CSType + " " + Name + " {"); if (Getter != null) { sw.Write (indent + "\tget "); Getter.GenerateBody (gen_info, container_type, "\t"); sw.WriteLine (""); } else if (getterName != null) { sw.WriteLine (indent + "\tget {"); container_type.Prepare (sw, indent + "\t\t"); sw.WriteLine (indent + "\t\t" + CSType + " result = " + table.FromNativeReturn (ctype, getterName + " (" + container_type.CallByName () + ")") + ";"); container_type.Finish (sw, indent + "\t\t"); sw.WriteLine (indent + "\t\treturn result;"); sw.WriteLine (indent + "\t}"); } else if (Readable && offsetName != null) { sw.WriteLine (indent + "\tget {"); sw.WriteLine (indent + "\t\tunsafe {"); if (is_struct) { sw.WriteLine (indent + "\t\t\t" + CSType + "* raw_ptr = (" + CSType + "*)(((byte*)" + container_type.CallByName () + ") + " + offsetName + ");"); sw.WriteLine (indent + "\t\t\treturn *raw_ptr;"); } else { sw.WriteLine (indent + "\t\t\t" + table.GetMarshalReturnType (CType) + "* raw_ptr = (" + table.GetMarshalReturnType (CType) + "*)(((byte*)" + container_type.CallByName () + ") + " + offsetName + ");"); sw.WriteLine (indent + "\t\t\treturn " + table.FromNativeReturn (ctype, "(*raw_ptr)") + ";"); } sw.WriteLine (indent + "\t\t}"); sw.WriteLine (indent + "\t}"); } if (Setter != null) { sw.Write (indent + "\tset "); Setter.GenerateBody (gen_info, container_type, "\t"); sw.WriteLine (""); } else if (setterName != null) { sw.WriteLine (indent + "\tset {"); container_type.Prepare (sw, indent + "\t\t"); sw.WriteLine (indent + "\t\t" + setterName + " (" + container_type.CallByName () + ", " + table.CallByName (ctype, "value") + ");"); container_type.Finish (sw, indent + "\t\t"); sw.WriteLine (indent + "\t}"); } else if (Writable && offsetName != null) { sw.WriteLine (indent + "\tset {"); sw.WriteLine (indent + "\t\tunsafe {"); if (is_struct) { sw.WriteLine (indent + "\t\t\t" + CSType + "* raw_ptr = (" + CSType + "*)(((byte*)" + container_type.CallByName () + ") + " + offsetName + ");"); sw.WriteLine (indent + "\t\t\t*raw_ptr = value;"); } else { sw.WriteLine (indent + "\t\t\t" + table.GetMarshalReturnType (CType) + "* raw_ptr = (" + table.GetMarshalReturnType (CType) + "*)(((byte*)" + container_type.CallByName () + ") + " + offsetName + ");"); sw.WriteLine (indent + "\t\t\t*raw_ptr = " + table.ToNativeReturn (ctype, "value") + ";"); } sw.WriteLine (indent + "\t\t}"); sw.WriteLine (indent + "\t}"); } sw.WriteLine (indent + "}"); sw.WriteLine (""); if (getterName != null || setterName != null || getOffsetName != null) GenerateGlue (gen_info); } protected void GenerateGlue (GenerationInfo gen_info) { StreamWriter sw = gen_info.GlueWriter; SymbolTable table = SymbolTable.Table; string FieldCType = CType.Replace ("-", " "); bool byref = table[CType] is ByRefGen || table[CType] is StructGen; string GlueCType = byref ? FieldCType + " *" : FieldCType; string ContainerCType = container_type.CName; string ContainerCName = container_type.Name.ToLower (); if (getterName != null) { sw.WriteLine ("{0} {1} ({2} *{3});", GlueCType, getterName, ContainerCType, ContainerCName); } if (setterName != null) { sw.WriteLine ("void {0} ({1} *{2}, {3} value);", setterName, ContainerCType, ContainerCName, GlueCType); } if (getOffsetName != null) sw.WriteLine ("guint {0} (void);", getOffsetName); sw.WriteLine (""); if (getterName != null) { sw.WriteLine (GlueCType); sw.WriteLine ("{0} ({1} *{2})", getterName, ContainerCType, ContainerCName); sw.WriteLine ("{"); sw.WriteLine ("\treturn ({0}){1}{2}->{3};", GlueCType, byref ? "&" : "", ContainerCName, CName); sw.WriteLine ("}"); sw.WriteLine (""); } if (setterName != null) { sw.WriteLine ("void"); sw.WriteLine ("{0} ({1} *{2}, {3} value)", setterName, ContainerCType, ContainerCName, GlueCType); sw.WriteLine ("{"); sw.WriteLine ("\t{0}->{1} = ({2}){3}value;", ContainerCName, CName, FieldCType, byref ? "*" : ""); sw.WriteLine ("}"); sw.WriteLine (""); } if (getOffsetName != null) { sw.WriteLine ("guint"); sw.WriteLine ("{0} (void)", getOffsetName); sw.WriteLine ("{"); sw.WriteLine ("\treturn (guint)G_STRUCT_OFFSET ({0}, {1});", ContainerCType, CName); sw.WriteLine ("}"); sw.WriteLine (""); } } } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using Amazon.Runtime.Internal.Util; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Linq; namespace Amazon.Util { /// <summary> /// This class defines utilities and constants that can be used by /// all the client libraries of the SDK. /// </summary> public static partial class AWSSDKUtils { #region Internal Constants internal const string DefaultRegion = "us-east-1"; internal const string DefaultGovRegion = "us-gov-west-1"; private const char SlashChar = '/'; private const string Slash = "/"; internal const int DefaultMaxRetry = 3; private const int DefaultConnectionLimit = 50; private const int DefaultMaxIdleTime = 50 * 1000; // 50 seconds public static readonly DateTime EPOCH_START = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public const int DefaultBufferSize = 8192; // Default value of progress update interval for streaming is 100KB. public const long DefaultProgressUpdateInterval = 102400; internal static Dictionary<int, string> RFCEncodingSchemes = new Dictionary<int, string> { { 3986, ValidUrlCharacters }, { 1738, ValidUrlCharactersRFC1738 } }; internal const string S3Accelerate = "s3-accelerate"; #endregion #region Public Constants /// <summary> /// The user agent string header /// </summary> public const string UserAgentHeader = "User-Agent"; /// <summary> /// The Set of accepted and valid Url characters per RFC3986. /// Characters outside of this set will be encoded. /// </summary> public const string ValidUrlCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; /// <summary> /// The Set of accepted and valid Url characters per RFC1738. /// Characters outside of this set will be encoded. /// </summary> public const string ValidUrlCharactersRFC1738 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_."; /// <summary> /// The set of accepted and valid Url path characters per RFC3986. /// </summary> private static string ValidPathCharacters = DetermineValidPathCharacters(); // Checks which path characters should not be encoded // This set will be different for .NET 4 and .NET 4.5, as // per http://msdn.microsoft.com/en-us/library/hh367887%28v=vs.110%29.aspx private static string DetermineValidPathCharacters() { const string basePathCharacters = "/:'()!*[]"; var sb = new StringBuilder(); foreach (var c in basePathCharacters) { var escaped = Uri.EscapeUriString(c.ToString()); if (escaped.Length == 1 && escaped[0] == c) sb.Append(c); } return sb.ToString(); } /// <summary> /// The string representing Url Encoded Content in HTTP requests /// </summary> public const string UrlEncodedContent = "application/x-www-form-urlencoded; charset=utf-8"; /// <summary> /// The GMT Date Format string. Used when parsing date objects /// </summary> public const string GMTDateFormat = "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T"; /// <summary> /// The ISO8601Date Format string. Used when parsing date objects /// </summary> public const string ISO8601DateFormat = "yyyy-MM-dd\\THH:mm:ss.fff\\Z"; /// <summary> /// The ISO8601Date Format string. Used when parsing date objects /// </summary> public const string ISO8601DateFormatNoMS = "yyyy-MM-dd\\THH:mm:ss\\Z"; /// <summary> /// The ISO8601 Basic date/time format string. Used when parsing date objects /// </summary> public const string ISO8601BasicDateTimeFormat = "yyyyMMddTHHmmssZ"; /// <summary> /// The ISO8601 basic date format. Used during AWS4 signature computation. /// </summary> public const string ISO8601BasicDateFormat = "yyyyMMdd"; /// <summary> /// The RFC822Date Format string. Used when parsing date objects /// </summary> public const string RFC822DateFormat = "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T"; #endregion #region Internal Methods /// <summary> /// Returns an extension of a path. /// This has the same behavior as System.IO.Path.GetExtension, but does not /// check the path for invalid characters. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetExtension(string path) { if (path == null) return null; int length = path.Length; int index = length; while (--index >= 0) { char ch = path[index]; if (ch == '.') { if (index != length - 1) return path.Substring(index, length - index); else return string.Empty; } else if (IsPathSeparator(ch)) break; } return string.Empty; } // Checks if the character is one \ / : private static bool IsPathSeparator(char ch) { return (ch == '\\' || ch == '/' || ch == ':'); } /* * Determines the string to be signed based on the input parameters for * AWS Signature Version 2 */ internal static string CalculateStringToSignV2(IDictionary<string, string> parameters, string serviceUrl) { StringBuilder data = new StringBuilder("POST\n", 512); IDictionary<string, string> sorted = new SortedDictionary<string, string>(parameters, StringComparer.Ordinal); Uri endpoint = new Uri(serviceUrl); data.Append(endpoint.Host); data.Append("\n"); string uri = endpoint.AbsolutePath; if (uri == null || uri.Length == 0) { uri = "/"; } data.Append(AWSSDKUtils.UrlEncode(uri, true)); data.Append("\n"); foreach (KeyValuePair<string, string> pair in sorted) { if (pair.Value != null) { data.Append(AWSSDKUtils.UrlEncode(pair.Key, false)); data.Append("="); data.Append(AWSSDKUtils.UrlEncode(pair.Value, false)); data.Append("&"); } } string result = data.ToString(); return result.Remove(result.Length - 1); } /** * Convert Dictionary of paremeters to Url encoded query string */ internal static string GetParametersAsString(IDictionary<string, string> parameters) { string[] keys = new string[parameters.Keys.Count]; parameters.Keys.CopyTo(keys, 0); Array.Sort<string>(keys); StringBuilder data = new StringBuilder(512); foreach (string key in keys) { string value = parameters[key]; if (value != null) { data.Append(key); data.Append('='); data.Append(AWSSDKUtils.UrlEncode(value, false)); data.Append('&'); } } string result = data.ToString(); if (result.Length == 0) return string.Empty; return result.Remove(result.Length - 1); } /// <summary> /// Returns the canonicalized resource path for the service endpoint /// </summary> /// <param name="endpoint">Endpoint URL for the request</param> /// <param name="resourcePath">Resource path for the request</param> /// <remarks> /// If resourcePath begins or ends with slash, the resulting canonicalized /// path will follow suit. /// </remarks> /// <returns>Canonicalized resource path for the endpoint</returns> public static string CanonicalizeResourcePath(Uri endpoint, string resourcePath) { if (endpoint != null) { var path = endpoint.AbsolutePath; if (string.IsNullOrEmpty(path) || string.Equals(path, Slash, StringComparison.Ordinal)) path = string.Empty; if (!string.IsNullOrEmpty(resourcePath) && resourcePath.StartsWith(Slash, StringComparison.Ordinal)) resourcePath = resourcePath.Substring(1); if (!string.IsNullOrEmpty(resourcePath)) path = path + Slash + resourcePath; resourcePath = path; } if (string.IsNullOrEmpty(resourcePath)) return Slash; // split path at / into segments var pathSegments = resourcePath.Split(new char[] { SlashChar }, StringSplitOptions.None); // url encode the segments var encodedSegments = pathSegments .Select(segment => AWSSDKUtils.UrlEncode(segment, false)) .ToArray(); // join the encoded segments with / var canonicalizedResourcePath = string.Join(Slash, encodedSegments); return canonicalizedResourcePath; } /// <summary> /// Returns a new string created by joining each of the strings in the /// specified list together, with a comma between them. /// </summary> /// <parma name="strings">The list of strings to join into a single, comma delimited /// string list.</parma> /// <returns> A new string created by joining each of the strings in the /// specified list together, with a comma between strings.</returns> public static String Join(List<String> strings) { StringBuilder result = new StringBuilder(); Boolean first = true; foreach (String s in strings) { if (!first) result.Append(", "); result.Append(s); first = false; } return result.ToString(); } /// <summary> /// Attempt to infer the region for a service request based on the endpoint /// </summary> /// <param name="url">Endpoint to the service to be called</param> /// <returns> /// Region parsed from the endpoint; DefaultRegion (or DefaultGovRegion) /// if it cannot be determined/is not explicit /// </returns> public static string DetermineRegion(string url) { int delimIndex = url.IndexOf("//", StringComparison.Ordinal); if (delimIndex >= 0) url = url.Substring(delimIndex + 2); if(url.EndsWith("/", StringComparison.Ordinal)) url = url.Substring(0, url.Length - 1); int awsIndex = url.IndexOf(".amazonaws.com", StringComparison.Ordinal); if (awsIndex < 0) return DefaultRegion; string serviceAndRegion = url.Substring(0, awsIndex); int cloudSearchIndex = url.IndexOf(".cloudsearch.amazonaws.com", StringComparison.Ordinal); if (cloudSearchIndex > 0) serviceAndRegion = url.Substring(0, cloudSearchIndex); int queueIndex = serviceAndRegion.IndexOf("queue", StringComparison.Ordinal); if (queueIndex == 0) return DefaultRegion; if (queueIndex > 0) return serviceAndRegion.Substring(0, queueIndex - 1); if (serviceAndRegion.StartsWith("s3-", StringComparison.Ordinal)) { // Accelerate endpoint is global and does not contain region information if (serviceAndRegion.Equals(AWSSDKUtils.S3Accelerate, StringComparison.Ordinal)) return null; serviceAndRegion = "s3." + serviceAndRegion.Substring(3); } int separatorIndex = serviceAndRegion.LastIndexOf('.'); if (separatorIndex == -1) return DefaultRegion; string region = serviceAndRegion.Substring(separatorIndex + 1); if (region.Equals("external-1")) return RegionEndpoint.USEast1.SystemName; if (string.Equals(region, "us-gov", StringComparison.Ordinal)) return DefaultGovRegion; return region; } /// <summary> /// Attempt to infer the service name for a request (in short form, eg 'iam') from the /// service endpoint. /// </summary> /// <param name="url">Endpoint to the service to be called</param> /// <returns> /// Short-form name of the service parsed from the endpoint; empty string if it cannot /// be determined /// </returns> public static string DetermineService(string url) { int delimIndex = url.IndexOf("//", StringComparison.Ordinal); if (delimIndex >= 0) url = url.Substring(delimIndex + 2); string[] urlParts = url.Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries); if (urlParts == null || urlParts.Length == 0) return string.Empty; string servicePart = urlParts[0]; int hyphenated = servicePart.IndexOf('-'); string service; if (hyphenated < 0) { service = servicePart; } else { service = servicePart.Substring(0, hyphenated); } // Check for SQS : return "sqs" incase service is determined to be "queue" as per the URL. if (service.Equals("queue")) { return "sqs"; } else { return service; } } /// <summary> /// Utility method for converting Unix epoch seconds to DateTime structure. /// </summary> /// <param name="seconds">The number of seconds since January 1, 1970.</param> /// <returns>Converted DateTime structure</returns> public static DateTime ConvertFromUnixEpochSeconds(int seconds) { return new DateTime(seconds * 10000000L + EPOCH_START.Ticks, DateTimeKind.Utc).ToLocalTime(); } public static int ConvertToUnixEpochSeconds(DateTime dateTime) { return (int)ConvertToUnixEpochMilliSeconds(dateTime); } public static double ConvertToUnixEpochMilliSeconds(DateTime dateTime) { TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - EPOCH_START.Ticks); double milli = Math.Round(ts.TotalMilliseconds, 0) / 1000.0; return milli; } /// <summary> /// Helper function to format a byte array into string /// </summary> /// <param name="data">The data blob to process</param> /// <param name="lowercase">If true, returns hex digits in lower case form</param> /// <returns>String version of the data</returns> public static string ToHex(byte[] data, bool lowercase) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sb.Append(data[i].ToString(lowercase ? "x2" : "X2", CultureInfo.InvariantCulture)); } return sb.ToString(); } /// <summary> /// Calls a specific EventHandler in a background thread /// </summary> /// <param name="handler"></param> /// <param name="args"></param> /// <param name="sender"></param> public static void InvokeInBackground<T>(EventHandler<T> handler, T args, object sender) where T : EventArgs { if (handler == null) return; var list = handler.GetInvocationList(); foreach (var call in list) { var eventHandler = ((EventHandler<T>)call); if (eventHandler != null) { Dispatcher.Dispatch(() => eventHandler(sender, args)); } } } private static BackgroundInvoker _dispatcher; private static BackgroundInvoker Dispatcher { get { if (_dispatcher == null) { _dispatcher = new BackgroundInvoker(); } return _dispatcher; } } /// <summary> /// Parses a query string of a URL and returns the parameters as a string-to-string dictionary. /// </summary> /// <param name="url"></param> /// <returns></returns> public static Dictionary<string, string> ParseQueryParameters(string url) { Dictionary<string, string> parameters = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(url)) { int queryIndex = url.IndexOf('?'); if (queryIndex >= 0) { string queryString = url.Substring(queryIndex + 1); string[] kvps = queryString.Split(new char[] { '&' }, StringSplitOptions.None); foreach (string kvp in kvps) { if (string.IsNullOrEmpty(kvp)) continue; string[] nameValuePair = kvp.Split(new char[] { '=' }, 2); string name = nameValuePair[0]; string value = nameValuePair.Length == 1 ? null : nameValuePair[1]; parameters[name] = value; } } } return parameters; } internal static bool AreEqual(object[] itemsA, object[] itemsB) { if (itemsA == null || itemsB == null) return (itemsA == itemsB); if (itemsA.Length != itemsB.Length) return false; var length = itemsA.Length; for (int i = 0; i < length; i++) { var a = itemsA[i]; var b = itemsB[i]; if (!AreEqual(a, b)) return false; } return true; } internal static bool AreEqual(object a, object b) { if (a == null || b == null) return (a == b); if (object.ReferenceEquals(a, b)) return true; return (a.Equals(b)); } /// <summary> /// Utility method for converting a string to a MemoryStream. /// </summary> /// <param name="s"></param> /// <returns></returns> public static MemoryStream GenerateMemoryStreamFromString(string s) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(s); writer.Flush(); stream.Position = 0; return stream; } /// <summary> /// Utility method for copy the contents of the source stream to the destination stream. /// </summary> /// <param name="source"></param> /// <param name="destination"></param> public static void CopyStream(Stream source, Stream destination) { CopyStream(source, destination, DefaultBufferSize); } /// <summary> /// Utility method for copy the contents of the source stream to the destination stream. /// </summary> /// <param name="source"></param> /// <param name="destination"></param> /// <param name="bufferSize"></param> public static void CopyStream(Stream source, Stream destination, int bufferSize) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); byte[] array = new byte[bufferSize]; int count; while ((count = source.Read(array, 0, array.Length)) != 0) { destination.Write(array, 0, count); } } #endregion #region Public Methods and Properties /// <summary> /// Formats the current date as a GMT timestamp /// </summary> /// <returns>A GMT formatted string representation /// of the current date and time /// </returns> public static string FormattedCurrentTimestampGMT { get { DateTime dateTime = AWSSDKUtils.CorrectedUtcNow; DateTime formatted = new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, DateTimeKind.Local ); return formatted.ToString( GMTDateFormat, CultureInfo.InvariantCulture ); } } /// <summary> /// Formats the current date as ISO 8601 timestamp /// </summary> /// <returns>An ISO 8601 formatted string representation /// of the current date and time /// </returns> public static string FormattedCurrentTimestampISO8601 { get { return GetFormattedTimestampISO8601(0); } } /// <summary> /// Gets the ISO8601 formatted timestamp that is minutesFromNow /// in the future. /// </summary> /// <param name="minutesFromNow">The number of minutes from the current instant /// for which the timestamp is needed.</param> /// <returns>The ISO8601 formatted future timestamp.</returns> public static string GetFormattedTimestampISO8601(int minutesFromNow) { DateTime dateTime = AWSSDKUtils.CorrectedUtcNow.AddMinutes(minutesFromNow); DateTime formatted = new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, DateTimeKind.Local ); return formatted.ToString( AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture ); } /// <summary> /// Formats the current date as ISO 8601 timestamp /// </summary> /// <returns>An ISO 8601 formatted string representation /// of the current date and time /// </returns> public static string FormattedCurrentTimestampRFC822 { get { return GetFormattedTimestampRFC822(0); } } /// <summary> /// Gets the RFC822 formatted timestamp that is minutesFromNow /// in the future. /// </summary> /// <param name="minutesFromNow">The number of minutes from the current instant /// for which the timestamp is needed.</param> /// <returns>The ISO8601 formatted future timestamp.</returns> public static string GetFormattedTimestampRFC822(int minutesFromNow) { DateTime dateTime = AWSSDKUtils.CorrectedUtcNow.AddMinutes(minutesFromNow); DateTime formatted = new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, DateTimeKind.Local ); return formatted.ToString( AWSSDKUtils.RFC822DateFormat, CultureInfo.InvariantCulture ); } /// <summary> /// URL encodes a string per RFC3986. If the path property is specified, /// the accepted path characters {/+:} are not encoded. /// </summary> /// <param name="data">The string to encode</param> /// <param name="path">Whether the string is a URL path or not</param> /// <returns>The encoded string</returns> public static string UrlEncode(string data, bool path) { return UrlEncode(3986, data, path); } /// <summary> /// URL encodes a string per the specified RFC. If the path property is specified, /// the accepted path characters {/+:} are not encoded. /// </summary> /// <param name="rfcNumber">RFC number determing safe characters</param> /// <param name="data">The string to encode</param> /// <param name="path">Whether the string is a URL path or not</param> /// <returns>The encoded string</returns> /// <remarks> /// Currently recognised RFC versions are 1738 (Dec '94) and 3986 (Jan '05). /// If the specified RFC is not recognised, 3986 is used by default. /// </remarks> public static string UrlEncode(int rfcNumber, string data, bool path) { StringBuilder encoded = new StringBuilder(data.Length * 2); string validUrlCharacters; if (!RFCEncodingSchemes.TryGetValue(rfcNumber, out validUrlCharacters)) validUrlCharacters = ValidUrlCharacters; string unreservedChars = String.Concat(validUrlCharacters, (path ? ValidPathCharacters : "")); foreach (char symbol in System.Text.Encoding.UTF8.GetBytes(data)) { if (unreservedChars.IndexOf(symbol) != -1) { encoded.Append(symbol); } else { encoded.Append("%").Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol)); } } return encoded.ToString(); } public static void Sleep(TimeSpan ts) { Sleep((int)ts.TotalMilliseconds); } /// <summary> /// Convert bytes to a hex string /// </summary> /// <param name="value">Bytes to convert.</param> /// <returns>Hexadecimal string representing the byte array.</returns> public static string BytesToHexString(byte[] value) { string hex = BitConverter.ToString(value); hex = hex.Replace("-", string.Empty); return hex; } /// <summary> /// Convert a hex string to bytes /// </summary> /// <param name="hex">Hexadecimal string</param> /// <returns>Byte array corresponding to the hex string.</returns> public static byte[] HexStringToBytes(string hex) { if (string.IsNullOrEmpty(hex) || hex.Length % 2 == 1) throw new ArgumentOutOfRangeException("hex"); int count = 0; byte[] buffer = new byte[hex.Length / 2]; for (int i = 0; i < hex.Length; i += 2) { string sub = hex.Substring(i, 2); byte b = Convert.ToByte(sub, 16); buffer[count] = b; count++; } return buffer; } /// <summary> /// Returns DateTime.UtcNow + ClockOffset when /// <seealso cref="AWSConfigs.CorrectForClockSkew"/> is true. /// This value should be used when constructing requests, as it /// will represent accurate time w.r.t. AWS servers. /// </summary> public static DateTime CorrectedUtcNow { get { var now = DateTime.UtcNow; if (AWSConfigs.CorrectForClockSkew) now += AWSConfigs.ClockOffset; return now; } } /// <summary> /// Returns true if the string has any bidirectional control characters. /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool HasBidiControlCharacters(string input) { if (string.IsNullOrEmpty(input)) return false; foreach(var c in input) { if (IsBidiControlChar(c)) return true; } return false; } private static bool IsBidiControlChar(char c) { // check general range if (c < '\u200E' || c > '\u202E') return false; // check specific characters return ( c == '\u200E' || // LRM c == '\u200F' || // RLM c == '\u202A' || // LRE c == '\u202B' || // RLE c == '\u202C' || // PDF c == '\u202D' || // LRO c == '\u202E' // RLO ); } #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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class PreIncrementAssignTests : IncDecAssignTests { [Theory] [PerCompilationType(nameof(Int16sAndIncrements))] [PerCompilationType(nameof(NullableInt16sAndIncrements))] [PerCompilationType(nameof(UInt16sAndIncrements))] [PerCompilationType(nameof(NullableUInt16sAndIncrements))] [PerCompilationType(nameof(Int32sAndIncrements))] [PerCompilationType(nameof(NullableInt32sAndIncrements))] [PerCompilationType(nameof(UInt32sAndIncrements))] [PerCompilationType(nameof(NullableUInt32sAndIncrements))] [PerCompilationType(nameof(Int64sAndIncrements))] [PerCompilationType(nameof(NullableInt64sAndIncrements))] [PerCompilationType(nameof(UInt64sAndIncrements))] [PerCompilationType(nameof(NullableUInt64sAndIncrements))] [PerCompilationType(nameof(DecimalsAndIncrements))] [PerCompilationType(nameof(NullableDecimalsAndIncrements))] [PerCompilationType(nameof(SinglesAndIncrements))] [PerCompilationType(nameof(NullableSinglesAndIncrements))] [PerCompilationType(nameof(DoublesAndIncrements))] [PerCompilationType(nameof(NullableDoublesAndIncrements))] public void ReturnsCorrectValues(Type type, object value, object result, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PreIncrementAssign(variable) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(Int16sAndIncrements))] [PerCompilationType(nameof(NullableInt16sAndIncrements))] [PerCompilationType(nameof(UInt16sAndIncrements))] [PerCompilationType(nameof(NullableUInt16sAndIncrements))] [PerCompilationType(nameof(Int32sAndIncrements))] [PerCompilationType(nameof(NullableInt32sAndIncrements))] [PerCompilationType(nameof(UInt32sAndIncrements))] [PerCompilationType(nameof(NullableUInt32sAndIncrements))] [PerCompilationType(nameof(Int64sAndIncrements))] [PerCompilationType(nameof(NullableInt64sAndIncrements))] [PerCompilationType(nameof(UInt64sAndIncrements))] [PerCompilationType(nameof(NullableUInt64sAndIncrements))] [PerCompilationType(nameof(DecimalsAndIncrements))] [PerCompilationType(nameof(NullableDecimalsAndIncrements))] [PerCompilationType(nameof(SinglesAndIncrements))] [PerCompilationType(nameof(NullableSinglesAndIncrements))] [PerCompilationType(nameof(DoublesAndIncrements))] [PerCompilationType(nameof(NullableDoublesAndIncrements))] public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); LabelTarget target = Expression.Label(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PreIncrementAssign(variable), Expression.Return(target, variable), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void SingleNanToNan(bool useInterpreter) { TestPropertyClass<float> instance = new TestPropertyClass<float>(); instance.TestInstance = float.NaN; Assert.True(float.IsNaN( Expression.Lambda<Func<float>>( Expression.PreIncrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<float>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(float.IsNaN(instance.TestInstance)); } [Theory] [ClassData(typeof(CompilationTypes))] public void DoubleNanToNan(bool useInterpreter) { TestPropertyClass<double> instance = new TestPropertyClass<double>(); instance.TestInstance = double.NaN; Assert.True(double.IsNaN( Expression.Lambda<Func<double>>( Expression.PreIncrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<double>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(double.IsNaN(instance.TestInstance)); } [Theory] [PerCompilationType(nameof(IncrementOverflowingValues))] public void OverflowingValuesThrow(object value, bool useInterpreter) { ParameterExpression variable = Expression.Variable(value.GetType()); Action overflow = Expression.Lambda<Action>( Expression.Block( typeof(void), new[] { variable }, Expression.Assign(variable, Expression.Constant(value)), Expression.PreIncrementAssign(variable) ) ).Compile(useInterpreter); Assert.Throws<OverflowException>(overflow); } [Theory] [MemberData(nameof(UnincrementableAndUndecrementableTypes))] public void InvalidOperandType(Type type) { ParameterExpression variable = Expression.Variable(type); Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable)); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectResult(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")) ); Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectAssign(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); LabelTarget target = Expression.Label(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")), Expression.Return(target, variable), Expression.Label(target, Expression.Default(typeof(string))) ); Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Fact] public void IncorrectMethodType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"); Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable, method)); } [Fact] public void IncorrectMethodParameterCount() { Expression variable = Expression.Variable(typeof(string)); MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals"); AssertExtensions.Throws<ArgumentException>("method", () => Expression.PreIncrementAssign(variable, method)); } [Fact] public void IncorrectMethodReturnType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString"); AssertExtensions.Throws<ArgumentException>(null, () => Expression.PreIncrementAssign(variable, method)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StaticMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<uint>.TestStatic = 2U; Assert.Equal( 3U, Expression.Lambda<Func<uint>>( Expression.PreIncrementAssign( Expression.Property(null, typeof(TestPropertyClass<uint>), "TestStatic") ) ).Compile(useInterpreter)() ); Assert.Equal(3U, TestPropertyClass<uint>.TestStatic); } [Theory] [ClassData(typeof(CompilationTypes))] public void InstanceMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<int> instance = new TestPropertyClass<int>(); instance.TestInstance = 2; Assert.Equal( 3, Expression.Lambda<Func<int>>( Expression.PreIncrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<int>), "TestInstance" ) ) ).Compile(useInterpreter)() ); Assert.Equal(3, instance.TestInstance); } [Theory] [ClassData(typeof(CompilationTypes))] public void ArrayAccessCorrect(bool useInterpreter) { int[] array = new int[1]; array[0] = 2; Assert.Equal( 3, Expression.Lambda<Func<int>>( Expression.PreIncrementAssign( Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0)) ) ).Compile(useInterpreter)() ); Assert.Equal(3, array[0]); } [Fact] public void CanReduce() { ParameterExpression variable = Expression.Variable(typeof(int)); UnaryExpression op = Expression.PreIncrementAssign(variable); Assert.True(op.CanReduce); Assert.NotSame(op, op.ReduceAndCheck()); } [Fact] public void NullOperand() { AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.PreIncrementAssign(null)); } [Fact] public void UnwritableOperand() { AssertExtensions.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(Expression.Constant(1))); } [Fact] public void UnreadableOperand() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(value)); } [Fact] public void UpdateSameOperandSameNode() { UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int))); Assert.Same(op, op.Update(op.Operand)); Assert.Same(op, NoOpVisitor.Instance.Visit(op)); } [Fact] public void UpdateDiffOperandDiffNode() { UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int))); Assert.NotSame(op, op.Update(Expression.Variable(typeof(int)))); } [Fact] public void ToStringTest() { UnaryExpression e = Expression.PreIncrementAssign(Expression.Parameter(typeof(int), "x")); Assert.Equal("++x", e.ToString()); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 10/4/2009 10:42:27 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using DotSpatial.Data; namespace DotSpatial.Symbology.Forms { /// <summary> /// The bar graph, when given a rectangular frame to work in, calculates appropriate bins /// from values, and draws the various labels and bars necessary. /// </summary> public class BarGraph : IDisposable { #region Private Variables private int _axisTextHeight; private int[] _bins; private List<ColorRange> _colorRanges; private int _countTextWidth; private TextFont _font; private int _height; private bool _logY; private int _maxBinCount; private double _maximum; private double _mean; private int _minHeight; private double _minimum; private int _numColumns; private ColorRange _selectedRange; private bool _showMean; private bool _showStandardDeviation; private double _std; private string _title; private TextFont _titleFont; private int _titleHeight; private int _width; #endregion #region Constructors /// <summary> /// Creates a new instance of BarGraph /// </summary> public BarGraph(int width, int height) { _numColumns = 40; _font = new TextFont(); _titleFont = new TextFont(20f); _title = "Statistical Breaks:"; _countTextWidth = 15; _axisTextHeight = 30; _minHeight = 20; _width = width; _height = height; _minimum = 0; _maximum = 100; _colorRanges = new List<ColorRange>(); } #endregion #region Methods /// <summary> /// Gets the bounding rectangle for the actual graph itself /// </summary> public Rectangle GetGraphBounds() { return new Rectangle(_countTextWidth, _titleHeight + 5, _width - _countTextWidth - 10, _height - _axisTextHeight - 10 - _titleHeight); } #endregion #region Properties /// <summary> /// Gets or sets the array of integers that represent the positive integer value stored in /// each bar. /// </summary> public int[] Bins { get { return _bins; } set { _bins = value; } } /// <summary> /// Gets or sets the list of color ranges that control how the colors are drawn to the graph. /// </summary> public List<ColorRange> ColorRanges { get { return _colorRanges; } set { _colorRanges = value; } } /// <summary> /// Gets or sets the Font for text like the axis labels /// </summary> public TextFont Font { get { return _font; } set { _font = value; } } /// <summary> /// Gets or sets the integer height /// </summary> public int Height { get { return _height; } set { _height = value; } } /// <summary> /// Gets or sets a boolean that indicates whether or not count values should be drawn with /// heights that are proportional to the logarithm of the count, instead of the count itself. /// </summary> public bool LogY { get { return _logY; } set { _logY = value; } } /// <summary> /// Gets or sets the integer maximum from all of the current bins. /// </summary> public int MaxBinCount { get { return _maxBinCount; } set { _maxBinCount = value; } } /// <summary> /// This doesn't affect the statistical minimum or maximum, but rather the current view extents. /// </summary> public double Maximum { get { return _maximum; } set { _maximum = value; } } /// <summary> /// The mean line can be drawn if it is in the view range. This is the statistical mean /// for all the values, not just the values currently in view. /// </summary> public double Mean { get { return _mean; } set { _mean = value; } } /// <summary> /// Gets or sets the double standard deviation. If ShowStandardDeviation is true, then /// they will be represented by red lines on either side of the mean. /// </summary> public double StandardDeviation { get { return _std; } set { _std = value; } } /// <summary> /// Very small counts frequently disappear next to big counts. One strategy is to use a /// minimum height, so that the difference between 0 and 1 is magnified on the columns. /// </summary> public int MinHeight { get { return _minHeight; } set { _minHeight = value; } } /// <summary> /// Gets or sets the maximum extent for this graph. This doesn't affect the numeric statistics, /// but only the current view of that statistics. /// </summary> public double Minimum { get { return _minimum; } set { _minimum = value; } } /// <summary> /// Gets or sets the number of columns. Setting this will recalculate the bins. /// </summary> public int NumColumns { get { return _numColumns; } set { if (value < 0) value = 0; _numColumns = value; } } /// <summary> /// Gets or sets the color range. /// </summary> public ColorRange SelectedRange { get { return _selectedRange; } set { _selectedRange = value; } } /// <summary> /// Boolean, if this is true, the mean will be shown as a blue dotted line. /// </summary> public bool ShowMean { get { return _showMean; } set { _showMean = value; } } /// <summary> /// Boolean, if this is true, the integral standard deviations from the mean will be drawn /// as red dotted lines. /// </summary> public bool ShowStandardDeviation { get { return _showStandardDeviation; } set { _showStandardDeviation = value; } } /// <summary> /// Gets or sets the title of the graph. /// </summary> public string Title { get { return _title; } set { _title = value; } } /// <summary> /// Gets or sets the font to use for the graph title /// </summary> public TextFont TitleFont { get { return _titleFont; } set { _titleFont = value; } } /// <summary> /// Gets or sets the width of this graph in pixels. /// </summary> public int Width { get { return _width; } set { _width = value; } } #endregion #region IDisposable Members /// <summary> /// Disposes the font and titlefont /// </summary> public void Dispose() { _font.Dispose(); _titleFont.Dispose(); } #endregion /// <summary> /// Draws the graph, the colored bins, selected region, and any text, but not any sliders. /// </summary> /// <param name="g"></param> /// <param name="clip"></param> public void Draw(Graphics g, Rectangle clip) { DrawText(g); Rectangle gb = GetGraphBounds(); DrawSelectionHighlight(g, clip, gb); DrawColumns(g, clip); g.DrawRectangle(Pens.Black, gb); if (_showMean) { Pen p = new Pen(Color.Blue); p.DashStyle = DashStyle.Dash; float x = GetPosition(_mean); if (x > -32000 && x < 32000) g.DrawLine(p, x, gb.Top, x, gb.Bottom); p.Dispose(); } if (_showStandardDeviation) { Pen p = new Pen(Color.Red); p.DashStyle = DashStyle.Dash; for (int i = 1; i < 6; i++) { double h = _mean + _std * i; double l = _mean - _std * i; if (h < _maximum && h > _minimum) { float x = GetPosition(h); if (x > -32000 && x < 32000) g.DrawLine(p, x, gb.Top, x, gb.Bottom); } if (l < _maximum && l > _minimum) { float x = GetPosition(l); if (x > -32000 && x < 32000) g.DrawLine(p, x, gb.Top, x, gb.Bottom); } } p.Dispose(); } } private void DrawColumns(Graphics g, Rectangle clip) { if (_numColumns == 0 || _maxBinCount == 0) return; Rectangle gb = GetGraphBounds(); float dX = (gb.Width) / (float)_numColumns; float dY = (gb.Height) / (float)_maxBinCount; if (_maxBinCount == 0) return; if (_logY) dY = (float)((gb.Height) / Math.Log(_maxBinCount)); for (int i = 0; i < _numColumns; i++) { if (_bins[i] == 0) continue; float h = dY * _bins[i]; if (_logY) h = (float)((dY) * Math.Log(_bins[i])); if (h < _minHeight) h = _minHeight; RectangleF rect = new RectangleF(dX * i + gb.X, gb.Height - h + gb.Y, dX, h); if (!clip.IntersectsWith(rect)) continue; Color light = Color.LightGray; Color dark = Color.DarkGray; double centerValue = CenterValue(i); if (_colorRanges != null) { foreach (ColorRange item in _colorRanges) { if (!item.Contains(centerValue)) continue; Color c = item.Color; light = c.Lighter(.2f); dark = c.Darker(.2f); break; } } LinearGradientBrush lgb = new LinearGradientBrush(rect, light, dark, LinearGradientMode.Horizontal); g.FillRectangle(lgb, rect.X, rect.Y, rect.Width, rect.Height); lgb.Dispose(); } } /// <summary> /// Given a double value, this returns the floating point position on this graph, /// based on the current minimum, maximum values. /// </summary> /// <param name="value">The double value to locate</param> /// <returns>A floating point X position</returns> public float GetPosition(double value) { Rectangle gb = GetGraphBounds(); return (float)(gb.Width * (value - _minimum) / (_maximum - _minimum) + gb.X); } /// <summary> /// Given a floating point X coordinate (relative to the control, not just the graph) /// this will return the double value represented by that location. /// </summary> /// <param name="position">The floating point position</param> /// <returns>The double value at the specified X coordinate</returns> public double GetValue(float position) { Rectangle gb = GetGraphBounds(); return ((position - gb.X) / gb.Width) * (_maximum - _minimum) + _minimum; } private void DrawSelectionHighlight(Graphics g, Rectangle clip, Rectangle gb) { if (_selectedRange == null) return; int index = _colorRanges.IndexOf(_selectedRange); if (index < 0) return; float left = gb.Left; if (_selectedRange.Range.Maximum < _minimum) return; if (_selectedRange.Range.Minimum > _maximum) return; if (_selectedRange.Range.Minimum != null) { float rangeLeft = GetPosition(_selectedRange.Range.Minimum.Value); if (rangeLeft > left) left = rangeLeft; } float right = gb.Right; if (_selectedRange.Range.Maximum != null) { float rangeRight = GetPosition(_selectedRange.Range.Maximum.Value); if (rangeRight < right) right = rangeRight; } Rectangle selectionRect = new Rectangle((int)left, gb.Top, (int)(right - left), gb.Height); if (!clip.IntersectsWith(selectionRect)) return; GraphicsPath gp = new GraphicsPath(); gp.AddRoundedRectangle(selectionRect, 2); if (selectionRect.Width != 0 && selectionRect.Height != 0) { LinearGradientBrush lgb = new LinearGradientBrush(selectionRect, Color.FromArgb(241, 248, 253), Color.FromArgb(213, 239, 252), LinearGradientMode.ForwardDiagonal); g.FillPath(lgb, gp); lgb.Dispose(); } gp.Dispose(); } /// <summary> /// Gets the real data value at the center of one of the bins. /// </summary> /// <param name="binIndex"></param> /// <returns></returns> public double CenterValue(int binIndex) { return _minimum + (_maximum - _minimum) * (binIndex + .5) / NumColumns; } private static string Format(double value) { if (Math.Abs(value) < 1) return value.ToString("E4"); if (value < 1E10) return value.ToString("#, ###"); return value.ToString("E4"); } /// <summary> /// Draws only the text for this bar graph. This will also calculate some critical /// font measurements to help size the internal part of the graph. /// </summary> /// <param name="g"></param> public void DrawText(Graphics g) { _titleHeight = (int)Math.Ceiling(g.MeasureString("My", _titleFont.GetFont()).Height); Font fnt = _font.GetFont(); string min = Format(_minimum); SizeF minSize = g.MeasureString(min, fnt); string max = Format(_maximum); SizeF maxSize = g.MeasureString(max, fnt); string mid = Format((_maximum + _minimum) / 2); SizeF midSize = g.MeasureString(mid, fnt); _axisTextHeight = (int)(Math.Ceiling(Math.Max(Math.Max(minSize.Height, maxSize.Height), midSize.Height))); _axisTextHeight += 10; const string one = "1"; SizeF oneSize = g.MeasureString(one, fnt); string count = Format(_maxBinCount); SizeF countSize = g.MeasureString(count, fnt); SizeF halfSize = new SizeF(0, 0); string halfCount = string.Empty; if (_maxBinCount > 1) { halfCount = Format(_maxBinCount / 2f); if (_logY) halfCount = Format(Math.Exp(Math.Log(_maxBinCount) / 2)); halfSize = g.MeasureString(halfCount, fnt); } _countTextWidth = (int)(Math.Ceiling(Math.Max(Math.Max(oneSize.Width, countSize.Width), halfSize.Width))); _countTextWidth += 20; Rectangle gb = GetGraphBounds(); _font.Draw(g, min, gb.X, gb.Bottom + 15); g.DrawLine(Pens.Black, gb.Left, gb.Bottom, gb.Left, gb.Bottom + 10); _font.Draw(g, max, gb.Right - maxSize.Width, gb.Bottom + 15); g.DrawLine(Pens.Black, gb.Left + gb.Width / 2, gb.Bottom, gb.Left + gb.Width / 2, gb.Bottom + 10); _font.Draw(g, mid, gb.X + gb.Width / 2 - midSize.Width / 2, gb.Bottom + 15); g.DrawLine(Pens.Black, gb.Right, gb.Bottom, gb.Right, gb.Bottom + 10); float dY; if (_maxBinCount == 0) { dY = _minHeight; } else { dY = (gb.Height) / (float)_maxBinCount; } float oneH = Math.Max(dY, _minHeight); _font.Draw(g, one, gb.Left - oneSize.Width - 15, gb.Bottom - oneSize.Height / 2 - oneH); g.DrawLine(Pens.Black, gb.Left - 10, gb.Bottom - oneH, gb.Left, gb.Bottom - oneH); if (_maxBinCount > 1) { _font.Draw(g, count, gb.Left - countSize.Width - 15, gb.Top); g.DrawLine(Pens.Black, gb.Left - 20, gb.Top, gb.Left, gb.Top); _font.Draw(g, halfCount, gb.Left - halfSize.Width - 15, gb.Top + gb.Height / 2 - halfSize.Height / 2); g.DrawLine(Pens.Black, gb.Left - 10, gb.Top + gb.Height / 2, gb.Left, gb.Top + gb.Height / 2); } SizeF titleSize = g.MeasureString(_title, _titleFont.GetFont()); _titleFont.Draw(g, _title, gb.X + gb.Width / 2 - titleSize.Width / 2, 2.5f); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace NuGet { public static class PackageRepositoryExtensions { public static bool Exists(this IPackageRepository repository, IPackageMetadata package) { return repository.Exists(package.Id, package.Version); } public static bool Exists(this IPackageRepository repository, string packageId) { return Exists(repository, packageId, version: null); } public static bool Exists(this IPackageRepository repository, string packageId, Version version) { return repository.FindPackage(packageId, version) != null; } public static bool TryFindPackage(this IPackageRepository repository, string packageId, Version version, out IPackage package) { package = repository.FindPackage(packageId, version); return package != null; } public static IPackage FindPackage(this IPackageRepository repository, string packageId) { return repository.FindPackage(packageId, version: null); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, string versionSpec) { if (versionSpec == null) { throw new ArgumentNullException("versionSpec"); } return repository.FindPackage(packageId, VersionUtility.ParseVersionSpec(versionSpec)); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, Version version) { if (repository == null) { throw new ArgumentNullException("repository"); } if (packageId == null) { throw new ArgumentNullException("packageId"); } // If the repository implements it's own lookup then use that instead. // This is an optimization that we use so we don't have to enumerate packages for // sources that don't need to. var packageLookup = repository as IPackageLookup; if (packageLookup != null && version != null) { return packageLookup.FindPackage(packageId, version); } IEnumerable<IPackage> packages = repository.FindPackagesById(packageId) .ToList() .OrderByDescending(p => p.Version); if (version != null) { packages = packages.Where(p => p.Version == version); } return packages.FirstOrDefault(); } public static IEnumerable<IPackage> FindPackages(this IPackageRepository repository, IEnumerable<string> packageIds) { if (packageIds == null) { throw new ArgumentNullException("packageIds"); } return FindPackages(repository, packageIds, GetFilterExpression); } public static IQueryable<IPackage> FindPackagesById(this IPackageRepository repository, string packageId) { return from p in repository.GetPackages() where p.Id.ToLower() == packageId.ToLower() orderby p.Id select p; } /// <summary> /// Since Odata dies when our query for updates is too big. We query for updates 10 packages at a time /// and return the full list of packages. /// </summary> private static IEnumerable<IPackage> FindPackages<T>(this IPackageRepository repository, IEnumerable<T> items, Func<IEnumerable<T>, Expression<Func<IPackage, bool>>> filterSelector) { const int batchSize = 10; while (items.Any()) { IEnumerable<T> currentItems = items.Take(batchSize); Expression<Func<IPackage, bool>> filterExpression = filterSelector(currentItems); var query = repository.GetPackages().Where(filterExpression).OrderBy(p => p.Id); foreach (var package in query) { yield return package; } items = items.Skip(batchSize); } } public static IPackage FindPackage(this IPackageRepository repository, string packageId, IVersionSpec versionInfo) { if (repository == null) { throw new ArgumentNullException("repository"); } if (packageId == null) { throw new ArgumentNullException("packageId"); } IEnumerable<IPackage> packages = repository.FindPackagesById(packageId) .ToList() .OrderByDescending(p => p.Version); if (versionInfo != null) { packages = packages.FindByVersion(versionInfo); } return packages.FirstOrDefault(); } public static IPackage FindDependency(this IPackageRepository repository, PackageDependency dependency) { if (repository == null) { throw new ArgumentNullException("repository"); } if (dependency == null) { throw new ArgumentNullException("dependency"); } // When looking for dependencies, order by lowest version IEnumerable<IPackage> packages = repository.FindPackagesById(dependency.Id) .ToList(); // If version info was specified then use it if (dependency.VersionSpec != null) { packages = packages.FindByVersion(dependency.VersionSpec); } else { // BUG 840: If no version info was specified then pick the latest return packages.OrderByDescending(p => p.Version) .FirstOrDefault(); } if (packages.Any()) { // We want to take the biggest build and revision number for the smallest // major and minor combination (we want to make some versioning assumptions that the 3rd number is a non-breaking bug fix). This is so that we get the closest version // to the dependency, but also get bug fixes without requiring people to manually update the nuspec. // For example, if A -> B 1.0.0 and the feed has B 1.0.0 and B 1.0.1 then the more correct choice is B 1.0.1. // If we don't do this, A will always end up getting the 'buggy' 1.0.0, // unless someone explicitly changes it to ask for 1.0.1, which is very painful if many packages are using B 1.0.0. var groups = from p in packages group p by new { p.Version.Major, p.Version.Minor } into g orderby g.Key.Major, g.Key.Minor select g; return (from p in groups.First() orderby p.Version descending select p).FirstOrDefault(); } return null; } /// <summary> /// Returns updates for packages from the repository /// </summary> /// <param name="repository">The repository to search for updates</param> /// <param name="packages">Packages to look for updates</param> /// <returns></returns> public static IEnumerable<IPackage> GetUpdates(this IPackageRepository repository, IEnumerable<IPackage> packages) { List<IPackage> packageList = packages.ToList(); if (!packageList.Any()) { yield break; } // These are the packages that we need to look at for potential updates. IDictionary<string, IPackage> sourcePackages = GetUpdateCandidates(repository, packageList) .ToList() .GroupBy(package => package.Id) .ToDictionary(package => package.Key, package => package.OrderByDescending(p => p.Version).First()); foreach (IPackage package in packageList) { IPackage newestAvailablePackage; if (sourcePackages.TryGetValue(package.Id, out newestAvailablePackage) && newestAvailablePackage.Version > package.Version) { yield return newestAvailablePackage; } } } /// <summary> /// Since odata dies when our query for updates is too big. We query for updates 10 packages at a time /// and return the full list of candidates for updates. /// </summary> private static IEnumerable<IPackage> GetUpdateCandidates(IPackageRepository repository, IEnumerable<IPackage> packages) { return FindPackages(repository, packages, GetFilterExpression); } /// <summary> /// For the list of input packages generate an expression like: /// p => p.Id == 'package1id' or p.Id == 'package2id' or p.Id == 'package3id'... up to package n /// </summary> private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<IPackage> packages) { return GetFilterExpression(packages.Select(p => p.Id)); } [SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "This is for a linq query")] private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<string> ids) { ParameterExpression parameterExpression = Expression.Parameter(typeof(IPackageMetadata)); Expression expressionBody = ids.Select(id => GetCompareExpression(parameterExpression, id.ToLower())) .Aggregate(Expression.OrElse); return Expression.Lambda<Func<IPackage, bool>>(expressionBody, parameterExpression); } /// <summary> /// Builds the expression: package.Id.ToLower() == "somepackageid" /// </summary> private static Expression GetCompareExpression(Expression parameterExpression, object value) { // package.Id Expression propertyExpression = Expression.Property(parameterExpression, "Id"); // .ToLower() Expression toLowerExpression = Expression.Call(propertyExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes)); // == localPackage.Id return Expression.Equal(toLowerExpression, Expression.Constant(value)); } // HACK: We need this to avoid a partial trust issue. We need to be able to evaluate closures // within this class internal static object Eval(FieldInfo fieldInfo, object obj) { return fieldInfo.GetValue(obj); } } }
// 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. namespace System.ServiceModel.Syndication { using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; // sealed because the ctor results in a call to the virtual InsertItem method public sealed class SyndicationElementExtensionCollection : Collection<SyndicationElementExtension> { private XmlBuffer _buffer; private bool _initialized; internal SyndicationElementExtensionCollection() : this((XmlBuffer)null) { } internal SyndicationElementExtensionCollection(XmlBuffer buffer) : base() { _buffer = buffer; if (_buffer != null) { PopulateElements(); } _initialized = true; } internal SyndicationElementExtensionCollection(SyndicationElementExtensionCollection source) : base() { _buffer = source._buffer; for (int i = 0; i < source.Items.Count; ++i) { base.Add(source.Items[i]); } _initialized = true; } public void Add(object extension) { if (extension is SyndicationElementExtension) { base.Add((SyndicationElementExtension)extension); } else { this.Add(extension, (DataContractSerializer)null); } } public void Add(string outerName, string outerNamespace, object dataContractExtension) { this.Add(outerName, outerNamespace, dataContractExtension, null); } public void Add(object dataContractExtension, DataContractSerializer serializer) { this.Add(null, null, dataContractExtension, serializer); } public void Add(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { if (dataContractExtension == null) { throw new ArgumentNullException(nameof(dataContractExtension)); } if (dataContractSerializer == null) { dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); } base.Add(new SyndicationElementExtension(outerName, outerNamespace, dataContractExtension, dataContractSerializer)); } public void Add(object xmlSerializerExtension, XmlSerializer serializer) { if (xmlSerializerExtension == null) { throw new ArgumentNullException(nameof(xmlSerializerExtension)); } if (serializer == null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); } base.Add(new SyndicationElementExtension(xmlSerializerExtension, serializer)); } public void Add(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } base.Add(new SyndicationElementExtension(reader)); } public async Task<XmlReader> GetReaderAtElementExtensions() { XmlBuffer extensionsBuffer = await GetOrCreateBufferOverExtensions(); XmlReader reader = extensionsBuffer.GetReader(0); reader.ReadStartElement(); return reader; } public Task<Collection<TExtension>> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace) { return ReadElementExtensions<TExtension>(extensionName, extensionNamespace, new DataContractSerializer(typeof(TExtension))); } public Task<Collection<TExtension>> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer serializer) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } return ReadExtensions<TExtension>(extensionName, extensionNamespace, serializer, null); } public Task<Collection<TExtension>> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlSerializer serializer) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } return ReadExtensions<TExtension>(extensionName, extensionNamespace, null, serializer); } internal async Task WriteToAsync(XmlWriter writer) { if (_buffer != null) { using (XmlDictionaryReader reader = _buffer.GetReader(0)) { reader.ReadStartElement(); while (reader.IsStartElement()) { await writer.WriteNodeAsync(reader, false); } } } else { for (int i = 0; i < this.Items.Count; ++i) { await this.Items[i].WriteToAsync(writer); } } } protected override void ClearItems() { base.ClearItems(); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void InsertItem(int index, SyndicationElementExtension item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } base.InsertItem(index, item); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void RemoveItem(int index) { base.RemoveItem(index); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void SetItem(int index, SyndicationElementExtension item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } base.SetItem(index, item); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } private async Task<XmlBuffer> GetOrCreateBufferOverExtensions() { if (_buffer != null) { return _buffer; } XmlBuffer newBuffer = new XmlBuffer(int.MaxValue); using (XmlWriter writer = newBuffer.OpenSection(XmlDictionaryReaderQuotas.Max)) { writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag); for (int i = 0; i < this.Count; ++i) { await this[i].WriteToAsync(writer); } writer.WriteEndElement(); } newBuffer.CloseSection(); newBuffer.Close(); _buffer = newBuffer; return newBuffer; } private void PopulateElements() { using (XmlDictionaryReader reader = _buffer.GetReader(0)) { reader.ReadStartElement(); int index = 0; while (reader.IsStartElement()) { base.Add(new SyndicationElementExtension(_buffer, index, reader.LocalName, reader.NamespaceURI)); reader.Skip(); ++index; } } } private async Task<Collection<TExtension>> ReadExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer dcSerializer, XmlSerializer xmlSerializer) { if (string.IsNullOrEmpty(extensionName)) { throw new ArgumentNullException(SR.ExtensionNameNotSpecified); } Debug.Assert((dcSerializer == null) != (xmlSerializer == null), "exactly one serializer should be supplied"); // normalize the null and empty namespace if (extensionNamespace == null) { extensionNamespace = string.Empty; } Collection<TExtension> results = new Collection<TExtension>(); for (int i = 0; i < this.Count; ++i) { if (extensionName != this[i].OuterName || extensionNamespace != this[i].OuterNamespace) { continue; } if (dcSerializer != null) { results.Add(await this[i].GetObject<TExtension>(dcSerializer)); } else { results.Add(await this[i].GetObject<TExtension>(xmlSerializer)); } } return results; } } }
#region File Description //----------------------------------------------------------------------------- // InputState.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using SharpDX.DirectInput; using Spectrum.Framework.VR; using System; using System.Linq; using System.Collections.Generic; #endregion namespace Spectrum.Framework.Input { [Flags] public enum KeyPressType { None, Press, Release, Hold, } public class InputState { public static float MouseSensitivity = 0.003f; public static SpectrumMouse SpecMouse = new SpectrumMouse(); public static InputState Current { get; private set; } = new InputState(); public float DT; public Microsoft.Xna.Framework.Input.KeyboardState KeyboardState; public CursorState CursorState; public Gamepad[] Gamepads = new Gamepad[4]; public VRHMD VRHMD = new VRHMD(); public VRController[] VRControllers = new VRController[] { new VRController(VRHand.Left), new VRController(VRHand.Right) }; public VRController VRFromHand(VRHand hand) => VRControllers[hand == VRHand.Right ? 1 : 0]; public InputState Last; public bool DisableCursorState { get; private set; } public DefaultDict<KeyBind, bool> consumedKeys = new DefaultDict<KeyBind, bool>(); public InputState(bool disableCursorState = false) { DisableCursorState = disableCursorState; KeyboardState = Microsoft.Xna.Framework.Input.Keyboard.GetState(); if (!DisableCursorState) CursorState = SpecMouse.GetCurrentState(); Last = null; for (int i = 0; i < 4; i++) { Gamepads[i] = new Gamepad(new SharpDX.XInput.Controller((SharpDX.XInput.UserIndex)i)); } } #region Public Methods public void Update(float dt) { if (Last == null) Last = new InputState(); Last.DT = DT; DT = dt; Last.KeyboardState = KeyboardState; KeyboardState = Microsoft.Xna.Framework.Input.Keyboard.GetState(); Last.CursorState = CursorState; if (!DisableCursorState) CursorState = SpecMouse.GetCurrentState(CursorState); for (int i = 0; i < 4; i++) { Last.Gamepads[i] = Gamepads[i]; Gamepads[i].Update(); } if (SpecVR.Running) { Last.VRHMD = VRHMD; VRHMD.Update(); for (int i = 0; i < 2; i++) { Last.VRControllers[i] = VRControllers[i]; VRControllers[i].Update(); } } if (!DisableCursorState) RawMouse.Update(); foreach (var kvp in consumedKeys.ToList()) { // Clear when the key is up and either we only consumed the press OR the release has passed as well if (!IsKeyDown(kvp.Key, false) && (!kvp.Value || !IsNewKeyRelease(kvp.Key, false))) consumedKeys.Remove(kvp.Key); } } public void ConsumeInput(KeyBind key, bool hold) => consumedKeys[key] |= hold; public bool IsConsumed(KeyBind key) => consumedKeys.ContainsKey(key); public bool IsKeyDown(string bindingName, PlayerInformation playerInfo = null) { InputLayout layout = (playerInfo ?? PlayerInformation.Default).Layout; if (!layout.KeyBindings.TryGetValue(bindingName, out KeyBinding binding)) { DebugPrinter.PrintOnce("Binding not found " + bindingName); return false; } return IsKeyDown(binding); } public bool IsKeyDown(KeyBinding binding, bool consultConsumed = true) { return binding.Options.Any(button => IsKeyDown(button, consultConsumed)); } public bool IsKeyDown(KeyBind button, bool consultConsumed = true) { if (consultConsumed && consumedKeys.ContainsKey(button)) return false; if (!button.modifiers.All(modifier => IsKeyDown(modifier))) return false; if ((button.key != null && KeyboardState.IsKeyDown(button.key.Value)) || (button.mouseButton != null && IsMouseDown(button.mouseButton.Value))) return true; // TODO: Use a field in KeyBind to specify the gamepad index //foreach (int gamepadIndex in playerInfo.UsedGamepads) //{ // if (button.button != null && Gamepads[gamepadIndex].IsButtonPressed(button.button)) { return true; } //} if (SpecVR.Running && button.vrButton != null) if (VRControllers.Any(controller => controller.IsButtonPressed(button.vrButton.Value))) return true; return false; } public bool IsNewKeyPress(string bindingName, PlayerInformation playerInfo = null) => IsKeyDown(bindingName, playerInfo) && !Last.IsKeyDown(bindingName, playerInfo); public bool IsNewKeyPress(KeyBinding binding, bool consultConsumed = true) => binding.Options.Any(b => IsNewKeyPress(b, consultConsumed)); public bool IsNewKeyPress(KeyBind button, bool consultConsumed = true) => (!consultConsumed || !consumedKeys.ContainsKey(button)) && IsKeyDown(button, false) && !Last.IsKeyDown(button, false); public bool IsNewKeyRelease(string bindingName, PlayerInformation playerInfo = null) => !IsKeyDown(bindingName, playerInfo) && Last.IsKeyDown(bindingName, playerInfo); public bool IsNewKeyRelease(KeyBinding binding, bool consultConsumed = true) => binding.Options.Any(b => IsNewKeyRelease(b, consultConsumed)); public bool IsNewKeyRelease(KeyBind button, bool consultConsumed = true) => (!consultConsumed || !consumedKeys.ContainsKey(button)) && !IsKeyDown(button, false) && Last.IsKeyDown(button, false); public float GetAxis1D(string axisName, PlayerInformation playerInfo = null) { playerInfo = playerInfo ?? PlayerInformation.Default; InputLayout layout = playerInfo.Layout; if (!layout.Axes1.TryGetValue(axisName, out Axis1 axis)) throw new KeyNotFoundException("Axis not found"); return axis.Value(this, playerInfo); } public Vector2 GetAxis2D(string horizontal, string vertical, bool limitToOne = false, PlayerInformation playerInfo = null) { Vector2 output = new Vector2(GetAxis1D(horizontal, playerInfo), GetAxis1D(vertical, playerInfo)); if (limitToOne && output.LengthSquared > 1) output.Normalize(); return output; } public Point MousePosition => CursorState.P; public bool IsMouseDown(int button) { if (button >= (CursorState?.buttons?.Length ?? 0)) return false; if (button >= 0) return CursorState.buttons[button]; if (button == -1) return MouseScrollY > 0; if (button == -2) return MouseScrollY < 0; if (button == -3) return MouseScrollX > 0; if (button == -4) return MouseScrollX < 0; return false; } public bool IsNewMousePress(int button) => button < (CursorState?.buttons?.Length ?? 0) && IsMouseDown(button) && !Last.IsMouseDown(button); public bool IsNewMouseRelease(int button) => button < (CursorState?.buttons?.Length ?? 0) && !IsMouseDown(button) && Last.IsMouseDown(button); public int MouseScrollY => CursorState?.ScrollY ?? 0; public int MouseScrollX => CursorState?.ScrollX ?? 0; #endregion /// <summary> /// Helps take keyboard input for a text box or something. /// Should be called in HandleInput /// </summary> /// <param name="currentString">The string being modified</param> /// <param name="input">Input from the HandleInput call</param> /// <returns>Modified string</returns> public void TakeKeyboardInput(ref int position, ref string currentString) { position = Math.Max(Math.Min(position, currentString.Length), 0); Keys[] pressedKeys = KeyboardState.GetPressedKeys(); foreach (Keys key in pressedKeys) { if (IsNewKeyPress(key)) { if (key == Keys.Back && position > 0) { int count = 0; if (IsKeyDown(Keys.LeftControl) || IsKeyDown(Keys.RightControl)) { while (count < currentString.Length - 1 && currentString[currentString.Length - 1 - count] != ' ') count++; } count++; position -= count; currentString = currentString.Remove(position, count); } if (key == Keys.Right && position < currentString.Length) position++; if (key == Keys.Left && position > 0) position--; char typedChar = GetChar(key, IsKeyDown(Keys.LeftShift) || IsKeyDown(Keys.RightShift)); if (typedChar != (char)0) { currentString = currentString.Insert(position, "" + typedChar); position++; } } } } private static char GetChar(Keys key, bool shiftHeld) { if (key == Keys.Space) return ' '; if (key >= Keys.A && key <= Keys.Z) { if (shiftHeld) { return key.ToString()[0]; } else { return key.ToString().ToLower()[0]; } } if (key >= Keys.D0 && key <= Keys.D9) { if (shiftHeld) { if (key == Keys.D2) return '@'; else if (key == Keys.D0) return ')'; else if (key == Keys.D6) return '^'; else if (key == Keys.D8) return '*'; else { if (key > Keys.D5) { return (char)(key - Keys.D0 + 31); } else return (char)(key - Keys.D0 + 32); } } else return (key - Keys.D0).ToString()[0]; } if (key >= Keys.NumPad0 && key <= Keys.NumPad9) return (key - Keys.NumPad0).ToString()[0]; if (key == Keys.OemPeriod || key == Keys.Decimal) return '.'; if (key == Keys.OemQuestion) return '/'; return (char)0; } } }
// DirectXTK MakeSpriteFont tool // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 using System; using System.Collections.Generic; using System.Globalization; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using System.Runtime.InteropServices; namespace MakeSpriteFont { // Uses System.Drawing (aka GDI+) to rasterize TrueType fonts into a series of glyph bitmaps. public class TrueTypeImporter : IFontImporter { // Properties hold the imported font data. public IEnumerable<Glyph> Glyphs { get; private set; } public float LineSpacing { get; private set; } // Size of the temp surface used for GDI+ rasterization. const int MaxGlyphSize = 1024; public void Import(CommandLineOptions options) { // Create a bunch of GDI+ objects. using (Font font = CreateFont(options)) using (Brush brush = new SolidBrush(Color.White)) using (StringFormat stringFormat = new StringFormat(StringFormatFlags.NoFontFallback)) using (Bitmap bitmap = new Bitmap(MaxGlyphSize, MaxGlyphSize, PixelFormat.Format32bppArgb)) using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.PixelOffsetMode = options.Sharp ? PixelOffsetMode.None : PixelOffsetMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; // Which characters do we want to include? var characters = CharacterRegion.Flatten(options.CharacterRegions); var glyphList = new List<Glyph>(); // Rasterize each character in turn. int count = 0; foreach (char character in characters) { ++count; if (count == 500) { if (!options.FastPack) { Console.WriteLine("WARNING: capturing a large font. This may take a long time to complete and could result in too large a texture. Consider using /FastPack."); } Console.Write("."); } else if ((count % 500) == 0) { Console.Write("."); } Glyph glyph = ImportGlyph(character, font, brush, stringFormat, bitmap, graphics); glyphList.Add(glyph); } if (count > 500) { Console.WriteLine(); } Glyphs = glyphList; // Store the font height. LineSpacing = font.GetHeight(); } } // Attempts to instantiate the requested GDI+ font object. static Font CreateFont(CommandLineOptions options) { Font font = new Font(options.SourceFont, PointsToPixels(options.FontSize), options.FontStyle, GraphicsUnit.Pixel); try { // The font constructor automatically substitutes fonts if it can't find the one requested. // But we prefer the caller to know if anything is wrong with their data. A simple string compare // isn't sufficient because some fonts (eg. MS Mincho) change names depending on the locale. // Early out: in most cases the name will match the current or invariant culture. if (options.SourceFont.Equals(font.FontFamily.GetName(CultureInfo.CurrentCulture.LCID), StringComparison.OrdinalIgnoreCase) || options.SourceFont.Equals(font.FontFamily.GetName(CultureInfo.InvariantCulture.LCID), StringComparison.OrdinalIgnoreCase)) { return font; } // Check the font name in every culture. foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) { if (options.SourceFont.Equals(font.FontFamily.GetName(culture.LCID), StringComparison.OrdinalIgnoreCase)) { return font; } } // A font substitution must have occurred. throw new Exception(string.Format("Can't find font '{0}'.", options.SourceFont)); } catch { font.Dispose(); throw; } } // Converts a font size from points to pixels. Can't just let GDI+ do this for us, // because we want identical results on every machine regardless of system DPI settings. static float PointsToPixels(float points) { return points * 96 / 72; } // Rasterizes a single character glyph. static Glyph ImportGlyph(char character, Font font, Brush brush, StringFormat stringFormat, Bitmap bitmap, Graphics graphics) { string characterString = character.ToString(); // Measure the size of this character. SizeF size = graphics.MeasureString(characterString, font, Point.Empty, stringFormat); int characterWidth = (int)Math.Ceiling(size.Width); int characterHeight = (int)Math.Ceiling(size.Height); // Pad to make sure we capture any overhangs (negative ABC spacing, etc.) int padWidth = characterWidth; int padHeight = characterHeight / 2; int bitmapWidth = characterWidth + padWidth * 2; int bitmapHeight = characterHeight + padHeight * 2; if (bitmapWidth > MaxGlyphSize || bitmapHeight > MaxGlyphSize) throw new Exception("Excessively large glyph won't fit in my lazily implemented fixed size temp surface."); // Render the character. graphics.Clear(Color.Black); graphics.DrawString(characterString, font, brush, padWidth, padHeight, stringFormat); graphics.Flush(); // Clone the newly rendered image. Bitmap glyphBitmap = bitmap.Clone(new Rectangle(0, 0, bitmapWidth, bitmapHeight), PixelFormat.Format32bppArgb); BitmapUtils.ConvertGreyToAlpha(glyphBitmap); // Query its ABC spacing. float? abc = GetCharacterWidth(character, font, graphics); // Construct the output Glyph object. return new Glyph(character, glyphBitmap) { XOffset = -padWidth, XAdvance = abc.HasValue ? padWidth - bitmapWidth + abc.Value : -padWidth, YOffset = -padHeight, }; } // Queries APC spacing for the specified character. static float? GetCharacterWidth(char character, Font font, Graphics graphics) { // Look up the native device context and font handles. IntPtr hdc = graphics.GetHdc(); try { IntPtr hFont = font.ToHfont(); try { // Select our font into the DC. IntPtr oldFont = NativeMethods.SelectObject(hdc, hFont); try { // Query the character spacing. var result = new NativeMethods.ABCFloat[1]; if (NativeMethods.GetCharABCWidthsFloat(hdc, character, character, result)) { return result[0].A + result[0].B + result[0].C; } else { return null; } } finally { NativeMethods.SelectObject(hdc, oldFont); } } finally { NativeMethods.DeleteObject(hFont); } } finally { graphics.ReleaseHdc(hdc); } } // Interop to the native GDI GetCharABCWidthsFloat method. static class NativeMethods { [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll", CharSet = CharSet.Unicode)] public static extern bool GetCharABCWidthsFloat(IntPtr hdc, uint iFirstChar, uint iLastChar, [Out] ABCFloat[] lpABCF); [StructLayout(LayoutKind.Sequential)] public struct ABCFloat { public float A; public float B; public float C; } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // All code in this file requires .NET Framework 2.0 or later. #if !NET_1_1 && !NET_1_0 [assembly: Elmah.Scc("$Id$")] namespace Elmah { #region Imports using System; using System.Collections; using System.Data; using System.Data.SQLite; using System.Globalization; using System.IO; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses SQLite as its backing store. /// </summary> public class SQLiteErrorLog : ErrorLog { private readonly string _connectionString; /// <summary> /// Initializes a new instance of the <see cref="SQLiteErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public SQLiteErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); string connectionString = ConnectionStringHelper.GetConnectionString(config, true); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new ApplicationException("Connection string is missing for the SQLite error log."); _connectionString = connectionString; InitializeDatabase(); ApplicationName = Mask.NullString((string) config["applicationName"]); } /// <summary> /// Initializes a new instance of the <see cref="SQLiteErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public SQLiteErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = ConnectionStringHelper.GetResolvedConnectionString(connectionString); InitializeDatabase(); } private static readonly object _lock = new object(); private void InitializeDatabase() { string connectionString = ConnectionString; Debug.AssertStringNotEmpty(connectionString); string dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString); if (File.Exists(dbFilePath)) return; // // Make sure that we don't have multiple threads all trying to create the database // lock (_lock) { // // Just double check that no other thread has created the database while // we were waiting for the lock // if (File.Exists(dbFilePath)) return; SQLiteConnection.CreateFile(dbFilePath); const string sql = @" CREATE TABLE Error ( ErrorId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Application TEXT NOT NULL, Host TEXT NOT NULL, Type TEXT NOT NULL, Source TEXT NOT NULL, Message TEXT NOT NULL, User TEXT NOT NULL, StatusCode INTEGER NOT NULL, TimeUtc TEXT NOT NULL, AllXml TEXT NOT NULL )"; using (SQLiteConnection connection = new SQLiteConnection(connectionString)) using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { connection.Open(); command.ExecuteNonQuery(); } } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "SQLite Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); const string query = @" INSERT INTO Error ( Application, Host, Type, Source, Message, User, StatusCode, TimeUtc, AllXml) VALUES ( @Application, @Host, @Type, @Source, @Message, @User, @StatusCode, @TimeUtc, @AllXml); SELECT last_insert_rowid();"; using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) using (SQLiteCommand command = new SQLiteCommand(query, connection)) { SQLiteParameterCollection parameters = command.Parameters; parameters.Add("@Application", DbType.String, 60).Value = ApplicationName; parameters.Add("@Host", DbType.String, 30).Value = error.HostName; parameters.Add("@Type", DbType.String, 100).Value = error.Type; parameters.Add("@Source", DbType.String, 60).Value = error.Source; parameters.Add("@Message", DbType.String, 500).Value = error.Message; parameters.Add("@User", DbType.String, 50).Value = error.User; parameters.Add("@StatusCode", DbType.Int64).Value = error.StatusCode; parameters.Add("@TimeUtc", DbType.DateTime).Value = error.Time.ToUniversalTime(); parameters.Add("@AllXml", DbType.String).Value = errorXml; connection.Open(); return Convert.ToInt64(command.ExecuteScalar()).ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); const string sql = @" SELECT ErrorId, Application, Host, Type, Source, Message, User, StatusCode, TimeUtc FROM Error ORDER BY ErrorId DESC LIMIT @PageIndex * @PageSize, @PageSize; SELECT COUNT(*) FROM Error"; using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { SQLiteParameterCollection parameters = command.Parameters; parameters.Add("@PageIndex", DbType.Int16).Value = pageIndex; parameters.Add("@PageSize", DbType.Int16).Value = pageSize; connection.Open(); using (SQLiteDataReader reader = command.ExecuteReader()) { if (errorEntryList != null) { while (reader.Read()) { string id = Convert.ToString(reader["ErrorId"], CultureInfo.InvariantCulture); Error error = new Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["User"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, id, error)); } } // // Get the result of SELECT COUNT(*) FROM Page // reader.NextResult(); reader.Read(); return reader.GetInt32(0); } } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); long key; try { key = long.Parse(id, CultureInfo.InvariantCulture); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } const string sql = @" SELECT AllXml FROM Error WHERE ErrorId = @ErrorId"; using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { SQLiteParameterCollection parameters = command.Parameters; parameters.Add("@ErrorId", DbType.Int64).Value = key; connection.Open(); string errorXml = (string) command.ExecuteScalar(); if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } } } } #endif //!NET_1_1 && !NET_1_0
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; public class Player { private List<IUnit> _units = new List<IUnit>(); private List<IBuilding> _buildings = new List<IBuilding>(); private Dictionary<MaterialType, int> _materialQuantity = new Dictionary<MaterialType, int> (); private bool _isHuman; private bool _isMain; public Color _stickColor; public GameObject[] _ghostObjects; private Transform _selectionBox; private Vector2 screenSelectionStartPoint; private Vector2 screenSelectionEndPoint; private Vector3 sceneSelectionStartPoint; private Vector3 sceneSelectionEndPoint; private Player _controlledPlayer; private List<IUnit> _selectedUnits = new List<IUnit>(); private RaycastHit[] _selectedUnitsToSave; private bool _multiSelection = false; private bool _selectionEnded = false; private float _xUnitPer3DUnit; private float _yUnitPer3DUnit; private int _minMouseDrag = 10; private bool _mouseOnGui = false; private bool _showBuildingOptions = false; private bool _ignoreClick = false; private GameObject _grid; private IBuilding _selectedBuilding; public Player (bool isHuman, bool isMain, Dictionary<MaterialType,int> startingQuantity) { _isHuman = isHuman; _isMain = isMain; _materialQuantity = new Dictionary<MaterialType, int> (startingQuantity); } public bool IsMain{ get { return _isMain; } } public void AddUnit(IUnit unit){ _units.Add (unit); } public void AddBuilding(IBuilding building){ _buildings.Add (building); } public void Start(Transform selectionBox, GameObject grid, ref GameObject[] ghostObjects){ _selectionBox = selectionBox; _selectionBox.parent = null; _ghostObjects = ghostObjects; _grid = grid; ConvertSceneToScreenScale (); } // Update is called once per frame public void Update () { //Unit Selection Region if (!_mouseOnGui) { _ignoreClick = false; if (Input.GetButtonDown ("Fire1")) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; int groundLayer = 1 << (int)LayerConstants.GROUND; int buildingLayer = 1 << (int)LayerConstants.BUILDINGS; int resourcesLayer = 1 << (int)LayerConstants.RESOURCES; if (Physics.Raycast (ray, out hit, Mathf.Infinity, groundLayer | buildingLayer | resourcesLayer)) { if (hit.collider.gameObject.layer == (int)LayerConstants.GROUND) { sceneSelectionStartPoint = hit.point; UnselectBuild (); }else if (hit.collider.gameObject.layer == (int)LayerConstants.RESOURCES){ if(_selectedUnits.Count > 0){ foreach(Unit unit in _selectedUnits){ if(unit.UnitClass.CanCollect()){ unit.StartCollecting (hit.collider.gameObject.GetComponent<AbstractSource>()); _ignoreClick = true; } } if(_ignoreClick) return; } } } if (Physics.Raycast (ray, out hit, 1 << (int)LayerConstants.UNITS)) { ClearSelectedUnits (); _selectionEnded = false; if (hit.collider.GetComponent<Unit> () != null) { _selectedUnitsToSave = new RaycastHit[1]; _selectedUnitsToSave [0] = hit; } } screenSelectionStartPoint = Input.mousePosition; } if (Input.GetButton ("Fire1")) { PreviewSelectedUnits (); } if (Input.GetButtonUp ("Fire1")) { _selectionEnded = true; screenSelectionStartPoint = Input.mousePosition; SaveSelectedUnits (); _selectedUnitsToSave = new RaycastHit[0]; _selectionBox.localScale = new Vector3 (1, 1, 1); _selectionBox.position = new Vector3 (10, 1000, -10); } if (PlataformUtil.IsMoveButtonUp() && _selectedUnits.Count > 0) { Vector3 target; RaycastHit hit; if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit, Mathf.Infinity)) { //so se move se clicar no chao if (hit.collider.gameObject.layer == (int)LayerConstants.GROUND) { target = hit.point; foreach (IUnit unity in _selectedUnits) { unity.MoveTo (target); } } } } } } public void OnGUI(GUISkin guiSkin) { if (!_mouseOnGui && !_ignoreClick) { if (Input.GetButton ("Fire1") && Vector2.Distance (screenSelectionStartPoint, Input.mousePosition) > _minMouseDrag) { //Screen coordinates are bottom-left is (0,0) and top-right is (Screen.width, Screen.height) GUI.Box ( new Rect ( screenSelectionStartPoint.x, Screen.height - screenSelectionStartPoint.y, Input.mousePosition.x - screenSelectionStartPoint.x, -(Input.mousePosition.y - screenSelectionStartPoint.y)), "", guiSkin.customStyles [0] ); } } } #region Cost public bool CheckBuildingCost(IBuilding building){ return CheckCost (building.MaterialCost (MaterialType.Circle), building.MaterialCost (MaterialType.Stick)); } public void ApplyBuildingCost(IBuilding building){ _materialQuantity [MaterialType.Circle] -= building.MaterialCost (MaterialType.Circle); _materialQuantity [MaterialType.Stick] -= building.MaterialCost (MaterialType.Stick); } public bool CheckUnitCost(IUnit unit){ if (CheckCost(unit.UnitClass.MaterialCost(MaterialType.Circle), unit.UnitClass.MaterialCost(MaterialType.Stick))){ _materialQuantity [MaterialType.Circle] -= unit.UnitClass.MaterialCost (MaterialType.Circle); _materialQuantity [MaterialType.Stick] -= unit.UnitClass.MaterialCost (MaterialType.Stick); return true; } return false; } private bool CheckCost(int circleCost, int stickCost){ if(circleCost <= _materialQuantity[MaterialType.Circle] && stickCost <= _materialQuantity[MaterialType.Stick]){ return true; } return false; } #endregion #region Unit Selection void ConvertSceneToScreenScale(){ Ray ray1 = Camera.main.ScreenPointToRay (new Vector3 (0, 0, 0)); RaycastHit hit1; Ray ray2 = Camera.main.ScreenPointToRay (new Vector3 (Screen.width,Screen.height, 0)); RaycastHit hit2; Physics.Raycast(ray1, out hit1, Mathf.Infinity, 1<<8); Physics.Raycast(ray2, out hit2, Mathf.Infinity, 1<<8); _xUnitPer3DUnit = Screen.width/Mathf.Abs(hit1.point.x-hit2.point.x); _yUnitPer3DUnit = Screen.height/Mathf.Abs(hit1.point.z-hit2.point.z); } void SaveSelectedUnits(){ ClearSelectedUnits (); _selectionEnded = true; if (_selectedUnitsToSave != null && _selectedUnitsToSave.Length > 0) { Debug.Log ("Saving!!!"); bool hasBuilders = false; foreach (RaycastHit hit in _selectedUnitsToSave) { if (hit.collider.GetComponent<Unit> () == null) continue; Unit unit = hit.transform.GetComponent<Unit> (); _selectedUnits.Add (unit); unit.Selected = true; if (unit.UnitClass.CanBuild) hasBuilders = true; } } } void PreviewSelectedUnits(){ _multiSelection = (Vector2.Distance(screenSelectionStartPoint, Input.mousePosition) > _minMouseDrag); if (_multiSelection) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if(Physics.Raycast(ray, out hit, Mathf.Infinity, 1<<(int)LayerConstants.GROUND)){ _selectionBox.localScale = new Vector3(100,1,hit.point.z-sceneSelectionStartPoint.z); _selectionBox.position = new Vector3(sceneSelectionStartPoint.x, sceneSelectionStartPoint.y, sceneSelectionStartPoint.z+(_selectionBox.lossyScale.z/2)); _selectedUnitsToSave = _selectionBox.rigidbody.SweepTestAll(new Vector3(hit.point.x-sceneSelectionStartPoint.x,0,0), Mathf.Abs(hit.point.x-sceneSelectionStartPoint.x)); } } } void UpdateSelectedUnits(){ for (int i = _selectedUnits.Count-1; i >= 0; i--) { if(_selectedUnits[i] == null) _selectedUnits.RemoveAt(i); } } void ClearSelectedUnits(){ foreach (IUnit unit in _selectedUnits) { unit.Selected = false; } _selectedUnits.Clear (); _showBuildingOptions = false; } public bool MouseOnGUI { get { return _mouseOnGui; } set { _mouseOnGui = value; } } public List<IUnit> SelectedUnits{ get { return _selectedUnits; } } public int Sticks{ get { return _materialQuantity[MaterialType.Stick]; } } public int Circles{ get { return _materialQuantity[MaterialType.Circle]; } } public int Gold{ get { return _materialQuantity[MaterialType.Gold]; } } #endregion #region Building public void SelectBuild(IBuilding building){ _selectedBuilding = building; ClearSelectedUnits (); } public void UnselectBuild(){ _selectedBuilding = null; } public IBuilding SelectedBuilding{ get { return _selectedBuilding; } } public void ShowGhostBuilding(int building){ Ray rayCursor = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitCursor; Vector3 position = Vector3.zero; if (Physics.Raycast (rayCursor, out hitCursor, Mathf.Infinity, 1 << (int)LayerConstants.GROUND)) { position = new Vector3 (hitCursor.point.x, 7, hitCursor.point.z); } GameObject ghostBuilding = GameObject.Instantiate(_grid, position, Quaternion.Euler (new Vector3 (270, 0, 0)) ) as GameObject; Vector3 size = _ghostObjects [building].renderer.bounds.size; ghostBuilding.transform.localScale = new Vector3(size.x / 2 , size.z / 2, 1); ghostBuilding.GetComponent<GhostBuilding> ()._objectToConstruct = _ghostObjects [building]; ghostBuilding.GetComponent<GhostBuilding> ()._owner = this; _showBuildingOptions = false; } #endregion #region Resource Collect public void AddMaterial(MaterialType type, int quantity){ _materialQuantity [type] += quantity; } #endregion }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.NetworkSenders { using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using NLog.Common; /// <summary> /// A base class for all network senders. Supports one-way sending of messages /// over various protocols. /// </summary> internal abstract class NetworkSender : IDisposable { private static int currentSendTime; /// <summary> /// Initializes a new instance of the <see cref="NetworkSender" /> class. /// </summary> /// <param name="url">The network URL.</param> protected NetworkSender(string url) { Address = url; LastSendTime = Interlocked.Increment(ref currentSendTime); } /// <summary> /// Gets the address of the network endpoint. /// </summary> public string Address { get; private set; } /// <summary> /// Gets the last send time. /// </summary> public int LastSendTime { get; private set; } /// <summary> /// Initializes this network sender. /// </summary> public void Initialize() { DoInitialize(); } /// <summary> /// Closes the sender and releases any unmanaged resources. /// </summary> /// <param name="continuation">The continuation.</param> public void Close(AsyncContinuation continuation) { DoClose(continuation); } /// <summary> /// Flushes any pending messages and invokes the <paramref name="continuation"/> on completion. /// </summary> /// <param name="continuation">The continuation.</param> public void FlushAsync(AsyncContinuation continuation) { DoFlush(continuation); } /// <summary> /// Send the given text over the specified protocol. /// </summary> /// <param name="bytes">Bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Send(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation) { try { LastSendTime = Interlocked.Increment(ref currentSendTime); DoSend(bytes, offset, length, asyncContinuation); } catch (Exception ex) { InternalLogger.Error(ex, "NetworkTarget: Error sending network request"); asyncContinuation(ex); } } /// <summary> /// Closes the sender and releases any unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Initializes resources for the protocol specific implementation. /// </summary> protected virtual void DoInitialize() { } /// <summary> /// Closes resources for the protocol specific implementation. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void DoClose(AsyncContinuation continuation) { continuation(null); } /// <summary> /// Performs the flush and invokes the <paramref name="continuation"/> on completion. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void DoFlush(AsyncContinuation continuation) { continuation(null); } /// <summary> /// Sends the payload using the protocol specific implementation. /// </summary> /// <param name="bytes">The bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The async continuation to be invoked after the buffer has been sent.</param> protected abstract void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation); /// <summary> /// Parses the URI into an endpoint address. /// </summary> /// <param name="uri">The URI to parse.</param> /// <param name="addressFamily">The address family.</param> /// <returns>Parsed endpoint.</returns> protected virtual EndPoint ParseEndpointAddress(Uri uri, AddressFamily addressFamily) { switch (uri.HostNameType) { case UriHostNameType.IPv4: case UriHostNameType.IPv6: return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port); default: { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var addresses = Dns.GetHostEntry(uri.Host).AddressList; #else var addresses = Dns.GetHostAddressesAsync(uri.Host).ConfigureAwait(false).GetAwaiter().GetResult(); #endif // Only prioritize IPv6 addresses, when explictly specified or the only option foreach (var addr in System.Linq.Enumerable.OrderBy(addresses, a => a.AddressFamily)) { if (addr.AddressFamily == addressFamily || addressFamily == AddressFamily.Unspecified) { return new IPEndPoint(addr, uri.Port); } } throw new IOException($"Cannot resolve '{uri.Host}' to an address in '{addressFamily}'"); } } } public virtual void CheckSocket() { } private void Dispose(bool disposing) { if (disposing) { Close(ex => { }); } } } }
#pragma warning disable 0618 using System; using System.Text; using System.Runtime.InteropServices; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] namespace System.Windows.Forms { public class MessageBoxManager { private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); private delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam); private const int WH_CALLWNDPROCRET = 12; private const int WM_DESTROY = 0x0002; private const int WM_INITDIALOG = 0x0110; private const int WM_TIMER = 0x0113; private const int WM_USER = 0x400; private const int DM_GETDEFID = WM_USER + 0; private const int MBOK = 1; private const int MBCancel = 2; private const int MBAbort = 3; private const int MBRetry = 4; private const int MBIgnore = 5; private const int MBYes = 6; private const int MBNo = 7; [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); [DllImport("user32.dll")] private static extern int UnhookWindowsHookEx(IntPtr idHook); [DllImport("user32.dll")] private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", EntryPoint = "GetWindowTextLengthW", CharSet = CharSet.Unicode)] private static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)] private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength); [DllImport("user32.dll")] private static extern int EndDialog(IntPtr hDlg, IntPtr nResult); [DllImport("user32.dll")] private static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam); [DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)] private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32.dll")] private static extern int GetDlgCtrlID(IntPtr hwndCtl); [DllImport("user32.dll")] private static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem); [DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode)] private static extern bool SetWindowText(IntPtr hWnd, string lpString); [StructLayout(LayoutKind.Sequential)] public struct CWPRETSTRUCT { public IntPtr lResult; public IntPtr lParam; public IntPtr wParam; public uint message; public IntPtr hwnd; }; private static HookProc hookProc; private static EnumChildProc enumProc; [ThreadStatic] private static IntPtr hHook; [ThreadStatic] private static int nButton; /// <summary> /// OK text /// </summary> public static string OK = "&OK"; /// <summary> /// Cancel text /// </summary> public static string Cancel = "&Cancel"; /// <summary> /// Abort text /// </summary> public static string Abort = "&Abort"; /// <summary> /// Retry text /// </summary> public static string Retry = "&Retry"; /// <summary> /// Ignore text /// </summary> public static string Ignore = "&Ignore"; /// <summary> /// Yes text /// </summary> public static string Yes = "&Yes"; /// <summary> /// No text /// </summary> public static string No = "&No"; static MessageBoxManager() { hookProc = new HookProc(MessageBoxHookProc); enumProc = new EnumChildProc(MessageBoxEnumProc); hHook = IntPtr.Zero; } /// <summary> /// Enables MessageBoxManager functionality /// </summary> /// <remarks> /// MessageBoxManager functionality is enabled on current thread only. /// Each thread that needs MessageBoxManager functionality has to call this method. /// </remarks> public static void Register() { if (hHook != IntPtr.Zero) throw new NotSupportedException("One hook per thread allowed."); hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId()); } /// <summary> /// Disables MessageBoxManager functionality /// </summary> /// <remarks> /// Disables MessageBoxManager functionality on current thread only. /// </remarks> public static void Unregister() { if (hHook != IntPtr.Zero) { UnhookWindowsHookEx(hHook); hHook = IntPtr.Zero; } } private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode < 0) return CallNextHookEx(hHook, nCode, wParam, lParam); CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT)); IntPtr hook = hHook; if (msg.message == WM_INITDIALOG) { int nLength = GetWindowTextLength(msg.hwnd); StringBuilder className = new StringBuilder(10); GetClassName(msg.hwnd, className, className.Capacity); if (className.ToString() == "#32770") { nButton = 0; EnumChildWindows(msg.hwnd, enumProc, IntPtr.Zero); if (nButton == 1) { IntPtr hButton = GetDlgItem(msg.hwnd, MBCancel); if (hButton != IntPtr.Zero) SetWindowText(hButton, OK); } } } return CallNextHookEx(hook, nCode, wParam, lParam); } private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam) { StringBuilder className = new StringBuilder(10); GetClassName(hWnd, className, className.Capacity); if (className.ToString() == "Button") { int ctlId = GetDlgCtrlID(hWnd); switch (ctlId) { case MBOK: SetWindowText(hWnd, OK); break; case MBCancel: SetWindowText(hWnd, Cancel); break; case MBAbort: SetWindowText(hWnd, Abort); break; case MBRetry: SetWindowText(hWnd, Retry); break; case MBIgnore: SetWindowText(hWnd, Ignore); break; case MBYes: SetWindowText(hWnd, Yes); break; case MBNo: SetWindowText(hWnd, No); break; } nButton++; } return true; } } }
using System.Diagnostics; using System.Collections; namespace Memento.Core.Converter { /// <summary> /// HtmlSchema class /// maintains static information about HTML structure /// can be used by HtmlParser to check conditions under which an element starts or ends, etc. /// </summary> internal class HtmlSchema { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// static constructor, initializes the ArrayLists /// that hold the elements in various sub-components of the schema /// e.g _htmlEmptyElements, etc. /// </summary> static HtmlSchema() { // initializes the list of all html elements InitializeInlineElements(); InitializeBlockElements(); InitializeOtherOpenableElements(); // initialize empty elements list InitializeEmptyElements(); // initialize list of elements closing on the outer element end InitializeElementsClosingOnParentElementEnd(); // initalize list of elements that close when a new element starts InitializeElementsClosingOnNewElementStart(); // Initialize character entities InitializeHtmlCharacterEntities(); } #endregion Constructors; // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// returns true when xmlElementName corresponds to empty element /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool IsEmptyElement(string xmlElementName) { // convert to lowercase before we check // because element names are not case sensitive return _htmlEmptyElements.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if xmlElementName represents a block formattinng element. /// It used in an algorithm of transferring inline elements over block elements /// in HtmlParser /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsBlockElement(string xmlElementName) { return _htmlBlockElements.Contains(xmlElementName); } /// <summary> /// returns true if the xmlElementName represents an inline formatting element /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsInlineElement(string xmlElementName) { return _htmlInlineElements.Contains(xmlElementName); } /// <summary> /// It is a list of known html elements which we /// want to allow to produce bt HTML parser, /// but don'tt want to act as inline, block or no-scope. /// Presence in this list will allow to open /// elements during html parsing, and adding the /// to a tree produced by html parser. /// </summary> internal static bool IsKnownOpenableElement(string xmlElementName) { return _htmlOtherOpenableElements.Contains(xmlElementName); } /// <summary> /// returns true when xmlElementName closes when the outer element closes /// this is true of elements with optional start tags /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool ClosesOnParentElementEnd(string xmlElementName) { // convert to lowercase when testing return _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if the current element closes when the new element, whose name has just been read, starts /// </summary> /// <param name="currentElementName"> /// string representing current element name /// </param> /// <param name="elementName"></param> /// string representing name of the next element that will start internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName) { Debug.Assert(currentElementName == currentElementName.ToLower()); switch (currentElementName) { case "colgroup": return _htmlElementsClosingColgroup.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dd": return _htmlElementsClosingDD.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dt": return _htmlElementsClosingDT.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "li": return _htmlElementsClosingLI.Contains(nextElementName); case "p": return HtmlSchema.IsBlockElement(nextElementName); case "tbody": return _htmlElementsClosingTbody.Contains(nextElementName); case "tfoot": return _htmlElementsClosingTfoot.Contains(nextElementName); case "thead": return _htmlElementsClosingThead.Contains(nextElementName); case "tr": return _htmlElementsClosingTR.Contains(nextElementName); case "td": return _htmlElementsClosingTD.Contains(nextElementName); case "th": return _htmlElementsClosingTH.Contains(nextElementName); } return false; } /// <summary> /// returns true if the string passed as argument is an Html entity name /// </summary> /// <param name="entityName"> /// string to be tested for Html entity name /// </param> internal static bool IsEntity(string entityName) { // we do not convert entity strings to lowercase because these names are case-sensitive if (_htmlCharacterEntities.Contains(entityName)) { return true; } else { return false; } } /// <summary> /// returns the character represented by the entity name string which is passed as an argument, if the string is an entity name /// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise /// </summary> /// <param name="entityName"> /// string representing entity name whose character value is desired /// </param> internal static char EntityCharacterValue(string entityName) { if (_htmlCharacterEntities.Contains(entityName)) { return (char) _htmlCharacterEntities[entityName]; } else { return (char)0; } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties #endregion Internal Indexers // --------------------------------------------------------------------- // // Private Methods // // --------------------------------------------------------------------- #region Private Methods private static void InitializeInlineElements() { _htmlInlineElements = new ArrayList(); _htmlInlineElements.Add("a"); _htmlInlineElements.Add("abbr"); _htmlInlineElements.Add("acronym"); _htmlInlineElements.Add("address"); _htmlInlineElements.Add("b"); _htmlInlineElements.Add("bdo"); // ??? _htmlInlineElements.Add("big"); _htmlInlineElements.Add("button"); _htmlInlineElements.Add("code"); _htmlInlineElements.Add("del"); // deleted text _htmlInlineElements.Add("dfn"); _htmlInlineElements.Add("em"); _htmlInlineElements.Add("font"); _htmlInlineElements.Add("i"); _htmlInlineElements.Add("ins"); // inserted text _htmlInlineElements.Add("kbd"); // text to entered by a user _htmlInlineElements.Add("label"); _htmlInlineElements.Add("legend"); // ??? _htmlInlineElements.Add("q"); // short inline quotation _htmlInlineElements.Add("s"); // strike-through text style _htmlInlineElements.Add("samp"); // Specifies a code sample _htmlInlineElements.Add("small"); _htmlInlineElements.Add("span"); _htmlInlineElements.Add("strike"); _htmlInlineElements.Add("strong"); _htmlInlineElements.Add("sub"); _htmlInlineElements.Add("sup"); _htmlInlineElements.Add("u"); _htmlInlineElements.Add("var"); // indicates an instance of a program variable } private static void InitializeBlockElements() { _htmlBlockElements = new ArrayList(); _htmlBlockElements.Add("blockquote"); _htmlBlockElements.Add("body"); _htmlBlockElements.Add("caption"); _htmlBlockElements.Add("center"); _htmlBlockElements.Add("cite"); _htmlBlockElements.Add("dd"); _htmlBlockElements.Add("dir"); // treat as UL element _htmlBlockElements.Add("div"); _htmlBlockElements.Add("dl"); _htmlBlockElements.Add("dt"); _htmlBlockElements.Add("form"); // Not a block according to XHTML spec _htmlBlockElements.Add("h1"); _htmlBlockElements.Add("h2"); _htmlBlockElements.Add("h3"); _htmlBlockElements.Add("h4"); _htmlBlockElements.Add("h5"); _htmlBlockElements.Add("h6"); _htmlBlockElements.Add("html"); _htmlBlockElements.Add("li"); _htmlBlockElements.Add("menu"); // treat as UL element _htmlBlockElements.Add("ol"); _htmlBlockElements.Add("p"); _htmlBlockElements.Add("pre"); // Renders text in a fixed-width font _htmlBlockElements.Add("table"); _htmlBlockElements.Add("tbody"); _htmlBlockElements.Add("td"); _htmlBlockElements.Add("textarea"); _htmlBlockElements.Add("tfoot"); _htmlBlockElements.Add("th"); _htmlBlockElements.Add("thead"); _htmlBlockElements.Add("tr"); _htmlBlockElements.Add("tt"); _htmlBlockElements.Add("ul"); } /// <summary> /// initializes _htmlEmptyElements with empty elements in HTML 4 spec at /// http://www.w3.org/TR/REC-html40/index/elements.html /// </summary> private static void InitializeEmptyElements() { // Build a list of empty (no-scope) elements // (element not requiring closing tags, and not accepting any content) _htmlEmptyElements = new ArrayList(); _htmlEmptyElements.Add("area"); _htmlEmptyElements.Add("base"); _htmlEmptyElements.Add("basefont"); _htmlEmptyElements.Add("br"); _htmlEmptyElements.Add("col"); _htmlEmptyElements.Add("frame"); _htmlEmptyElements.Add("hr"); _htmlEmptyElements.Add("img"); _htmlEmptyElements.Add("input"); _htmlEmptyElements.Add("isindex"); _htmlEmptyElements.Add("link"); _htmlEmptyElements.Add("meta"); _htmlEmptyElements.Add("param"); } private static void InitializeOtherOpenableElements() { // It is a list of known html elements which we // want to allow to produce bt HTML parser, // but don'tt want to act as inline, block or no-scope. // Presence in this list will allow to open // elements during html parsing, and adding the // to a tree produced by html parser. _htmlOtherOpenableElements = new ArrayList(); _htmlOtherOpenableElements.Add("applet"); _htmlOtherOpenableElements.Add("base"); _htmlOtherOpenableElements.Add("basefont"); _htmlOtherOpenableElements.Add("colgroup"); _htmlOtherOpenableElements.Add("fieldset"); //_htmlOtherOpenableElements.Add("form"); --> treated as block _htmlOtherOpenableElements.Add("frameset"); _htmlOtherOpenableElements.Add("head"); _htmlOtherOpenableElements.Add("iframe"); _htmlOtherOpenableElements.Add("map"); _htmlOtherOpenableElements.Add("noframes"); _htmlOtherOpenableElements.Add("noscript"); _htmlOtherOpenableElements.Add("object"); _htmlOtherOpenableElements.Add("optgroup"); _htmlOtherOpenableElements.Add("option"); _htmlOtherOpenableElements.Add("script"); _htmlOtherOpenableElements.Add("select"); _htmlOtherOpenableElements.Add("style"); _htmlOtherOpenableElements.Add("title"); } /// <summary> /// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are optional /// we assume that for any element for which closing tags are optional, the element closes when it's outer element /// (in which it is nested) does /// </summary> private static void InitializeElementsClosingOnParentElementEnd() { _htmlElementsClosingOnParentElementEnd = new ArrayList(); _htmlElementsClosingOnParentElementEnd.Add("body"); _htmlElementsClosingOnParentElementEnd.Add("colgroup"); _htmlElementsClosingOnParentElementEnd.Add("dd"); _htmlElementsClosingOnParentElementEnd.Add("dt"); _htmlElementsClosingOnParentElementEnd.Add("head"); _htmlElementsClosingOnParentElementEnd.Add("html"); _htmlElementsClosingOnParentElementEnd.Add("li"); _htmlElementsClosingOnParentElementEnd.Add("p"); _htmlElementsClosingOnParentElementEnd.Add("tbody"); _htmlElementsClosingOnParentElementEnd.Add("td"); _htmlElementsClosingOnParentElementEnd.Add("tfoot"); _htmlElementsClosingOnParentElementEnd.Add("thead"); _htmlElementsClosingOnParentElementEnd.Add("th"); _htmlElementsClosingOnParentElementEnd.Add("tr"); } private static void InitializeElementsClosingOnNewElementStart() { _htmlElementsClosingColgroup = new ArrayList(); _htmlElementsClosingColgroup.Add("colgroup"); _htmlElementsClosingColgroup.Add("tr"); _htmlElementsClosingColgroup.Add("thead"); _htmlElementsClosingColgroup.Add("tfoot"); _htmlElementsClosingColgroup.Add("tbody"); _htmlElementsClosingDD = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); // TODO: dd may end in other cases as well - if a new "p" starts, etc. // TODO: these are the basic "legal" cases but there may be more recovery _htmlElementsClosingDT = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); // TODO: dd may end in other cases as well - if a new "p" starts, etc. // TODO: these are the basic "legal" cases but there may be more recovery _htmlElementsClosingLI = new ArrayList(); _htmlElementsClosingLI.Add("li"); // TODO: more complex recovery _htmlElementsClosingTbody = new ArrayList(); _htmlElementsClosingTbody.Add("tbody"); _htmlElementsClosingTbody.Add("thead"); _htmlElementsClosingTbody.Add("tfoot"); // TODO: more complex recovery _htmlElementsClosingTR = new ArrayList(); // NOTE: tr should not really close on a new thead // because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional // and thead can't come after tbody // however, if we do encounter this, it's probably best to end the row and ignore the thead or treat // it as part of the table _htmlElementsClosingTR.Add("thead"); _htmlElementsClosingTR.Add("tfoot"); _htmlElementsClosingTR.Add("tbody"); _htmlElementsClosingTR.Add("tr"); // TODO: more complex recovery _htmlElementsClosingTD = new ArrayList(); _htmlElementsClosingTD.Add("td"); _htmlElementsClosingTD.Add("th"); _htmlElementsClosingTD.Add("tr"); _htmlElementsClosingTD.Add("tbody"); _htmlElementsClosingTD.Add("tfoot"); _htmlElementsClosingTD.Add("thead"); // TODO: more complex recovery _htmlElementsClosingTH = new ArrayList(); _htmlElementsClosingTH.Add("td"); _htmlElementsClosingTH.Add("th"); _htmlElementsClosingTH.Add("tr"); _htmlElementsClosingTH.Add("tbody"); _htmlElementsClosingTH.Add("tfoot"); _htmlElementsClosingTH.Add("thead"); // TODO: more complex recovery _htmlElementsClosingThead = new ArrayList(); _htmlElementsClosingThead.Add("tbody"); _htmlElementsClosingThead.Add("tfoot"); // TODO: more complex recovery _htmlElementsClosingTfoot = new ArrayList(); _htmlElementsClosingTfoot.Add("tbody"); // although thead comes before tfoot, we add it because if it is found the tfoot should close // and some recovery processing be done on the thead _htmlElementsClosingTfoot.Add("thead"); // TODO: more complex recovery } /// <summary> /// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names /// </summary> private static void InitializeHtmlCharacterEntities() { _htmlCharacterEntities = new Hashtable(); _htmlCharacterEntities["Aacute"] = (char)193; _htmlCharacterEntities["aacute"] = (char)225; _htmlCharacterEntities["Acirc"] = (char)194; _htmlCharacterEntities["acirc"] = (char)226; _htmlCharacterEntities["acute"] = (char)180; _htmlCharacterEntities["AElig"] = (char)198; _htmlCharacterEntities["aelig"] = (char)230; _htmlCharacterEntities["Agrave"] = (char)192; _htmlCharacterEntities["agrave"] = (char)224; _htmlCharacterEntities["alefsym"] = (char)8501; _htmlCharacterEntities["Alpha"] = (char)913; _htmlCharacterEntities["alpha"] = (char)945; _htmlCharacterEntities["amp"] = (char)38; _htmlCharacterEntities["and"] = (char)8743; _htmlCharacterEntities["ang"] = (char)8736; _htmlCharacterEntities["Aring"] = (char)197; _htmlCharacterEntities["aring"] = (char)229; _htmlCharacterEntities["asymp"] = (char)8776; _htmlCharacterEntities["Atilde"] = (char)195; _htmlCharacterEntities["atilde"] = (char)227; _htmlCharacterEntities["Auml"] = (char)196; _htmlCharacterEntities["auml"] = (char)228; _htmlCharacterEntities["bdquo"] = (char)8222; _htmlCharacterEntities["Beta"] = (char)914; _htmlCharacterEntities["beta"] = (char)946; _htmlCharacterEntities["brvbar"] = (char)166; _htmlCharacterEntities["bull"] = (char)8226; _htmlCharacterEntities["cap"] = (char)8745; _htmlCharacterEntities["Ccedil"] = (char)199; _htmlCharacterEntities["ccedil"] = (char)231; _htmlCharacterEntities["cent"] = (char)162; _htmlCharacterEntities["Chi"] = (char)935; _htmlCharacterEntities["chi"] = (char)967; _htmlCharacterEntities["circ"] = (char)710; _htmlCharacterEntities["clubs"] = (char)9827; _htmlCharacterEntities["cong"] = (char)8773; _htmlCharacterEntities["copy"] = (char)169; _htmlCharacterEntities["crarr"] = (char)8629; _htmlCharacterEntities["cup"] = (char)8746; _htmlCharacterEntities["curren"] = (char)164; _htmlCharacterEntities["dagger"] = (char)8224; _htmlCharacterEntities["Dagger"] = (char)8225; _htmlCharacterEntities["darr"] = (char)8595; _htmlCharacterEntities["dArr"] = (char)8659; _htmlCharacterEntities["deg"] = (char)176; _htmlCharacterEntities["Delta"] = (char)916; _htmlCharacterEntities["delta"] = (char)948; _htmlCharacterEntities["diams"] = (char)9830; _htmlCharacterEntities["divide"] = (char)247; _htmlCharacterEntities["Eacute"] = (char)201; _htmlCharacterEntities["eacute"] = (char)233; _htmlCharacterEntities["Ecirc"] = (char)202; _htmlCharacterEntities["ecirc"] = (char)234; _htmlCharacterEntities["Egrave"] = (char)200; _htmlCharacterEntities["egrave"] = (char)232; _htmlCharacterEntities["empty"] = (char)8709; _htmlCharacterEntities["emsp"] = (char)8195; _htmlCharacterEntities["ensp"] = (char)8194; _htmlCharacterEntities["Epsilon"] = (char)917; _htmlCharacterEntities["epsilon"] = (char)949; _htmlCharacterEntities["equiv"] = (char)8801; _htmlCharacterEntities["Eta"] = (char)919; _htmlCharacterEntities["eta"] = (char)951; _htmlCharacterEntities["ETH"] = (char)208; _htmlCharacterEntities["eth"] = (char)240; _htmlCharacterEntities["Euml"] = (char)203; _htmlCharacterEntities["euml"] = (char)235; _htmlCharacterEntities["euro"] = (char)8364; _htmlCharacterEntities["exist"] = (char)8707; _htmlCharacterEntities["fnof"] = (char)402; _htmlCharacterEntities["forall"] = (char)8704; _htmlCharacterEntities["frac12"] = (char)189; _htmlCharacterEntities["frac14"] = (char)188; _htmlCharacterEntities["frac34"] = (char)190; _htmlCharacterEntities["frasl"] = (char)8260; _htmlCharacterEntities["Gamma"] = (char)915; _htmlCharacterEntities["gamma"] = (char)947; _htmlCharacterEntities["ge"] = (char)8805; _htmlCharacterEntities["gt"] = (char)62; _htmlCharacterEntities["harr"] = (char)8596; _htmlCharacterEntities["hArr"] = (char)8660; _htmlCharacterEntities["hearts"] = (char)9829; _htmlCharacterEntities["hellip"] = (char)8230; _htmlCharacterEntities["Iacute"] = (char)205; _htmlCharacterEntities["iacute"] = (char)237; _htmlCharacterEntities["Icirc"] = (char)206; _htmlCharacterEntities["icirc"] = (char)238; _htmlCharacterEntities["iexcl"] = (char)161; _htmlCharacterEntities["Igrave"] = (char)204; _htmlCharacterEntities["igrave"] = (char)236; _htmlCharacterEntities["image"] = (char)8465; _htmlCharacterEntities["infin"] = (char)8734; _htmlCharacterEntities["int"] = (char)8747; _htmlCharacterEntities["Iota"] = (char)921; _htmlCharacterEntities["iota"] = (char)953; _htmlCharacterEntities["iquest"] = (char)191; _htmlCharacterEntities["isin"] = (char)8712; _htmlCharacterEntities["Iuml"] = (char)207; _htmlCharacterEntities["iuml"] = (char)239; _htmlCharacterEntities["Kappa"] = (char)922; _htmlCharacterEntities["kappa"] = (char)954; _htmlCharacterEntities["Lambda"] = (char)923; _htmlCharacterEntities["lambda"] = (char)955; _htmlCharacterEntities["lang"] = (char)9001; _htmlCharacterEntities["laquo"] = (char)171; _htmlCharacterEntities["larr"] = (char)8592; _htmlCharacterEntities["lArr"] = (char)8656; _htmlCharacterEntities["lceil"] = (char)8968; _htmlCharacterEntities["ldquo"] = (char)8220; _htmlCharacterEntities["le"] = (char)8804; _htmlCharacterEntities["lfloor"] = (char)8970; _htmlCharacterEntities["lowast"] = (char)8727; _htmlCharacterEntities["loz"] = (char)9674; _htmlCharacterEntities["lrm"] = (char)8206; _htmlCharacterEntities["lsaquo"] = (char)8249; _htmlCharacterEntities["lsquo"] = (char)8216; _htmlCharacterEntities["lt"] = (char)60; _htmlCharacterEntities["macr"] = (char)175; _htmlCharacterEntities["mdash"] = (char)8212; _htmlCharacterEntities["micro"] = (char)181; _htmlCharacterEntities["middot"] = (char)183; _htmlCharacterEntities["minus"] = (char)8722; _htmlCharacterEntities["Mu"] = (char)924; _htmlCharacterEntities["mu"] = (char)956; _htmlCharacterEntities["nabla"] = (char)8711; _htmlCharacterEntities["nbsp"] = (char)160; _htmlCharacterEntities["ndash"] = (char)8211; _htmlCharacterEntities["ne"] = (char)8800; _htmlCharacterEntities["ni"] = (char)8715; _htmlCharacterEntities["not"] = (char)172; _htmlCharacterEntities["notin"] = (char)8713; _htmlCharacterEntities["nsub"] = (char)8836; _htmlCharacterEntities["Ntilde"] = (char)209; _htmlCharacterEntities["ntilde"] = (char)241; _htmlCharacterEntities["Nu"] = (char)925; _htmlCharacterEntities["nu"] = (char)957; _htmlCharacterEntities["Oacute"] = (char)211; _htmlCharacterEntities["ocirc"] = (char)244; _htmlCharacterEntities["OElig"] = (char)338; _htmlCharacterEntities["oelig"] = (char)339; _htmlCharacterEntities["Ograve"] = (char)210; _htmlCharacterEntities["ograve"] = (char)242; _htmlCharacterEntities["oline"] = (char)8254; _htmlCharacterEntities["Omega"] = (char)937; _htmlCharacterEntities["omega"] = (char)969; _htmlCharacterEntities["Omicron"] = (char)927; _htmlCharacterEntities["omicron"] = (char)959; _htmlCharacterEntities["oplus"] = (char)8853; _htmlCharacterEntities["or"] = (char)8744; _htmlCharacterEntities["ordf"] = (char)170; _htmlCharacterEntities["ordm"] = (char)186; _htmlCharacterEntities["Oslash"] = (char)216; _htmlCharacterEntities["oslash"] = (char)248; _htmlCharacterEntities["Otilde"] = (char)213; _htmlCharacterEntities["otilde"] = (char)245; _htmlCharacterEntities["otimes"] = (char)8855; _htmlCharacterEntities["Ouml"] = (char)214; _htmlCharacterEntities["ouml"] = (char)246; _htmlCharacterEntities["para"] = (char)182; _htmlCharacterEntities["part"] = (char)8706; _htmlCharacterEntities["permil"] = (char)8240; _htmlCharacterEntities["perp"] = (char)8869; _htmlCharacterEntities["Phi"] = (char)934; _htmlCharacterEntities["phi"] = (char)966; _htmlCharacterEntities["pi"] = (char)960; _htmlCharacterEntities["piv"] = (char)982; _htmlCharacterEntities["plusmn"] = (char)177; _htmlCharacterEntities["pound"] = (char)163; _htmlCharacterEntities["prime"] = (char)8242; _htmlCharacterEntities["Prime"] = (char)8243; _htmlCharacterEntities["prod"] = (char)8719; _htmlCharacterEntities["prop"] = (char)8733; _htmlCharacterEntities["Psi"] = (char)936; _htmlCharacterEntities["psi"] = (char)968; _htmlCharacterEntities["quot"] = (char)34; _htmlCharacterEntities["radic"] = (char)8730; _htmlCharacterEntities["rang"] = (char)9002; _htmlCharacterEntities["raquo"] = (char)187; _htmlCharacterEntities["rarr"] = (char)8594; _htmlCharacterEntities["rArr"] = (char)8658; _htmlCharacterEntities["rceil"] = (char)8969; _htmlCharacterEntities["rdquo"] = (char)8221; _htmlCharacterEntities["real"] = (char)8476; _htmlCharacterEntities["reg"] = (char)174; _htmlCharacterEntities["rfloor"] = (char)8971; _htmlCharacterEntities["Rho"] = (char)929; _htmlCharacterEntities["rho"] = (char)961; _htmlCharacterEntities["rlm"] = (char)8207; _htmlCharacterEntities["rsaquo"] = (char)8250; _htmlCharacterEntities["rsquo"] = (char)8217; _htmlCharacterEntities["sbquo"] = (char)8218; _htmlCharacterEntities["Scaron"] = (char)352; _htmlCharacterEntities["scaron"] = (char)353; _htmlCharacterEntities["sdot"] = (char)8901; _htmlCharacterEntities["sect"] = (char)167; _htmlCharacterEntities["shy"] = (char)173; _htmlCharacterEntities["Sigma"] = (char)931; _htmlCharacterEntities["sigma"] = (char)963; _htmlCharacterEntities["sigmaf"] = (char)962; _htmlCharacterEntities["sim"] = (char)8764; _htmlCharacterEntities["spades"] = (char)9824; _htmlCharacterEntities["sub"] = (char)8834; _htmlCharacterEntities["sube"] = (char)8838; _htmlCharacterEntities["sum"] = (char)8721; _htmlCharacterEntities["sup"] = (char)8835; _htmlCharacterEntities["sup1"] = (char)185; _htmlCharacterEntities["sup2"] = (char)178; _htmlCharacterEntities["sup3"] = (char)179; _htmlCharacterEntities["supe"] = (char)8839; _htmlCharacterEntities["szlig"] = (char)223; _htmlCharacterEntities["Tau"] = (char)932; _htmlCharacterEntities["tau"] = (char)964; _htmlCharacterEntities["there4"] = (char)8756; _htmlCharacterEntities["Theta"] = (char)920; _htmlCharacterEntities["theta"] = (char)952; _htmlCharacterEntities["thetasym"] = (char)977; _htmlCharacterEntities["thinsp"] = (char)8201; _htmlCharacterEntities["THORN"] = (char)222; _htmlCharacterEntities["thorn"] = (char)254; _htmlCharacterEntities["tilde"] = (char)732; _htmlCharacterEntities["times"] = (char)215; _htmlCharacterEntities["trade"] = (char)8482; _htmlCharacterEntities["Uacute"] = (char)218; _htmlCharacterEntities["uacute"] = (char)250; _htmlCharacterEntities["uarr"] = (char)8593; _htmlCharacterEntities["uArr"] = (char)8657; _htmlCharacterEntities["Ucirc"] = (char)219; _htmlCharacterEntities["ucirc"] = (char)251; _htmlCharacterEntities["Ugrave"] = (char)217; _htmlCharacterEntities["ugrave"] = (char)249; _htmlCharacterEntities["uml"] = (char)168; _htmlCharacterEntities["upsih"] = (char)978; _htmlCharacterEntities["Upsilon"] = (char)933; _htmlCharacterEntities["upsilon"] = (char)965; _htmlCharacterEntities["Uuml"] = (char)220; _htmlCharacterEntities["uuml"] = (char)252; _htmlCharacterEntities["weierp"] = (char)8472; _htmlCharacterEntities["Xi"] = (char)926; _htmlCharacterEntities["xi"] = (char)958; _htmlCharacterEntities["Yacute"] = (char)221; _htmlCharacterEntities["yacute"] = (char)253; _htmlCharacterEntities["yen"] = (char)165; _htmlCharacterEntities["Yuml"] = (char)376; _htmlCharacterEntities["yuml"] = (char)255; _htmlCharacterEntities["Zeta"] = (char)918; _htmlCharacterEntities["zeta"] = (char)950; _htmlCharacterEntities["zwj"] = (char)8205; _htmlCharacterEntities["zwnj"] = (char)8204; } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // html element names // this is an array list now, but we may want to make it a hashtable later for better performance private static ArrayList _htmlInlineElements; private static ArrayList _htmlBlockElements; private static ArrayList _htmlOtherOpenableElements; // list of html empty element names private static ArrayList _htmlEmptyElements; // names of html elements for which closing tags are optional, and close when the outer nested element closes private static ArrayList _htmlElementsClosingOnParentElementEnd; // names of elements that close certain optional closing tag elements when they start // names of elements closing the colgroup element private static ArrayList _htmlElementsClosingColgroup; // names of elements closing the dd element private static ArrayList _htmlElementsClosingDD; // names of elements closing the dt element private static ArrayList _htmlElementsClosingDT; // names of elements closing the li element private static ArrayList _htmlElementsClosingLI; // names of elements closing the tbody element private static ArrayList _htmlElementsClosingTbody; // names of elements closing the td element private static ArrayList _htmlElementsClosingTD; // names of elements closing the tfoot element private static ArrayList _htmlElementsClosingTfoot; // names of elements closing the thead element private static ArrayList _htmlElementsClosingThead; // names of elements closing the th element private static ArrayList _htmlElementsClosingTH; // names of elements closing the tr element private static ArrayList _htmlElementsClosingTR; // html character entities hashtable private static Hashtable _htmlCharacterEntities; #endregion Private Fields } }
// BizTalk Typed BAM API Generator // Copyright (C) 2008-Present Thomas F. Abraham. All Rights Reserved. // Copyright (c) 2007 Darren Jefford. All Rights Reserved. // Licensed under the MIT License. See License.txt in the project root. using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.IO; using System.Data.OleDb; using System.Data; namespace Shared { /// <summary> /// Extracts the XML for a BizTalk BAM definition from a binary Excel XLS file. /// </summary> internal static class BamDefinitionXmlExporter { private static object objMissing = Missing.Value; public static string GetBamDefinitionXml(string xlsFileName, bool useAutomation) { if (!File.Exists(xlsFileName)) { throw new ArgumentException("File '" + xlsFileName + "' does not exist or is unavailable."); } if (useAutomation) { return GetBamDefinitionXmlAutomation(xlsFileName); } else { return GetBamDefinitionXmlDirect(xlsFileName); } } private static string GetBamDefinitionXmlDirect(string xlsFileName) { DataSet ds = new DataSet(); OleDbConnection conn = null; try { conn = GetOleDbConnection(xlsFileName); OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [BamXmlHiddenSheet$]", conn); try { da.Fill(ds); } catch (OleDbException ex) { if (ex.Errors.Count > 0 && ex.Errors[0].NativeError == -537199594) { throw new ArgumentException("ERROR: Could not find hidden BAM worksheet BamXmlHiddenSheet.", ex); } throw; } } finally { if (conn != null) { conn.Dispose(); } } // We should have gotten back a single DataTable with one row containing one or more columns // with a non-DBNull value. if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0 || ds.Tables[0].Rows[0].IsNull(0)) { throw new ArgumentException( "ERROR: Could not find hidden BAM worksheet or found no BAM XML on the worksheet. Expected to find BAM XML at cell BamXmlHiddenSheet!A1."); } // Build the complete XML by appending all cell values across the column. StringBuilder sb = new StringBuilder(); DataRow row = ds.Tables[0].Rows[0]; int columnCount = ds.Tables[0].Columns.Count; for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { if (!row.IsNull(columnIndex)) { sb.Append(row[columnIndex].ToString()); } else { break; } } return sb.ToString(); } private static OleDbConnection GetOleDbConnection(string xlsFileName) { OleDbConnection conn = null; string connectionString = null; // Try Data Connnectivity Components 2007 connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=NO;MAXSCANROWS=1\"", xlsFileName); conn = TryOpenOleDbConnection(connectionString); if (conn != null) { return conn; } // Try Access Database Engine 2010 Redistributable connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.14.0;Data Source={0};Extended Properties=\"Excel 14.0;HDR=NO;MAXSCANROWS=1\"", xlsFileName); conn = TryOpenOleDbConnection(connectionString); if (conn != null) { return conn; } // Try old Jet driver if XLS if (string.Compare(Path.GetExtension(xlsFileName), ".xls", StringComparison.OrdinalIgnoreCase) == 0) { connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=NO;MAXSCANROWS=1\"", xlsFileName); conn = TryOpenOleDbConnection(connectionString); if (conn != null) { return conn; } } throw new Exception( "ERROR: Could not open an OLE DB connection to the Excel file. " + "Export from XLSX requires installation of Microsoft Office 2007 or Access Database Engine 2010 Redistributable or JET 4.0 for XLS."); } private static OleDbConnection TryOpenOleDbConnection(string connectionString) { OleDbConnection conn = new OleDbConnection(connectionString); try { conn.Open(); } catch (Exception) { return null; } return conn; } private static string GetBamDefinitionXmlAutomation(string xlsFileName) { // This is needed to avoid issues with other cultures (see http://support.microsoft.com/kb/320369). System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US"); object excelApp = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application")); Type excelAppType = excelApp.GetType(); excelAppType.InvokeMember("Visible", BindingFlags.SetProperty, null, excelApp, new object[] { false }, ci); excelAppType.InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, excelApp, new object[] { false }, ci); object workbooks = excelAppType.InvokeMember("Workbooks", BindingFlags.GetProperty, null, excelApp, null, ci); string fullXLSPath = Path.GetFullPath(xlsFileName); object[] args = new object[] { fullXLSPath, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing }; object workbook = workbooks.GetType().InvokeMember("Open", BindingFlags.InvokeMethod, null, workbooks, args, ci); object worksheets = workbook.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, workbook, null, ci); object[] objArray2 = new object[] { "BamXmlHiddenSheet" }; object bamWorksheet = worksheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, worksheets, objArray2, ci); object cells = bamWorksheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty, null, bamWorksheet, null, ci); StringBuilder builder = new StringBuilder(); int num = 1; object[] objArray3 = new object[] { 1, num++ }; object cell = cells.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, cells, objArray3, ci); string str = (string)cell.GetType().InvokeMember("Value2", BindingFlags.GetProperty, null, cell, null, ci); for (; (str != null) && (str.Length > 0); str = (string)cell.GetType().InvokeMember("Value2", BindingFlags.GetProperty, null, cell, null, ci)) { builder.Append(str); objArray3[1] = num++; cell = cells.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, cells, objArray3, ci); } excelAppType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, excelApp, null, ci); excelApp = null; return builder.ToString(); } } }
// 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.Diagnostics; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal partial class CSharpCodeModelService { protected override AbstractNodeNameGenerator CreateNodeNameGenerator() { return new NodeNameGenerator(); } private class NodeNameGenerator : AbstractNodeNameGenerator { protected override bool IsNameableNode(SyntaxNode node) { return CSharpCodeModelService.IsNameableNode(node); } private static void AppendName(StringBuilder builder, NameSyntax name) { if (name.Kind() == SyntaxKind.QualifiedName) { AppendName(builder, ((QualifiedNameSyntax)name).Left); } switch (name.Kind()) { case SyntaxKind.IdentifierName: AppendDotIfNeeded(builder); builder.Append(((IdentifierNameSyntax)name).Identifier.ValueText); break; case SyntaxKind.GenericName: var genericName = (GenericNameSyntax)name; AppendDotIfNeeded(builder); builder.Append(genericName.Identifier.ValueText); AppendArity(builder, genericName.Arity); break; case SyntaxKind.AliasQualifiedName: var aliasQualifiedName = (AliasQualifiedNameSyntax)name; AppendName(builder, aliasQualifiedName.Alias); builder.Append("::"); AppendName(builder, aliasQualifiedName.Name); break; case SyntaxKind.QualifiedName: AppendName(builder, ((QualifiedNameSyntax)name).Right); break; } } private static void AppendTypeName(StringBuilder builder, TypeSyntax type) { if (type is NameSyntax name) { AppendName(builder, name); } else { switch (type.Kind()) { case SyntaxKind.PredefinedType: builder.Append(((PredefinedTypeSyntax)type).Keyword.ValueText); break; case SyntaxKind.ArrayType: var arrayType = (ArrayTypeSyntax)type; AppendTypeName(builder, arrayType.ElementType); var specifiers = arrayType.RankSpecifiers; for (int i = 0; i < specifiers.Count; i++) { builder.Append('['); var specifier = specifiers[i]; if (specifier.Rank > 1) { builder.Append(',', specifier.Rank - 1); } builder.Append(']'); } break; case SyntaxKind.PointerType: AppendTypeName(builder, ((PointerTypeSyntax)type).ElementType); builder.Append('*'); break; case SyntaxKind.NullableType: AppendTypeName(builder, ((NullableTypeSyntax)type).ElementType); builder.Append('?'); break; } } } private static void AppendParameterList(StringBuilder builder, BaseParameterListSyntax parameterList) { builder.Append(parameterList is BracketedParameterListSyntax ? '[' : '('); var firstSeen = false; foreach (var parameter in parameterList.Parameters) { if (firstSeen) { builder.Append(","); } if (parameter.Modifiers.Any(SyntaxKind.RefKeyword)) { builder.Append("ref "); } else if (parameter.Modifiers.Any(SyntaxKind.OutKeyword)) { builder.Append("out "); } else if (parameter.Modifiers.Any(SyntaxKind.ParamsKeyword)) { builder.Append("params "); } AppendTypeName(builder, parameter.Type); firstSeen = true; } builder.Append(parameterList is BracketedParameterListSyntax ? ']' : ')'); } private static void AppendOperatorName(StringBuilder builder, SyntaxKind kind) { var name = "#op_" + kind.ToString(); if (name.EndsWith("Keyword", StringComparison.Ordinal)) { name = name.Substring(0, name.Length - 7); } else if (name.EndsWith("Token", StringComparison.Ordinal)) { name = name.Substring(0, name.Length - 5); } builder.Append(name); } protected override void AppendNodeName(StringBuilder builder, SyntaxNode node) { Debug.Assert(node != null); Debug.Assert(IsNameableNode(node)); AppendDotIfNeeded(builder); switch (node.Kind()) { case SyntaxKind.NamespaceDeclaration: var namespaceDeclaration = (NamespaceDeclarationSyntax)node; AppendName(builder, namespaceDeclaration.Name); break; case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; builder.Append(typeDeclaration.Identifier.ValueText); AppendArity(builder, typeDeclaration.Arity); break; case SyntaxKind.EnumDeclaration: var enumDeclaration = (EnumDeclarationSyntax)node; builder.Append(enumDeclaration.Identifier.ValueText); break; case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; builder.Append(delegateDeclaration.Identifier.ValueText); AppendArity(builder, delegateDeclaration.Arity); break; case SyntaxKind.EnumMemberDeclaration: var enumMemberDeclaration = (EnumMemberDeclarationSyntax)node; builder.Append(enumMemberDeclaration.Identifier.ValueText); break; case SyntaxKind.VariableDeclarator: var variableDeclarator = (VariableDeclaratorSyntax)node; builder.Append(variableDeclarator.Identifier.ValueText); break; case SyntaxKind.MethodDeclaration: var methodDeclaration = (MethodDeclarationSyntax)node; builder.Append(methodDeclaration.Identifier.ValueText); AppendArity(builder, methodDeclaration.Arity); AppendParameterList(builder, methodDeclaration.ParameterList); break; case SyntaxKind.OperatorDeclaration: var operatorDeclaration = (OperatorDeclarationSyntax)node; AppendOperatorName(builder, operatorDeclaration.OperatorToken.Kind()); AppendParameterList(builder, operatorDeclaration.ParameterList); break; case SyntaxKind.ConversionOperatorDeclaration: var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; AppendOperatorName(builder, conversionOperatorDeclaration.ImplicitOrExplicitKeyword.Kind()); builder.Append('_'); AppendTypeName(builder, conversionOperatorDeclaration.Type); AppendParameterList(builder, conversionOperatorDeclaration.ParameterList); break; case SyntaxKind.ConstructorDeclaration: var constructorDeclaration = (ConstructorDeclarationSyntax)node; builder.Append(constructorDeclaration.Modifiers.Any(SyntaxKind.StaticKeyword) ? "#sctor" : "#ctor"); AppendParameterList(builder, constructorDeclaration.ParameterList); break; case SyntaxKind.DestructorDeclaration: builder.Append("#dtor()"); break; case SyntaxKind.IndexerDeclaration: var indexerDeclaration = (IndexerDeclarationSyntax)node; builder.Append("#this"); AppendParameterList(builder, indexerDeclaration.ParameterList); break; case SyntaxKind.PropertyDeclaration: var propertyDeclaration = (PropertyDeclarationSyntax)node; builder.Append(propertyDeclaration.Identifier.ValueText); break; case SyntaxKind.EventDeclaration: var eventDeclaration = (EventDeclarationSyntax)node; builder.Append(eventDeclaration.Identifier.ValueText); break; } } } } }
// 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. // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_PropertyInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class PropertyInfo : MemberInfo, _PropertyInfo { #region Constructor protected PropertyInfo() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(PropertyInfo left, PropertyInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimePropertyInfo || right is RuntimePropertyInfo) { return false; } return left.Equals(right); } public static bool operator !=(PropertyInfo left, PropertyInfo right) { return !(left == right); } #endif // !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Property; } } #endregion #region Public Abstract\Virtual Members public virtual object GetConstantValue() { throw new NotImplementedException(); } public virtual object GetRawConstantValue() { throw new NotImplementedException(); } public abstract Type PropertyType { get; } public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture); public abstract MethodInfo[] GetAccessors(bool nonPublic); public abstract MethodInfo GetGetMethod(bool nonPublic); public abstract MethodInfo GetSetMethod(bool nonPublic); public abstract ParameterInfo[] GetIndexParameters(); public abstract PropertyAttributes Attributes { get; } public abstract bool CanRead { get; } public abstract bool CanWrite { get; } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public Object GetValue(Object obj) { return GetValue(obj, null); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public virtual Object GetValue(Object obj,Object[] index) { return GetValue(obj, BindingFlags.Default, null, index, null); } public abstract Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture); [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public void SetValue(Object obj, Object value) { SetValue(obj, value, null); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public virtual void SetValue(Object obj, Object value, Object[] index) { SetValue(obj, value, BindingFlags.Default, null, index, null); } #endregion #region Public Members public virtual Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; } public virtual Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; } public MethodInfo[] GetAccessors() { return GetAccessors(false); } public virtual MethodInfo GetMethod { get { return GetGetMethod(true); } } public virtual MethodInfo SetMethod { get { return GetSetMethod(true); } } public MethodInfo GetGetMethod() { return GetGetMethod(false); } public MethodInfo GetSetMethod() { return GetSetMethod(false); } public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } } #endregion #if !FEATURE_CORECLR Type _PropertyInfo.GetType() { return base.GetType(); } void _PropertyInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _PropertyInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _PropertyInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _PropertyInfo.Invoke in VM\DangerousAPIs.h and // include _PropertyInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _PropertyInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable { #region Private Data Members private int m_token; private string m_name; [System.Security.SecurityCritical] private void* m_utf8name; private PropertyAttributes m_flags; private RuntimeTypeCache m_reflectedTypeCache; private RuntimeMethodInfo m_getterMethod; private RuntimeMethodInfo m_setterMethod; private MethodInfo[] m_otherMethod; private RuntimeType m_declaringType; private BindingFlags m_bindingFlags; private Signature m_signature; private ParameterInfo[] m_parameters; #endregion #region Constructor [System.Security.SecurityCritical] // auto-generated internal RuntimePropertyInfo( int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { Contract.Requires(declaredType != null); Contract.Requires(reflectedTypeCache != null); Contract.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; m_token = tkProperty; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaredType; ConstArray sig; scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig); RuntimeMethodInfo dummy; Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(), out dummy, out dummy, out dummy, out m_getterMethod, out m_setterMethod, out m_otherMethod, out isPrivate, out m_bindingFlags); } #endregion #region Internal Members [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RuntimePropertyInfo m = o as RuntimePropertyInfo; if ((object)m == null) return false; return m.m_token == m_token && RuntimeTypeHandle.GetModule(m_declaringType).Equals( RuntimeTypeHandle.GetModule(m.m_declaringType)); } internal Signature Signature { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_signature == null) { PropertyAttributes flags; ConstArray sig; void* name; GetRuntimeModule().MetadataImport.GetPropertyProps( m_token, out name, out flags, out sig); m_signature = new Signature(sig.Signature.ToPointer(), (int)sig.Length, m_declaringType); } return m_signature; } } internal bool EqualsSig(RuntimePropertyInfo target) { //@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties. // The comparison is done by name and by sig. The EqualsSig comparison is expensive // but forutnetly it is only called when an inherited property is hidden by name or // when an interfaces declare properies with the same signature. // Note that we intentionally don't resolve generic arguments so that we don't treat // signatures that only match in certain instantiations as duplicates. This has the // down side of treating overriding and overriden properties as different properties // in some cases. But PopulateProperties in rttype.cs should have taken care of that // by comparing VTable slots. // // Class C1(Of T, Y) // Property Prop1(ByVal t1 As T) As Integer // Get // ... ... // End Get // End Property // Property Prop1(ByVal y1 As Y) As Integer // Get // ... ... // End Get // End Property // End Class // Contract.Requires(Name.Equals(target.Name)); Contract.Requires(this != target); Contract.Requires(this.ReflectedType == target.ReflectedType); return Signature.CompareSig(this.Signature, target.Signature); } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } #endregion #region Object Overrides public override String ToString() { return FormatNameAndSig(false); } private string FormatNameAndSig(bool serialization) { StringBuilder sbName = new StringBuilder(PropertyType.FormatTypeName(serialization)); sbName.Append(" "); sbName.Append(Name); RuntimeType[] arguments = Signature.Arguments; if (arguments.Length > 0) { sbName.Append(" ["); sbName.Append(MethodBase.ConstructParameters(arguments, Signature.CallingConvention, serialization)); sbName.Append("]"); } return sbName.ToString(); } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Property; } } public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = new Utf8String(m_utf8name).ToString(); return m_name; } } public override Type DeclaringType { get { return m_declaringType; } } public override Type ReflectedType { get { return ReflectedTypeInternal; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } public override int MetadataToken { get { return m_token; } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } #endregion #region PropertyInfo Overrides #region Non Dynamic public override Type[] GetRequiredCustomModifiers() { return Signature.GetCustomModifiers(0, true); } public override Type[] GetOptionalCustomModifiers() { return Signature.GetCustomModifiers(0, false); } [System.Security.SecuritySafeCritical] // auto-generated internal object GetConstantValue(bool raw) { Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw); if (defaultValue == DBNull.Value) // Arg_EnumLitValueNotFound -> "Literal value was not found." throw new InvalidOperationException(Environment.GetResourceString("Arg_EnumLitValueNotFound")); return defaultValue; } public override object GetConstantValue() { return GetConstantValue(false); } public override object GetRawConstantValue() { return GetConstantValue(true); } public override MethodInfo[] GetAccessors(bool nonPublic) { List<MethodInfo> accessorList = new List<MethodInfo>(); if (Associates.IncludeAccessor(m_getterMethod, nonPublic)) accessorList.Add(m_getterMethod); if (Associates.IncludeAccessor(m_setterMethod, nonPublic)) accessorList.Add(m_setterMethod); if ((object)m_otherMethod != null) { for(int i = 0; i < m_otherMethod.Length; i ++) { if (Associates.IncludeAccessor(m_otherMethod[i] as MethodInfo, nonPublic)) accessorList.Add(m_otherMethod[i]); } } return accessorList.ToArray(); } public override Type PropertyType { get { return Signature.ReturnType; } } public override MethodInfo GetGetMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_getterMethod, nonPublic)) return null; return m_getterMethod; } public override MethodInfo GetSetMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_setterMethod, nonPublic)) return null; return m_setterMethod; } public override ParameterInfo[] GetIndexParameters() { ParameterInfo[] indexParams = GetIndexParametersNoCopy(); int numParams = indexParams.Length; if (numParams == 0) return indexParams; ParameterInfo[] ret = new ParameterInfo[numParams]; Array.Copy(indexParams, ret, numParams); return ret; } internal ParameterInfo[] GetIndexParametersNoCopy() { // @History - Logic ported from RTM // No need to lock because we don't guarantee the uniqueness of ParameterInfo objects if (m_parameters == null) { int numParams = 0; ParameterInfo[] methParams = null; // First try to get the Get method. MethodInfo m = GetGetMethod(true); if (m != null) { // There is a Get method so use it. methParams = m.GetParametersNoCopy(); numParams = methParams.Length; } else { // If there is no Get method then use the Set method. m = GetSetMethod(true); if (m != null) { methParams = m.GetParametersNoCopy(); numParams = methParams.Length - 1; } } // Now copy over the parameter info's and change their // owning member info to the current property info. ParameterInfo[] propParams = new ParameterInfo[numParams]; for (int i = 0; i < numParams; i++) propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this); m_parameters = propParams; } return m_parameters; } public override PropertyAttributes Attributes { get { return m_flags; } } public override bool CanRead { get { return m_getterMethod != null; } } public override bool CanWrite { get { return m_setterMethod != null; } } #endregion #region Dynamic [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override Object GetValue(Object obj,Object[] index) { return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, index, null); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) { MethodInfo m = GetGetMethod(true); if (m == null) throw new ArgumentException(System.Environment.GetResourceString("Arg_GetMethNotFnd")); return m.Invoke(obj, invokeAttr, binder, index, null); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, Object[] index) { SetValue(obj, value, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, index, null); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) { MethodInfo m = GetSetMethod(true); if (m == null) throw new ArgumentException(System.Environment.GetResourceString("Arg_SetMethNotFnd")); Object[] args = null; if (index != null) { args = new Object[index.Length + 1]; for(int i=0;i<index.Length;i++) args[i] = index[i]; args[index.Length] = value; } else { args = new Object[1]; args[0] = value; } m.Invoke(obj, invokeAttr, binder, args, culture); } #endregion #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), SerializationToString(), MemberTypes.Property, null); } internal string SerializationToString() { return FormatNameAndSig(true); } #endregion } }
/* * * (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.Globalization; using System.Linq; using System.Text; using System.Web; using System.Web.UI.WebControls; using ASC.Common.Logging; using ASC.Core; using ASC.CRM.Core; using ASC.CRM.Core.Dao; using ASC.CRM.Core.Entities; using ASC.MessagingSystem; using ASC.Web.CRM.Classes; using ASC.Web.CRM.Core; using ASC.Web.CRM.Resources; using ASC.Web.Studio.Core; using ASC.Web.Studio.Utility; using Autofac; namespace ASC.Web.CRM.Controls.Invoices { public partial class InvoiceActionView : BaseUserControl { #region Properies public static string Location { get { return PathProvider.GetFileStaticRelativePath("Invoices/InvoiceActionView.ascx"); } } public InvoiceActionType ActionType { get; set; } public Invoice TargetInvoice { get; set; } private const string ErrorCookieKey = "save_invoice_error"; protected string InvoicesNumber { get { var number = ActionType == InvoiceActionType.Edit ? TargetInvoice.Number : DaoFactory.InvoiceDao.GetNewInvoicesNumber(); return number.HtmlEncode(); } } #endregion #region Events protected void Page_Load(object sender, EventArgs e) { bool havePermission; if (ActionType == InvoiceActionType.Duplicate) { havePermission = TargetInvoice != null && CRMSecurity.CanAccessTo(TargetInvoice); } else { havePermission = TargetInvoice == null || CRMSecurity.CanEdit(TargetInvoice); } if (!havePermission) { Response.Redirect(PathProvider.StartURL() + "Invoices.aspx"); } RegisterClientScriptHelper.DataInvoicesActionView(Page, TargetInvoice); InitActionButtons(); RegisterScript(); } protected void SaveOrUpdateInvoice(Object sender, CommandEventArgs e) { try { using (var scope = DIHelper.Resolve()) { var dao = scope.Resolve<DaoFactory>(); var invoice = GetInvoice(dao); var billingAddressID = Convert.ToInt32(Request["billingAddressID"]); var deliveryAddressID = Convert.ToInt32(Request["deliveryAddressID"]); var messageAction = MessageAction.InvoiceCreated; if (invoice.ID > 0) { messageAction = MessageAction.InvoiceUpdated; RemoveInvoiceFile(invoice.FileID, dao); } invoice.ID = dao.InvoiceDao.SaveOrUpdateInvoice(invoice); MessageService.Send(HttpContext.Current.Request, messageAction, MessageTarget.Create(invoice.ID), invoice.Number); var invoiceLines = GetInvoiceLines(dao); foreach (var line in invoiceLines) { line.InvoiceID = invoice.ID; line.ID = dao.InvoiceLineDao.SaveOrUpdateInvoiceLine(line); } RemoveUnusedLines(invoice.ID, invoiceLines, dao); dao.InvoiceDao.UpdateInvoiceJsonData(invoice, billingAddressID, deliveryAddressID); if (Global.CanDownloadInvoices) { PdfQueueWorker.StartTask(HttpContext.Current, TenantProvider.CurrentTenantID, SecurityContext.CurrentAccount.ID, invoice.ID); } string redirectUrl; if (ActionType == InvoiceActionType.Create && UrlParameters.ContactID != 0) { redirectUrl = string.Format( e.CommandArgument.ToString() == "1" ? "Invoices.aspx?action=create&contactID={0}" : "Default.aspx?id={0}#invoices", UrlParameters.ContactID); } else { redirectUrl = e.CommandArgument.ToString() == "1" ? "Invoices.aspx?action=create" : string.Format("Invoices.aspx?id={0}", invoice.ID); } Response.Redirect(redirectUrl, false); Context.ApplicationInstance.CompleteRequest(); } } catch (Exception ex) { if (!(ex is InvoiceValidationException)) LogManager.GetLogger("ASC.CRM").Error(ex); var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey); if (cookie == null) { cookie = new HttpCookie(ErrorCookieKey) { Value = ex.Message }; HttpContext.Current.Response.Cookies.Add(cookie); } } } #endregion #region Methods private void InitActionButtons() { saveButton.OnClientClick = String.Format("return ASC.CRM.InvoiceActionView.submitForm('{0}');", saveButton.UniqueID); saveAndCreateNewButton.OnClientClick = String.Format("return ASC.CRM.InvoiceActionView.submitForm('{0}');", saveAndCreateNewButton.UniqueID); if (ActionType == InvoiceActionType.Create) { saveButton.Text = CRMInvoiceResource.AddThisInvoiceButton; saveAndCreateNewButton.Text = CRMInvoiceResource.AddAndCreateNewInvoiceButton; cancelButton.Attributes.Add("href", Request.UrlReferrer != null && Request.Url != null && String.Compare(Request.UrlReferrer.PathAndQuery, Request.Url.PathAndQuery) != 0 ? Request.UrlReferrer.OriginalString : "Invoices.aspx"); } if (ActionType == InvoiceActionType.Edit) { saveButton.Text = CRMCommonResource.SaveChanges; cancelButton.Attributes.Add("href", String.Format("Invoices.aspx?id={0}", TargetInvoice.ID)); } if (ActionType == InvoiceActionType.Duplicate) { saveButton.Text = CRMInvoiceResource.DuplicateInvoiceButton; saveAndCreateNewButton.Text = CRMInvoiceResource.DuplicateAndCreateNewInvoiceButton; cancelButton.Attributes.Add("href", String.Format("Invoices.aspx?id={0}", TargetInvoice.ID)); } } private void RegisterScript() { Page.RegisterClientScript(new Masters.ClientScripts.ExchangeRateViewData()); var sb = new StringBuilder(); sb.AppendFormat(@"ASC.CRM.InvoiceActionView.init({0}, ""{1}"");", (int)ContactSelectorTypeEnum.All, ErrorCookieKey ); Page.RegisterInlineScript(sb.ToString()); } private Invoice GetInvoice(DaoFactory dao) { var invoice = new Invoice(); if (ActionType == InvoiceActionType.Edit) { invoice.ID = TargetInvoice.ID; invoice.Number = TargetInvoice.Number; invoice.FileID = TargetInvoice.FileID; } else { invoice.Number = Request["invoiceNumber"]; if (dao.InvoiceDao.IsExist(invoice.Number)) throw new InvoiceValidationException(CRMErrorsResource.InvoiceNumberBusy); } DateTime issueDate; if (!DateTime.TryParse(Request["invoiceIssueDate"], out issueDate)) throw new InvoiceValidationException("invalid issueDate"); invoice.IssueDate = issueDate; invoice.ContactID = Convert.ToInt32(Request["invoiceContactID"]); if (invoice.ContactID <= 0) throw new InvoiceValidationException(CRMErrorsResource.InvoiceContactNotFound); var contact = dao.ContactDao.GetByID(invoice.ContactID); if (contact == null || !CRMSecurity.CanAccessTo(contact)) { throw new InvoiceValidationException(CRMErrorsResource.InvoiceContactNotFound); } invoice.ConsigneeID = Convert.ToInt32(Request["invoiceConsigneeID"]); if (invoice.ConsigneeID > 0) { var consignee = dao.ContactDao.GetByID(invoice.ConsigneeID); if (consignee == null || !CRMSecurity.CanAccessTo(consignee)) { throw new InvoiceValidationException(CRMErrorsResource.InvoiceConsigneeNotFound); } } else { invoice.ConsigneeID = 0; } invoice.EntityType = EntityType.Opportunity; invoice.EntityID = Convert.ToInt32(Request["invoiceOpportunityID"]); if (invoice.EntityID > 0) { var deal = dao.DealDao.GetByID(invoice.EntityID); if (deal == null || !CRMSecurity.CanAccessTo(deal)) throw new InvoiceValidationException(CRMErrorsResource.DealNotFound); var dealMembers = dao.DealDao.GetMembers(invoice.EntityID); if (!dealMembers.Contains(invoice.ContactID)) throw new InvoiceValidationException("contact doesn't have this opportunity"); } DateTime dueDate; if (!DateTime.TryParse(Request["invoiceDueDate"], out dueDate)) throw new InvoiceValidationException(CRMErrorsResource.InvoiceDueDateInvalid); if (issueDate > dueDate) throw new InvoiceValidationException(CRMErrorsResource.InvoiceIssueMoreThanDue); invoice.DueDate = dueDate; invoice.Language = Request["invoiceLanguage"]; if (string.IsNullOrEmpty(invoice.Language) || SetupInfo.EnabledCultures.All(c => c.Name != invoice.Language)) throw new InvoiceValidationException(CRMErrorsResource.LanguageNotFound); invoice.Currency = Request["invoiceCurrency"]; if (string.IsNullOrEmpty(invoice.Currency)) { throw new InvoiceValidationException(CRMErrorsResource.CurrencyNotFound); } else { invoice.Currency = invoice.Currency.ToUpper(); if (CurrencyProvider.Get(invoice.Currency) == null) { throw new InvoiceValidationException(CRMErrorsResource.CurrencyNotFound); } } invoice.ExchangeRate = Convert.ToDecimal(Request["invoiceExchangeRate"], new CultureInfo("en-US")); if (invoice.ExchangeRate <= 0) throw new InvoiceValidationException(CRMErrorsResource.ExchangeRateNotSet); invoice.PurchaseOrderNumber = Request["invoicePurchaseOrderNumber"]; invoice.Terms = Request["invoiceTerms"]; if (string.IsNullOrEmpty(invoice.Terms)) throw new InvoiceValidationException(CRMErrorsResource.InvoiceTermsNotFound); invoice.Description = Request["invoiceDescription"]; invoice.Status = InvoiceStatus.Draft; invoice.TemplateType = InvoiceTemplateType.Eur; return invoice; } private List<InvoiceLine> GetInvoiceLines(DaoFactory dao) { var invoiceLines = new List<InvoiceLine>(); if (!Request.Form.AllKeys.Any(x => x.StartsWith("iLineItem_"))) throw new InvoiceValidationException(CRMErrorsResource.InvoiceItemsListEmpty); foreach (var customField in Request.Form.AllKeys) { if (!customField.StartsWith("iLineItem_")) continue; var id = Convert.ToInt32(customField.Split('_')[1]); var sortOrder = Convert.ToInt32(customField.Split('_')[2]); var invoiceItemID = Convert.ToInt32(Request["iLineItem_" + id + "_" + sortOrder]); var invoiceTax1ID = Convert.ToInt32(Request["iLineTax1_" + id + "_" + sortOrder]); var invoiceTax2ID = Convert.ToInt32(Request["iLineTax2_" + id + "_" + sortOrder]); if (!dao.InvoiceItemDao.IsExist(invoiceItemID)) throw new InvoiceValidationException(CRMErrorsResource.InvoiceItemNotFound); if (invoiceTax1ID > 0 && !dao.InvoiceTaxDao.IsExist(invoiceTax1ID)) throw new InvoiceValidationException(CRMErrorsResource.InvoiceTaxNotFound); if (invoiceTax2ID > 0 && !dao.InvoiceTaxDao.IsExist(invoiceTax2ID)) throw new InvoiceValidationException(CRMErrorsResource.InvoiceTaxNotFound); var line = new InvoiceLine { ID = id, InvoiceItemID = invoiceItemID, InvoiceTax1ID = invoiceTax1ID, InvoiceTax2ID = invoiceTax2ID, Description = Request["iLineDescription_" + id + "_" + sortOrder], Quantity = Convert.ToDecimal(Request["iLineQuantity_" + id + "_" + sortOrder], new CultureInfo("en-US")), Price = Convert.ToDecimal(Request["iLinePrice_" + id + "_" + sortOrder], new CultureInfo("en-US")), Discount = Convert.ToDecimal(Request["iLineDiscount_" + id + "_" + sortOrder], new CultureInfo("en-US")), SortOrder = sortOrder }; invoiceLines.Add(line); } return invoiceLines; } private void RemoveUnusedLines(int invoiceID, List<InvoiceLine> lines, DaoFactory dao) { var oldLines = dao.InvoiceLineDao.GetInvoiceLines(invoiceID); foreach (var line in oldLines) { var contains = lines.Any(x => x.ID == line.ID); if (!contains) { dao.InvoiceLineDao.DeleteInvoiceLine(line.ID); } } } private void RemoveInvoiceFile(int fileID, DaoFactory dao) { var events = dao.FileDao.GetEventsByFile(fileID); foreach (var eventId in events) { var item = dao.RelationshipEventDao.GetByID(eventId); if (item != null && item.CategoryID == (int)HistoryCategorySystem.FilesUpload && dao.RelationshipEventDao.GetFiles(item.ID).Count == 1) dao.RelationshipEventDao.DeleteItem(item); } } #endregion #region InvoiceValidationException private class InvoiceValidationException : Exception { public InvoiceValidationException(string message) : base(message) { } } #endregion } }
//--------------------------------------------------------------------- // This file is part of the CLR Managed Debugger (mdbg) Sample. // // Copyright (C) Microsoft Corporation. All rights reserved. //--------------------------------------------------------------------- using System; using System.Threading; using System.Diagnostics; using System.Collections; using System.Security.Permissions; using Microsoft.Samples.Debugging.CorDebug; using Microsoft.Samples.Debugging.CorDebug.NativeApi; using Microsoft.Samples.Debugging.CorMetadata; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using Microsoft.Samples.Debugging.CorDebug.Utility; using Microsoft.Samples.Debugging.Native; using Microsoft.Win32.SafeHandles; using Microsoft.Samples.Debugging.MetaDataLocator; namespace Microsoft.Samples.Debugging.CorDebug.Utility { #region Dump Data Target /// <summary> /// Data target implementation for a dump file /// </summary> [CLSCompliant(false)] public sealed class DumpDataTarget : ICorDebugDataTarget, ICorDebugMetaDataLocator, IDisposable { Microsoft.Samples.Debugging.Native.DumpReader m_reader; Microsoft.Samples.Debugging.MetaDataLocator.CorDebugMetaDataLocator m_metaDataLocator; /// <summary> /// Constructor a Dump Target around an existing DumpReader. /// </summary> /// <param name="reader"></param> public DumpDataTarget(DumpReader reader)//, MdbgEngine.MDbgOptions options) { m_reader = reader; string s = ".\\"; try { // For our trivial implementation, try looking in the CLR directory DumpModule dm = m_reader.LookupModule("clr.dll"); s = dm.FullName; if (s.LastIndexOf('\\') != -1) { s = s.Substring(0, s.LastIndexOf('\\')); } } catch (DumpMissingDataException) { } m_metaDataLocator = new CorDebugMetaDataLocator(s);//, options); } /// <summary> /// Construct a dump target around the dump file. /// </summary> /// <param name="fileName"></param> public DumpDataTarget(string fileName) { m_reader = new Microsoft.Samples.Debugging.Native.DumpReader(fileName); } /// <summary> /// Dispose method. /// </summary> public void Dispose() { if (m_reader != null) { m_reader.Dispose(); } } #region ICorDebugDataTarget Members /// <summary> /// Implementation of ICorDebugDataTarget.GetPlatform /// </summary> /// <param name="type">platform that the process in this dump was executing on</param> public CorDebugPlatform GetPlatform() { // Infer platform based off CPU architecture // At the moment we only support windows. ProcessorArchitecture p = this.m_reader.ProcessorArchitecture; switch (p) { case ProcessorArchitecture.PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: case ProcessorArchitecture.PROCESSOR_ARCHITECTURE_INTEL: return CorDebugPlatform.CORDB_PLATFORM_WINDOWS_X86; case ProcessorArchitecture.PROCESSOR_ARCHITECTURE_IA64: return CorDebugPlatform.CORDB_PLATFORM_WINDOWS_IA64; case ProcessorArchitecture.PROCESSOR_ARCHITECTURE_AMD64: return CorDebugPlatform.CORDB_PLATFORM_WINDOWS_AMD64; } throw new InvalidOperationException("Unrecognized target architecture " + p); } // Implementation of ICorDebugDataTarget.ReadVirtual public uint ReadVirtual(ulong address, IntPtr buffer, uint bytesRequested) { uint bytesRead = m_reader.ReadPartialMemory(address, buffer, bytesRequested); if(bytesRead == 0) throw new System.Runtime.InteropServices.COMException("Could not read memory requested at address " + address + "."); return bytesRead; } // Implementation of ICorDebugDataTarget.GetThreadContext public void GetThreadContext(uint threadId, uint contextFlags, uint contextSize, IntPtr context) { // Ignore contextFlags because this will retrieve everything. m_reader.GetThread((int) threadId).GetThreadContext(context, (int) contextSize); } #endregion #region ICorDebugMetaDataLocator Members // Implementation of ICorDebugMetaDataLocator.GetMetaData public void GetMetaData(string imagePath, uint dwImageTimeStamp, uint dwImageSize, uint cchPathBuffer, out uint pcchPathBuffer, char[] wszPathBuffer) { m_metaDataLocator.GetMetaData(imagePath, dwImageTimeStamp, dwImageSize, cchPathBuffer, out pcchPathBuffer, wszPathBuffer); } #endregion } #endregion /// <summary> /// Utility class to wrap an unmanaged DLL and be responsible for freeing it. /// </summary> /// <remarks>This is a managed wrapper over the native LoadLibrary, GetProcAddress, and /// FreeLibrary calls. /// <list> /// <item>It wraps the raw pinvokes, and uses exceptions for error handling.</item> /// <item>It provides type-safe delegate wrappers over GetProcAddress</item> /// <item>It uses SafeHandles for the unmanaged resources</item> /// </list> /// You must be very careful to not call FreeLibrary (Dispose) until you are done with the /// library. If you call GetProcAddress after the library is freed, it will crash. /// </remarks> public sealed class UnmanagedLibraryLeak { #region Safe Handles and Native imports // See http://msdn.microsoft.com/msdnmag/issues/05/10/Reliability/ for more about safe handles. [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeLibraryHandle() : base(true) { } protected override bool ReleaseHandle() { // Since we can't safely Free the library yet, we don't. Once we can do this // safely, then this is the spot to call kernel32!FreeLibrary. return true; } } static class NativeMethods { const string s_kernel = "kernel32"; [DllImport(s_kernel, CharSet = CharSet.Auto, BestFitMapping = false, SetLastError = true)] public static extern SafeLibraryHandle LoadLibrary(string fileName); //[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] //[DllImport(s_kernel, SetLastError = true)] //[return: MarshalAs(UnmanagedType.Bool)] //public static extern bool FreeLibrary(IntPtr hModule); [DllImport(s_kernel)] public static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, String procname); } #endregion // Safe Handles and Native imports /// <summary> /// Constructor to load a dll and be responible for freeing it. /// </summary> /// <param name="fileName">full path name of dll to load</param> /// <exception cref="System.IO.FileNotFound">if fileName can't be found</exception> /// <remarks>Throws exceptions on failure. Most common failure would be file-not-found, or /// that the file is not a loadable image.</remarks> public UnmanagedLibraryLeak(string fileName) { m_hLibrary = NativeMethods.LoadLibrary(fileName); if (m_hLibrary.IsInvalid) { int hr = Marshal.GetHRForLastWin32Error(); Marshal.ThrowExceptionForHR(hr); } } /// <summary> /// Dynamically lookup a function in the dll via kernel32!GetProcAddress. /// </summary> /// <param name="functionName">raw name of the function in the export table.</param> /// <returns>null if function is not found. Else a delegate to the unmanaged function. /// </returns> /// <remarks>GetProcAddress results are valid as long as the dll is not yet unloaded. This /// is very very dangerous to use since you need to ensure that the dll is not unloaded /// until after you're done with any objects implemented by the dll. For example, if you /// get a delegate that then gets an IUnknown implemented by this dll, /// you can not dispose this library until that IUnknown is collected. Else, you may free /// the library and then the CLR may call release on that IUnknown and it will crash.</remarks> public TDelegate GetUnmanagedFunction<TDelegate>(string functionName) where TDelegate : class { IntPtr p = NativeMethods.GetProcAddress(m_hLibrary, functionName); // Failure is a common case, especially for adaptive code. if (p == IntPtr.Zero) { return null; } Delegate function = Marshal.GetDelegateForFunctionPointer(p, typeof(TDelegate)); // Ideally, we'd just make the constraint on TDelegate be // System.Delegate, but compiler error CS0702 (constrained can't be System.Delegate) // prevents that. So we make the constraint system.object and do the cast from object-->TDelegate. object o = function; return (TDelegate)o; } // Unmanaged resource. SafeLibraryHandle m_hLibrary; } // UnmanagedLibrary } // Microsoft.Samples.Debugging.CorDebug.Utility
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Reflection; using ServiceStack.Text.Common; using ServiceStack.Text.Jsv; namespace ServiceStack.Text { /// <summary> /// Creates an instance of a Type from a string value /// </summary> public static class TypeSerializer { private static readonly UTF8Encoding UTF8EncodingWithoutBom = new UTF8Encoding(false); public const string DoubleQuoteString = "\"\""; /// <summary> /// Determines whether the specified type is convertible from string. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if the specified type is convertible from string; otherwise, <c>false</c>. /// </returns> public static bool CanCreateFromString(Type type) { return JsvReader.GetParseFn(type) != null; } /// <summary> /// Parses the specified value. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static T DeserializeFromString<T>(string value) { if (string.IsNullOrEmpty(value)) return default(T); return (T)JsvReader<T>.Parse(value); } public static T DeserializeFromReader<T>(TextReader reader) { return DeserializeFromString<T>(reader.ReadToEnd()); } /// <summary> /// Parses the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object DeserializeFromString(string value, Type type) { return value == null ? null : JsvReader.GetParseFn(type)(value); } public static object DeserializeFromReader(TextReader reader, Type type) { return DeserializeFromString(reader.ReadToEnd(), type); } public static string SerializeToString<T>(T value) { if (value == null) return null; if (typeof(T) == typeof(string)) return value as string; #if NETFX_CORE if (typeof(T) == typeof(object) || typeof(T).GetTypeInfo().IsAbstract || typeof(T).GetTypeInfo().IsInterface) { if (typeof(T).GetTypeInfo().IsAbstract || typeof(T).GetTypeInfo().IsInterface) JsState.IsWritingDynamic = true; var result = SerializeToString(value, value.GetType()); if (typeof(T).GetTypeInfo().IsAbstract || typeof(T).GetTypeInfo().IsInterface) JsState.IsWritingDynamic = false; return result; } #else if (typeof(T) == typeof(object) || typeof(T).IsAbstract || typeof(T).IsInterface) { if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = true; var result = SerializeToString(value, value.GetType()); if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = false; return result; } #endif var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { JsvWriter<T>.WriteObject(writer, value); } return sb.ToString(); } public static string SerializeToString(object value, Type type) { if (value == null) return null; if (type == typeof(string)) return value as string; var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { JsvWriter.GetWriteFn(type)(writer, value); } return sb.ToString(); } public static void SerializeToWriter<T>(T value, TextWriter writer) { if (value == null) return; if (typeof(T) == typeof(string)) { writer.Write(value); return; } if (typeof(T) == typeof(object)) { #if NETFX_CORE if (typeof(T).GetTypeInfo().IsAbstract || typeof(T).GetTypeInfo().IsInterface) JsState.IsWritingDynamic = true; SerializeToWriter(value, value.GetType(), writer); if (typeof(T).GetTypeInfo().IsAbstract || typeof(T).GetTypeInfo().IsInterface) JsState.IsWritingDynamic = false; #else if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = true; SerializeToWriter(value, value.GetType(), writer); if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = false; #endif return; } JsvWriter<T>.WriteObject(writer, value); } public static void SerializeToWriter(object value, Type type, TextWriter writer) { if (value == null) return; if (type == typeof(string)) { writer.Write(value); return; } JsvWriter.GetWriteFn(type)(writer, value); } public static void SerializeToStream<T>(T value, Stream stream) { if (value == null) return; if (typeof(T) == typeof(object)) { #if NETFX_CORE if (typeof(T).GetTypeInfo().IsAbstract || typeof(T).GetTypeInfo().IsInterface) JsState.IsWritingDynamic = true; SerializeToStream(value, value.GetType(), stream); if (typeof(T).GetTypeInfo().IsAbstract || typeof(T).GetTypeInfo().IsInterface) JsState.IsWritingDynamic = false; #else if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = true; SerializeToStream(value, value.GetType(), stream); if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = false; #endif return; } var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsvWriter<T>.WriteObject(writer, value); writer.Flush(); } public static void SerializeToStream(object value, Type type, Stream stream) { var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsvWriter.GetWriteFn(type)(writer, value); writer.Flush(); } public static T Clone<T>(T value) { var serializedValue = SerializeToString(value); var cloneObj = DeserializeFromString<T>(serializedValue); return cloneObj; } public static T DeserializeFromStream<T>(Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString<T>(reader.ReadToEnd()); } } public static object DeserializeFromStream(Type type, Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString(reader.ReadToEnd(), type); } } /// <summary> /// Useful extension method to get the Dictionary[string,string] representation of any POCO type. /// </summary> /// <returns></returns> public static Dictionary<string, string> ToStringDictionary<T>(this T obj) where T : class { var jsv = SerializeToString(obj); var map = DeserializeFromString<Dictionary<string, string>>(jsv); return map; } /// <summary> /// Recursively prints the contents of any POCO object in a human-friendly, readable format /// </summary> /// <returns></returns> public static string Dump<T>(this T instance) { return SerializeAndFormat(instance); } /// <summary> /// Print Dump to Console.WriteLine /// </summary> public static void PrintDump<T>(this T instance) { #if NETFX_CORE System.Diagnostics.Debug.WriteLine(SerializeAndFormat(instance)); #else Console.WriteLine(SerializeAndFormat(instance)); #endif } /// <summary> /// Print string.Format to Console.WriteLine /// </summary> public static void Print(this string text, params object[] args) { #if NETFX_CORE if (args.Length > 0) System.Diagnostics.Debug.WriteLine(text, args); else System.Diagnostics.Debug.WriteLine(text); #else if (args.Length > 0) Console.WriteLine(text, args); else Console.WriteLine(text); #endif } public static string SerializeAndFormat<T>(this T instance) { var dtoStr = SerializeToString(instance); var formatStr = JsvFormatter.Format(dtoStr); return formatStr; } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Drawing.Drawing2D; using Autodesk.Revit.DB; using Point = System.Drawing.Point; namespace Revit.SDK.Samples.NewOpenings.CS { /// <summary> /// Main form used to display the profile of Wall or Floor and draw the opening profiles. /// </summary> public partial class NewOpeningsForm : System.Windows.Forms.Form { #region class members private Profile m_profile; //save the profile date (ProfileFloor or ProfileWall) private Matrix4 m_to2DMatrix; //save the matrix use to transform 3D to 2D private Matrix4 m_moveToCenterMatrix; //save the matrix use to move point to origin private Matrix4 m_scaleMatrix; //save the matrix use to scale private ITool m_tool = null; //current using tool private Queue<ITool> m_tools = new Queue<ITool>(); //all tool can use in pictureBox #endregion /// <summary> /// default constructor /// </summary> public NewOpeningsForm() { InitializeComponent(); } /// <summary> /// constructor /// </summary> /// <param name="profile">ProfileWall or ProfileFloor</param> public NewOpeningsForm(Profile profile) :this() { m_profile = profile; m_to2DMatrix = m_profile.To2DMatrix(); m_moveToCenterMatrix = m_profile.ToCenterMatrix(); InitTools(); } /// <summary> /// add tools, then use can draw by these tools in picture box /// </summary> private void InitTools() { //wall if(m_profile is ProfileWall) { m_tool = new RectTool(); m_tools.Enqueue(m_tool); m_tools.Enqueue(new EmptyTool()); } //floor else { m_tool = new LineTool(); m_tools.Enqueue(m_tool); m_tools.Enqueue(new RectTool()); m_tools.Enqueue(new CircleTool()); m_tools.Enqueue(new ArcTool()); m_tools.Enqueue(new EmptyTool()); } } /// <summary> /// use matrix to transform point /// </summary> /// <param name="pts">contain the points to be transform</param> private void TransFormPoints(Point[] pts) { System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix( 1, 0, 0, 1, this.openingPictureBox.Width / 2, this.openingPictureBox.Height / 2); matrix.Invert(); matrix.TransformPoints(pts); } /// <summary> /// get four points on circle by center and one point on circle /// </summary> /// <param name="points">contain the center and one point on circle</param> private List<Vector4> GenerateCircle4Point(List<Point> points) { Matrix rotation = new Matrix(); //get the circle center and bound point Point center = points[0]; Point bound = points[1]; rotation.RotateAt(90, (PointF)center); Point[] circle = new Point[4]; circle[0] = points[1]; for(int i = 1; i < 4; i++) { Point[] ps = new Point[1] { bound }; rotation.TransformPoints(ps); circle[i] = ps[0]; bound = ps[0]; } return TransForm2DTo3D(circle); } /// <summary> /// Transform the point on Form to 3d world coordinate of Revit /// </summary> /// <param name="ps">contain the points to be transform</param> private List<Vector4> TransForm2DTo3D(Point[] ps) { List<Vector4> result = new List<Vector4>(); TransFormPoints(ps); Matrix4 transFormMatrix = Matrix4.Multiply( m_scaleMatrix.Inverse(),m_moveToCenterMatrix); transFormMatrix = Matrix4.Multiply(transFormMatrix, m_to2DMatrix); foreach (Point point in ps) { Vector4 v = new Vector4(point.X, point.Y, 0); v = transFormMatrix.TransForm(v); result.Add(v); } return result; } /// <summary> /// calculate the matrix use to scale /// </summary> /// <param name="size">pictureBox size</param> private Matrix4 ComputerScaleMatrix(Size size) { PointF[] boundPoints = m_profile.GetFaceBounds(); float width = ((float)size.Width) / (boundPoints[1].X - boundPoints[0].X); float hight = ((float)size.Height) / (boundPoints[1].Y - boundPoints[0].Y); float factor = width <= hight ? width : hight; return new Matrix4(factor); } /// <summary> /// Calculate the matrix use to transform 3D to 2D /// </summary> private Matrix4 Comuter3DTo2DMatrix() { Matrix4 result = Matrix4.Multiply( m_to2DMatrix.Inverse(), m_moveToCenterMatrix.Inverse()); result = Matrix4.Multiply(result, m_scaleMatrix); return result; } private void OkButton_Click(object sender, EventArgs e) { foreach (ITool tool in m_tools) { List<List<Point>> curcves = tool.GetLines(); foreach (List<Point> curve in curcves) { List<Vector4> ps3D; if (tool.ToolType == ToolType.Circle) { ps3D = GenerateCircle4Point(curve); } else if (tool.ToolType == ToolType.Rectangle) { Point[] ps = new Point[4] { curve[0], new Point(curve[0].X, curve[1].Y), curve[1], new Point(curve[1].X, curve[0].Y) }; ps3D = TransForm2DTo3D(ps); } else { ps3D = TransForm2DTo3D(curve.ToArray()); } m_profile.DrawOpening(ps3D, tool.ToolType); } } this.Close(); } private void cancelButton_Click(object sender, EventArgs e) { this.Close(); } private void openingPictureBox_Paint(object sender, PaintEventArgs e) { //Draw the pictures in the m_tools list foreach (ITool tool in m_tools) { tool.Draw(e.Graphics); } //draw the tips string e.Graphics.DrawString(m_tool.ToolType.ToString(), SystemFonts.DefaultFont, SystemBrushes.Highlight, 2, 5); //move the origin to the picture center Size size = this.openingPictureBox.Size; e.Graphics.Transform = new System.Drawing.Drawing2D.Matrix( 1, 0, 0, 1, size.Width / 2, size.Height / 2); //draw profile Size scaleSize = new Size((int)(0.85 * size.Width), (int)(0.85 * size.Height)); m_scaleMatrix = ComputerScaleMatrix(scaleSize); Matrix4 trans = Comuter3DTo2DMatrix(); m_profile.Draw2D(e.Graphics, Pens.Blue, trans); } /// <summary> /// mouse event handle /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void openingPictureBox_MouseDown(object sender, MouseEventArgs e) { if (MouseButtons.Left == e.Button || MouseButtons.Right == e.Button) { Graphics g = openingPictureBox.CreateGraphics(); m_tool.OnMouseDown(g, e); m_tool.OnRightMouseClick(g, e); } else if (MouseButtons.Middle == e.Button) { m_tool.OnMidMouseDown(null, null); m_tool = m_tools.Peek(); m_tools.Enqueue(m_tool); m_tools.Dequeue(); Graphics graphic = openingPictureBox.CreateGraphics(); graphic.DrawString(m_tool.ToolType.ToString(), SystemFonts.DefaultFont, SystemBrushes.Highlight, 2, 5); this.Refresh(); } } /// <summary> /// Mouse event handle /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void openingPictureBox_MouseUp(object sender, MouseEventArgs e) { Graphics g = openingPictureBox.CreateGraphics(); m_tool.OnMouseUp(g, e); } /// <summary> /// Mouse event handle /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void openingPictureBox_MouseMove(object sender, MouseEventArgs e) { Graphics graphics = openingPictureBox.CreateGraphics(); m_tool.OnMouseMove(graphics, e); PaintEventArgs paintArg = new PaintEventArgs(graphics, new System.Drawing.Rectangle()); openingPictureBox_Paint(null, paintArg); } } }
using System; using System.Collections.Generic; using UnityEngine.Serialization; namespace UnityEngine.UI { /// <summary> /// Image is a textured element in the UI hierarchy. /// </summary> [AddComponentMenu("UI/Image", 10)] public class Image : MaskableGraphic, ISerializationCallbackReceiver, ILayoutElement, ICanvasRaycastFilter { public enum Type { Simple, Sliced, Tiled, Filled } public enum FillMethod { Horizontal, Vertical, Radial90, Radial180, Radial360, } public enum OriginHorizontal { Left, Right, } public enum OriginVertical { Bottom, Top, } public enum Origin90 { BottomLeft, TopLeft, TopRight, BottomRight, } public enum Origin180 { Bottom, Left, Top, Right, } public enum Origin360 { Bottom, Right, Top, Left, } [FormerlySerializedAs("m_Frame")] [SerializeField] private Sprite m_Sprite; public Sprite sprite { get { return m_Sprite; } set { if (SetPropertyUtility.SetClass(ref m_Sprite, value)) SetAllDirty(); } } [NonSerialized] private Sprite m_OverrideSprite; public Sprite overrideSprite { get { return m_OverrideSprite == null ? sprite : m_OverrideSprite; } set { if (SetPropertyUtility.SetClass(ref m_OverrideSprite, value)) SetAllDirty(); } } /// How the Image is drawn. [SerializeField] private Type m_Type = Type.Simple; public Type type { get { return m_Type; } set { if (SetPropertyUtility.SetStruct(ref m_Type, value)) SetVerticesDirty(); } } [SerializeField] private bool m_PreserveAspect = false; public bool preserveAspect { get { return m_PreserveAspect; } set { if (SetPropertyUtility.SetStruct(ref m_PreserveAspect, value)) SetVerticesDirty(); } } [SerializeField] private bool m_FillCenter = true; public bool fillCenter { get { return m_FillCenter; } set { if (SetPropertyUtility.SetStruct(ref m_FillCenter, value)) SetVerticesDirty(); } } /// Filling method for filled sprites. [SerializeField] private FillMethod m_FillMethod = FillMethod.Radial360; public FillMethod fillMethod { get { return m_FillMethod; } set { if (SetPropertyUtility.SetStruct(ref m_FillMethod, value)) {SetVerticesDirty(); m_FillOrigin = 0; } } } /// Amount of the Image shown. 0-1 range with 0 being nothing shown, and 1 being the full Image. [Range(0, 1)] [SerializeField] private float m_FillAmount = 1.0f; public float fillAmount { get { return m_FillAmount; } set { if (SetPropertyUtility.SetStruct(ref m_FillAmount, Mathf.Clamp01(value))) SetVerticesDirty(); } } /// Whether the Image should be filled clockwise (true) or counter-clockwise (false). [SerializeField] private bool m_FillClockwise = true; public bool fillClockwise { get { return m_FillClockwise; } set { if (SetPropertyUtility.SetStruct(ref m_FillClockwise, value)) SetVerticesDirty(); } } /// Controls the origin point of the Fill process. Value means different things with each fill method. [SerializeField] private int m_FillOrigin; public int fillOrigin { get { return m_FillOrigin; } set { if (SetPropertyUtility.SetStruct(ref m_FillOrigin, value)) SetVerticesDirty(); } } // Not serialized until we support read-enabled sprites better. private float m_EventAlphaThreshold = 1; public float eventAlphaThreshold { get { return m_EventAlphaThreshold; } set { m_EventAlphaThreshold = value; } } protected Image() {} /// <summary> /// Image's texture comes from the UnityEngine.Image. /// </summary> public override Texture mainTexture { get { return overrideSprite == null ? s_WhiteTexture : overrideSprite.texture; } } /// <summary> /// Whether the Image has a border to work with. /// </summary> public bool hasBorder { get { if (overrideSprite != null) { Vector4 v = overrideSprite.border; return v.sqrMagnitude > 0f; } return false; } } public float pixelsPerUnit { get { float spritePixelsPerUnit = 100; if (sprite) spritePixelsPerUnit = sprite.pixelsPerUnit; float referencePixelsPerUnit = 100; if (canvas) referencePixelsPerUnit = canvas.referencePixelsPerUnit; return spritePixelsPerUnit / referencePixelsPerUnit; } } public virtual void OnBeforeSerialize() {} public virtual void OnAfterDeserialize() { if (m_FillOrigin < 0) m_FillOrigin = 0; else if (m_FillMethod == FillMethod.Horizontal && m_FillOrigin > 1) m_FillOrigin = 0; else if (m_FillMethod == FillMethod.Vertical && m_FillOrigin > 1) m_FillOrigin = 0; else if (m_FillOrigin > 3) m_FillOrigin = 0; m_FillAmount = Mathf.Clamp(m_FillAmount, 0f, 1f); } /// Image's dimensions used for drawing. X = left, Y = bottom, Z = right, W = top. private Vector4 GetDrawingDimensions(bool shouldPreserveAspect) { var padding = overrideSprite == null ? Vector4.zero : Sprites.DataUtility.GetPadding(overrideSprite); var size = overrideSprite == null ? Vector2.zero : new Vector2(overrideSprite.rect.width, overrideSprite.rect.height); Rect r = GetPixelAdjustedRect(); // Debug.Log(string.Format("r:{2}, size:{0}, padding:{1}", size, padding, r)); int spriteW = Mathf.RoundToInt(size.x); int spriteH = Mathf.RoundToInt(size.y); var v = new Vector4( padding.x / spriteW, padding.y / spriteH, (spriteW - padding.z) / spriteW, (spriteH - padding.w) / spriteH); if (shouldPreserveAspect && size.sqrMagnitude > 0.0f) { var spriteRatio = size.x / size.y; var rectRatio = r.width / r.height; if (spriteRatio > rectRatio) { var oldHeight = r.height; r.height = r.width * (1.0f / spriteRatio); r.y += (oldHeight - r.height) * rectTransform.pivot.y; } else { var oldWidth = r.width; r.width = r.height * spriteRatio; r.x += (oldWidth - r.width) * rectTransform.pivot.x; } } v = new Vector4( r.x + r.width * v.x, r.y + r.height * v.y, r.x + r.width * v.z, r.y + r.height * v.w ); return v; } public override void SetNativeSize() { if (overrideSprite != null) { float w = overrideSprite.rect.width / pixelsPerUnit; float h = overrideSprite.rect.height / pixelsPerUnit; rectTransform.anchorMax = rectTransform.anchorMin; rectTransform.sizeDelta = new Vector2(w, h); SetAllDirty(); } } /// <summary> /// Update the UI renderer mesh. /// </summary> protected override void OnFillVBO(List<UIVertex> vbo) { if (overrideSprite == null) { base.OnFillVBO(vbo); return; } switch (type) { case Type.Simple: GenerateSimpleSprite(vbo, m_PreserveAspect); break; case Type.Sliced: GenerateSlicedSprite(vbo); break; case Type.Tiled: GenerateTiledSprite(vbo); break; case Type.Filled: GenerateFilledSprite(vbo, m_PreserveAspect); break; } } #region Various fill functions /// <summary> /// Generate vertices for a simple Image. /// </summary> void GenerateSimpleSprite(List<UIVertex> vbo, bool preserveAspect) { var vert = UIVertex.simpleVert; vert.color = color; Vector4 v = GetDrawingDimensions(preserveAspect); var uv = (overrideSprite != null) ? Sprites.DataUtility.GetOuterUV(overrideSprite) : Vector4.zero; vert.position = new Vector3(v.x, v.y); vert.uv0 = new Vector2(uv.x, uv.y); vbo.Add(vert); vert.position = new Vector3(v.x, v.w); vert.uv0 = new Vector2(uv.x, uv.w); vbo.Add(vert); vert.position = new Vector3(v.z, v.w); vert.uv0 = new Vector2(uv.z, uv.w); vbo.Add(vert); vert.position = new Vector3(v.z, v.y); vert.uv0 = new Vector2(uv.z, uv.y); vbo.Add(vert); } /// <summary> /// Generate vertices for a 9-sliced Image. /// </summary> static readonly Vector2[] s_VertScratch = new Vector2[4]; static readonly Vector2[] s_UVScratch = new Vector2[4]; void GenerateSlicedSprite(List<UIVertex> vbo) { if (!hasBorder) { GenerateSimpleSprite(vbo, false); return; } Vector4 outer, inner, padding, border; if (overrideSprite != null) { outer = Sprites.DataUtility.GetOuterUV(overrideSprite); inner = Sprites.DataUtility.GetInnerUV(overrideSprite); padding = Sprites.DataUtility.GetPadding(overrideSprite); border = overrideSprite.border; } else { outer = Vector4.zero; inner = Vector4.zero; padding = Vector4.zero; border = Vector4.zero; } Rect rect = GetPixelAdjustedRect(); border = GetAdjustedBorders(border / pixelsPerUnit, rect); padding = padding / pixelsPerUnit; s_VertScratch[0] = new Vector2(padding.x, padding.y); s_VertScratch[3] = new Vector2(rect.width - padding.z, rect.height - padding.w); s_VertScratch[1].x = border.x; s_VertScratch[1].y = border.y; s_VertScratch[2].x = rect.width - border.z; s_VertScratch[2].y = rect.height - border.w; for (int i = 0; i < 4; ++i) { s_VertScratch[i].x += rect.x; s_VertScratch[i].y += rect.y; } s_UVScratch[0] = new Vector2(outer.x, outer.y); s_UVScratch[1] = new Vector2(inner.x, inner.y); s_UVScratch[2] = new Vector2(inner.z, inner.w); s_UVScratch[3] = new Vector2(outer.z, outer.w); var uiv = UIVertex.simpleVert; uiv.color = color; for (int x = 0; x < 3; ++x) { int x2 = x + 1; for (int y = 0; y < 3; ++y) { if (!m_FillCenter && x == 1 && y == 1) { continue; } int y2 = y + 1; AddQuad(vbo, uiv, new Vector2(s_VertScratch[x].x, s_VertScratch[y].y), new Vector2(s_VertScratch[x2].x, s_VertScratch[y2].y), new Vector2(s_UVScratch[x].x, s_UVScratch[y].y), new Vector2(s_UVScratch[x2].x, s_UVScratch[y2].y)); } } } /// <summary> /// Generate vertices for a tiled Image. /// </summary> void GenerateTiledSprite(List<UIVertex> vbo) { Vector4 outer, inner, border; Vector2 spriteSize; if (overrideSprite != null) { outer = Sprites.DataUtility.GetOuterUV(overrideSprite); inner = Sprites.DataUtility.GetInnerUV(overrideSprite); border = overrideSprite.border; spriteSize = overrideSprite.rect.size; } else { outer = Vector4.zero; inner = Vector4.zero; border = Vector4.zero; spriteSize = Vector2.one * 100; } Rect rect = GetPixelAdjustedRect(); float tileWidth = (spriteSize.x - border.x - border.z) / pixelsPerUnit; float tileHeight = (spriteSize.y - border.y - border.w) / pixelsPerUnit; border = GetAdjustedBorders(border / pixelsPerUnit, rect); var uvMin = new Vector2(inner.x, inner.y); var uvMax = new Vector2(inner.z, inner.w); var v = UIVertex.simpleVert; v.color = color; // Min to max max range for tiled region in coordinates relative to lower left corner. float xMin = border.x; float xMax = rect.width - border.z; float yMin = border.y; float yMax = rect.height - border.w; // Safety check. Useful so Unity doesn't run out of memory if the sprites are too small. // Max tiles are 100 x 100. if ((xMax - xMin) > tileWidth * 100 || (yMax - yMin) > tileHeight * 100) { tileWidth = (xMax - xMin) / 100; tileHeight = (yMax - yMin) / 100; } var clipped = uvMax; if (m_FillCenter) { for (float y1 = yMin; y1 < yMax; y1 += tileHeight) { float y2 = y1 + tileHeight; if (y2 > yMax) { clipped.y = uvMin.y + (uvMax.y - uvMin.y) * (yMax - y1) / (y2 - y1); y2 = yMax; } clipped.x = uvMax.x; for (float x1 = xMin; x1 < xMax; x1 += tileWidth) { float x2 = x1 + tileWidth; if (x2 > xMax) { clipped.x = uvMin.x + (uvMax.x - uvMin.x) * (xMax - x1) / (x2 - x1); x2 = xMax; } AddQuad(vbo, v, new Vector2(x1, y1) + rect.position, new Vector2(x2, y2) + rect.position, uvMin, clipped); } } } if (!hasBorder) return; // Left and right tiled border clipped = uvMax; for (float y1 = yMin; y1 < yMax; y1 += tileHeight) { float y2 = y1 + tileHeight; if (y2 > yMax) { clipped.y = uvMin.y + (uvMax.y - uvMin.y) * (yMax - y1) / (y2 - y1); y2 = yMax; } AddQuad(vbo, v, new Vector2(0, y1) + rect.position, new Vector2(xMin, y2) + rect.position, new Vector2(outer.x, uvMin.y), new Vector2(uvMin.x, clipped.y)); AddQuad(vbo, v, new Vector2(xMax, y1) + rect.position, new Vector2(rect.width, y2) + rect.position, new Vector2(uvMax.x, uvMin.y), new Vector2(outer.z, clipped.y)); } // Bottom and top tiled border clipped = uvMax; for (float x1 = xMin; x1 < xMax; x1 += tileWidth) { float x2 = x1 + tileWidth; if (x2 > xMax) { clipped.x = uvMin.x + (uvMax.x - uvMin.x) * (xMax - x1) / (x2 - x1); x2 = xMax; } AddQuad(vbo, v, new Vector2(x1, 0) + rect.position, new Vector2(x2, yMin) + rect.position, new Vector2(uvMin.x, outer.y), new Vector2(clipped.x, uvMin.y)); AddQuad(vbo, v, new Vector2(x1, yMax) + rect.position, new Vector2(x2, rect.height) + rect.position, new Vector2(uvMin.x, uvMax.y), new Vector2(clipped.x, outer.w)); } // Corners AddQuad(vbo, v, new Vector2(0, 0) + rect.position, new Vector2(xMin, yMin) + rect.position, new Vector2(outer.x, outer.y), new Vector2(uvMin.x, uvMin.y)); AddQuad(vbo, v, new Vector2(xMax, 0) + rect.position, new Vector2(rect.width, yMin) + rect.position, new Vector2(uvMax.x, outer.y), new Vector2(outer.z, uvMin.y)); AddQuad(vbo, v, new Vector2(0, yMax) + rect.position, new Vector2(xMin, rect.height) + rect.position, new Vector2(outer.x, uvMax.y), new Vector2(uvMin.x, outer.w)); AddQuad(vbo, v, new Vector2(xMax, yMax) + rect.position, new Vector2(rect.width, rect.height) + rect.position, new Vector2(uvMax.x, uvMax.y), new Vector2(outer.z, outer.w)); } void AddQuad(List<UIVertex> vbo, UIVertex v, Vector2 posMin, Vector2 posMax, Vector2 uvMin, Vector2 uvMax) { v.position = new Vector3(posMin.x, posMin.y, 0); v.uv0 = new Vector2(uvMin.x, uvMin.y); vbo.Add(v); v.position = new Vector3(posMin.x, posMax.y, 0); v.uv0 = new Vector2(uvMin.x, uvMax.y); vbo.Add(v); v.position = new Vector3(posMax.x, posMax.y, 0); v.uv0 = new Vector2(uvMax.x, uvMax.y); vbo.Add(v); v.position = new Vector3(posMax.x, posMin.y, 0); v.uv0 = new Vector2(uvMax.x, uvMin.y); vbo.Add(v); } Vector4 GetAdjustedBorders(Vector4 border, Rect rect) { for (int axis = 0; axis <= 1; axis++) { // If the rect is smaller than the combined borders, then there's not room for the borders at their normal size. // In order to avoid artefacts with overlapping borders, we scale the borders down to fit. float combinedBorders = border[axis] + border[axis + 2]; if (rect.size[axis] < combinedBorders && combinedBorders != 0) { float borderScaleRatio = rect.size[axis] / combinedBorders; border[axis] *= borderScaleRatio; border[axis + 2] *= borderScaleRatio; } } return border; } /// <summary> /// Generate vertices for a filled Image. /// </summary> static readonly Vector2[] s_Xy = new Vector2[4]; static readonly Vector2[] s_Uv = new Vector2[4]; void GenerateFilledSprite(List<UIVertex> vbo, bool preserveAspect) { if (m_FillAmount < 0.001f) return; Vector4 v = GetDrawingDimensions(preserveAspect); Vector4 outer = overrideSprite != null ? Sprites.DataUtility.GetOuterUV(overrideSprite) : Vector4.zero; UIVertex uiv = UIVertex.simpleVert; uiv.color = color; float tx0 = outer.x; float ty0 = outer.y; float tx1 = outer.z; float ty1 = outer.w; // Horizontal and vertical filled sprites are simple -- just end the Image prematurely if (m_FillMethod == FillMethod.Horizontal || m_FillMethod == FillMethod.Vertical) { if (fillMethod == FillMethod.Horizontal) { float fill = (tx1 - tx0) * m_FillAmount; if (m_FillOrigin == 1) { v.x = v.z - (v.z - v.x) * m_FillAmount; tx0 = tx1 - fill; } else { v.z = v.x + (v.z - v.x) * m_FillAmount; tx1 = tx0 + fill; } } else if (fillMethod == FillMethod.Vertical) { float fill = (ty1 - ty0) * m_FillAmount; if (m_FillOrigin == 1) { v.y = v.w - (v.w - v.y) * m_FillAmount; ty0 = ty1 - fill; } else { v.w = v.y + (v.w - v.y) * m_FillAmount; ty1 = ty0 + fill; } } } s_Xy[0] = new Vector2(v.x, v.y); s_Xy[1] = new Vector2(v.x, v.w); s_Xy[2] = new Vector2(v.z, v.w); s_Xy[3] = new Vector2(v.z, v.y); s_Uv[0] = new Vector2(tx0, ty0); s_Uv[1] = new Vector2(tx0, ty1); s_Uv[2] = new Vector2(tx1, ty1); s_Uv[3] = new Vector2(tx1, ty0); if (m_FillAmount < 1f) { if (fillMethod == FillMethod.Radial90) { if (RadialCut(s_Xy, s_Uv, m_FillAmount, m_FillClockwise, m_FillOrigin)) { for (int i = 0; i < 4; ++i) { uiv.position = s_Xy[i]; uiv.uv0 = s_Uv[i]; vbo.Add(uiv); } } return; } if (fillMethod == FillMethod.Radial180) { for (int side = 0; side < 2; ++side) { float fx0, fx1, fy0, fy1; int even = m_FillOrigin > 1 ? 1 : 0; if (m_FillOrigin == 0 || m_FillOrigin == 2) { fy0 = 0f; fy1 = 1f; if (side == even) { fx0 = 0f; fx1 = 0.5f; } else { fx0 = 0.5f; fx1 = 1f; } } else { fx0 = 0f; fx1 = 1f; if (side == even) { fy0 = 0.5f; fy1 = 1f; } else { fy0 = 0f; fy1 = 0.5f; } } s_Xy[0].x = Mathf.Lerp(v.x, v.z, fx0); s_Xy[1].x = s_Xy[0].x; s_Xy[2].x = Mathf.Lerp(v.x, v.z, fx1); s_Xy[3].x = s_Xy[2].x; s_Xy[0].y = Mathf.Lerp(v.y, v.w, fy0); s_Xy[1].y = Mathf.Lerp(v.y, v.w, fy1); s_Xy[2].y = s_Xy[1].y; s_Xy[3].y = s_Xy[0].y; s_Uv[0].x = Mathf.Lerp(tx0, tx1, fx0); s_Uv[1].x = s_Uv[0].x; s_Uv[2].x = Mathf.Lerp(tx0, tx1, fx1); s_Uv[3].x = s_Uv[2].x; s_Uv[0].y = Mathf.Lerp(ty0, ty1, fy0); s_Uv[1].y = Mathf.Lerp(ty0, ty1, fy1); s_Uv[2].y = s_Uv[1].y; s_Uv[3].y = s_Uv[0].y; float val = m_FillClockwise ? fillAmount * 2f - side : m_FillAmount * 2f - (1 - side); if (RadialCut(s_Xy, s_Uv, Mathf.Clamp01(val), m_FillClockwise, ((side + m_FillOrigin + 3) % 4))) { for (int i = 0; i < 4; ++i) { uiv.position = s_Xy[i]; uiv.uv0 = s_Uv[i]; vbo.Add(uiv); } } } return; } if (fillMethod == FillMethod.Radial360) { for (int corner = 0; corner < 4; ++corner) { float fx0, fx1, fy0, fy1; if (corner < 2) { fx0 = 0f; fx1 = 0.5f; } else { fx0 = 0.5f; fx1 = 1f; } if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; } else { fy0 = 0.5f; fy1 = 1f; } s_Xy[0].x = Mathf.Lerp(v.x, v.z, fx0); s_Xy[1].x = s_Xy[0].x; s_Xy[2].x = Mathf.Lerp(v.x, v.z, fx1); s_Xy[3].x = s_Xy[2].x; s_Xy[0].y = Mathf.Lerp(v.y, v.w, fy0); s_Xy[1].y = Mathf.Lerp(v.y, v.w, fy1); s_Xy[2].y = s_Xy[1].y; s_Xy[3].y = s_Xy[0].y; s_Uv[0].x = Mathf.Lerp(tx0, tx1, fx0); s_Uv[1].x = s_Uv[0].x; s_Uv[2].x = Mathf.Lerp(tx0, tx1, fx1); s_Uv[3].x = s_Uv[2].x; s_Uv[0].y = Mathf.Lerp(ty0, ty1, fy0); s_Uv[1].y = Mathf.Lerp(ty0, ty1, fy1); s_Uv[2].y = s_Uv[1].y; s_Uv[3].y = s_Uv[0].y; float val = m_FillClockwise ? m_FillAmount * 4f - ((corner + m_FillOrigin) % 4) : m_FillAmount * 4f - (3 - ((corner + m_FillOrigin) % 4)); if (RadialCut(s_Xy, s_Uv, Mathf.Clamp01(val), m_FillClockwise, ((corner + 2) % 4))) { for (int i = 0; i < 4; ++i) { uiv.position = s_Xy[i]; uiv.uv0 = s_Uv[i]; vbo.Add(uiv); } } } return; } } // Fill the buffer with the quad for the Image for (int i = 0; i < 4; ++i) { uiv.position = s_Xy[i]; uiv.uv0 = s_Uv[i]; vbo.Add(uiv); } } /// <summary> /// Adjust the specified quad, making it be radially filled instead. /// </summary> static bool RadialCut(Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner) { // Nothing to fill if (fill < 0.001f) return false; // Even corners invert the fill direction if ((corner & 1) == 1) invert = !invert; // Nothing to adjust if (!invert && fill > 0.999f) return true; // Convert 0-1 value into 0 to 90 degrees angle in radians float angle = Mathf.Clamp01(fill); if (invert) angle = 1f - angle; angle *= 90f * Mathf.Deg2Rad; // Calculate the effective X and Y factors float cos = Mathf.Cos(angle); float sin = Mathf.Sin(angle); RadialCut(xy, cos, sin, invert, corner); RadialCut(uv, cos, sin, invert, corner); return true; } /// <summary> /// Adjust the specified quad, making it be radially filled instead. /// </summary> static void RadialCut(Vector2[] xy, float cos, float sin, bool invert, int corner) { int i0 = corner; int i1 = ((corner + 1) % 4); int i2 = ((corner + 2) % 4); int i3 = ((corner + 3) % 4); if ((corner & 1) == 1) { if (sin > cos) { cos /= sin; sin = 1f; if (invert) { xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos); xy[i2].x = xy[i1].x; } } else if (cos > sin) { sin /= cos; cos = 1f; if (!invert) { xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin); xy[i3].y = xy[i2].y; } } else { cos = 1f; sin = 1f; } if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos); else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin); } else { if (cos > sin) { sin /= cos; cos = 1f; if (!invert) { xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin); xy[i2].y = xy[i1].y; } } else if (sin > cos) { cos /= sin; sin = 1f; if (invert) { xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos); xy[i3].x = xy[i2].x; } } else { cos = 1f; sin = 1f; } if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin); else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos); } } #endregion public virtual void CalculateLayoutInputHorizontal() {} public virtual void CalculateLayoutInputVertical() {} public virtual float minWidth { get { return 0; } } public virtual float preferredWidth { get { if (overrideSprite == null) return 0; if (type == Type.Sliced || type == Type.Tiled) return Sprites.DataUtility.GetMinSize(overrideSprite).x / pixelsPerUnit; return overrideSprite.rect.size.x / pixelsPerUnit; } } public virtual float flexibleWidth { get { return -1; } } public virtual float minHeight { get { return 0; } } public virtual float preferredHeight { get { if (overrideSprite == null) return 0; if (type == Type.Sliced || type == Type.Tiled) return Sprites.DataUtility.GetMinSize(overrideSprite).y / pixelsPerUnit; return overrideSprite.rect.size.y / pixelsPerUnit; } } public virtual float flexibleHeight { get { return -1; } } public virtual int layoutPriority { get { return 0; } } public virtual bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera) { if (m_EventAlphaThreshold >= 1) return true; Sprite sprite = overrideSprite; if (sprite == null) return true; Vector2 local; RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPoint, eventCamera, out local); Rect rect = GetPixelAdjustedRect(); // Convert to have lower left corner as reference point. local.x += rectTransform.pivot.x * rect.width; local.y += rectTransform.pivot.y * rect.height; local = MapCoordinate(local, rect); // Normalize local coordinates. Rect spriteRect = sprite.textureRect; Vector2 normalized = new Vector2(local.x / spriteRect.width, local.y / spriteRect.height); // Convert to texture space. float x = Mathf.Lerp(spriteRect.x, spriteRect.xMax, normalized.x) / sprite.texture.width; float y = Mathf.Lerp(spriteRect.y, spriteRect.yMax, normalized.y) / sprite.texture.height; try { return sprite.texture.GetPixelBilinear(x, y).a >= m_EventAlphaThreshold; } catch (UnityException e) { Debug.LogError("Using clickAlphaThreshold lower than 1 on Image whose sprite texture cannot be read. " + e.Message + " Also make sure to disable sprite packing for this sprite.", this); return true; } } private Vector2 MapCoordinate(Vector2 local, Rect rect) { Rect spriteRect = sprite.rect; if (type == Type.Simple || type == Type.Filled) return new Vector2(local.x * spriteRect.width / rect.width, local.y * spriteRect.height / rect.height); Vector4 border = sprite.border; Vector4 adjustedBorder = GetAdjustedBorders(border / pixelsPerUnit, rect); for (int i = 0; i < 2; i++) { if (local[i] <= adjustedBorder[i]) continue; if (rect.size[i] - local[i] <= adjustedBorder[i + 2]) { local[i] -= (rect.size[i] - spriteRect.size[i]); continue; } if (type == Type.Sliced) { float lerp = Mathf.InverseLerp(adjustedBorder[i], rect.size[i] - adjustedBorder[i + 2], local[i]); local[i] = Mathf.Lerp(border[i], spriteRect.size[i] - border[i + 2], lerp); continue; } else { local[i] -= adjustedBorder[i]; local[i] = Mathf.Repeat(local[i], spriteRect.size[i] - border[i] - border[i + 2]); local[i] += border[i]; continue; } } return local; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Timeout.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft 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 RazorDBx.C5; using NUnit.Framework; using SCG = System.Collections.Generic; namespace C5UnitTests.hashtable.set { using CollectionOfInt = HashSet<int>; [TestFixture] public class GenericTesters { [Test] public void TestEvents () { Func<CollectionOfInt> factory = delegate() { return new CollectionOfInt (TenEqualityComparer.Default); }; new C5UnitTests.Templates.Events.CollectionTester<CollectionOfInt> ().Test (factory); } //[Test] //public void Extensible() //{ // C5UnitTests.Templates.Extensible.Clone.Tester<CollectionOfInt>(); // C5UnitTests.Templates.Extensible.Serialization.Tester<CollectionOfInt>(); //} } static class Factory { public static ICollection<T> New<T> () { return new HashSet<T> (); } } namespace Enumerable { [TestFixture] public class Multiops { private HashSet<int> list; private Func<int, bool> always, never, even; [SetUp] public void Init () { Debug.UseDeterministicHashing = true; list = new HashSet<int> (); always = delegate { return true; }; never = delegate { return false; }; even = delegate(int i) { return i % 2 == 0; }; } [Test] public void All () { Assert.IsTrue (list.All (always)); Assert.IsTrue (list.All (never)); Assert.IsTrue (list.All (even)); list.Add (0); Assert.IsTrue (list.All (always)); Assert.IsFalse (list.All (never)); Assert.IsTrue (list.All (even)); list.Add (5); Assert.IsTrue (list.All (always)); Assert.IsFalse (list.All (never)); Assert.IsFalse (list.All (even)); } [Test] public void Exists () { Assert.IsFalse (list.Exists (always)); Assert.IsFalse (list.Exists (never)); Assert.IsFalse (list.Exists (even)); list.Add (5); Assert.IsTrue (list.Exists (always)); Assert.IsFalse (list.Exists (never)); Assert.IsFalse (list.Exists (even)); list.Add (8); Assert.IsTrue (list.Exists (always)); Assert.IsFalse (list.Exists (never)); Assert.IsTrue (list.Exists (even)); } [Test] public void Apply () { int sum = 0; Action<int> a = delegate(int i) { sum = i + 10 * sum; }; list.Apply (a); Assert.AreEqual (0, sum); sum = 0; list.Add (5); list.Add (8); list.Add (7); list.Add (5); list.Apply (a); Assert.AreEqual (758, sum); } [TearDown] public void Dispose () { Debug.UseDeterministicHashing = false; list = null; } } [TestFixture] public class GetEnumerator { private HashSet<int> hashset; [SetUp] public void Init () { hashset = new HashSet<int> (); } [Test] public void Empty () { SCG.IEnumerator<int> e = hashset.GetEnumerator (); Assert.IsFalse (e.MoveNext ()); } [Test] public void Normal () { hashset.Add (5); hashset.Add (8); hashset.Add (5); hashset.Add (5); hashset.Add (10); hashset.Add (1); hashset.Add (16); hashset.Add (18); hashset.Add (17); hashset.Add (33); Assert.IsTrue (IC.seteq (hashset, 1, 5, 8, 10, 16, 17, 18, 33)); } [Test] public void DoDispose () { hashset.Add (5); hashset.Add (8); hashset.Add (5); SCG.IEnumerator<int> e = hashset.GetEnumerator (); e.MoveNext (); e.MoveNext (); e.Dispose (); } [Test] [ExpectedException(typeof(CollectionModifiedException))] public void MoveNextAfterUpdate () { hashset.Add (5); hashset.Add (8); hashset.Add (5); SCG.IEnumerator<int> e = hashset.GetEnumerator (); e.MoveNext (); hashset.Add (99); e.MoveNext (); } [TearDown] public void Dispose () { hashset = null; } } } namespace CollectionOrSink { [TestFixture] public class Formatting { ICollection<int> coll; IFormatProvider rad16; [SetUp] public void Init () { Debug.UseDeterministicHashing = true; coll = Factory.New<int> (); rad16 = new RadixFormatProvider (16); } [TearDown] public void Dispose () { Debug.UseDeterministicHashing = false; coll = null; rad16 = null; } [Test] public void Format () { Assert.AreEqual ("{ }", coll.ToString ()); coll.AddAll (new int[] { -4, 28, 129, 65530 }); Assert.AreEqual ("{ 65530, -4, 28, 129 }", coll.ToString ()); Assert.AreEqual ("{ FFFA, -4, 1C, 81 }", coll.ToString (null, rad16)); Assert.AreEqual ("{ 65530, -4, ... }", coll.ToString ("L14", null)); Assert.AreEqual ("{ FFFA, -4, ... }", coll.ToString ("L14", rad16)); } } [TestFixture] public class CollectionOrSink { private HashSet<int> hashset; [SetUp] public void Init () { hashset = new HashSet<int> (); } [Test] public void Choose () { hashset.Add (7); Assert.AreEqual (7, hashset.Choose ()); } [Test] [ExpectedException(typeof(NoSuchItemException))] public void BadChoose () { hashset.Choose (); } [Test] public void CountEtAl () { Assert.AreEqual (0, hashset.Count); Assert.IsTrue (hashset.IsEmpty); Assert.IsFalse (hashset.AllowsDuplicates); Assert.IsTrue (hashset.Add (0)); Assert.AreEqual (1, hashset.Count); Assert.IsFalse (hashset.IsEmpty); Assert.IsTrue (hashset.Add (5)); Assert.AreEqual (2, hashset.Count); Assert.IsFalse (hashset.Add (5)); Assert.AreEqual (2, hashset.Count); Assert.IsFalse (hashset.IsEmpty); Assert.IsTrue (hashset.Add (8)); Assert.AreEqual (3, hashset.Count); } [Test] public void AddAll () { hashset.Add (3); hashset.Add (4); hashset.Add (5); HashSet<int> hashset2 = new HashSet<int> (); hashset2.AddAll (hashset); Assert.IsTrue (IC.seteq (hashset2, 3, 4, 5)); hashset.Add (9); hashset.AddAll (hashset2); Assert.IsTrue (IC.seteq (hashset2, 3, 4, 5)); Assert.IsTrue (IC.seteq (hashset, 3, 4, 5, 9)); } [TearDown] public void Dispose () { hashset = null; } } [TestFixture] public class FindPredicate { private HashSet<int> list; Func<int, bool> pred; [SetUp] public void Init () { Debug.UseDeterministicHashing = true; list = new HashSet<int> (TenEqualityComparer.Default); pred = delegate(int i) { return i % 5 == 0; }; } [TearDown] public void Dispose () { Debug.UseDeterministicHashing = false; list = null; } [Test] public void Find () { int i; Assert.IsFalse (list.Find (pred, out i)); list.AddAll (new int[] { 4, 22, 67, 37 }); Assert.IsFalse (list.Find (pred, out i)); list.AddAll (new int[] { 45, 122, 675, 137 }); Assert.IsTrue (list.Find (pred, out i)); Assert.AreEqual (45, i); } } [TestFixture] public class UniqueItems { private HashSet<int> list; [SetUp] public void Init () { list = new HashSet<int> (); } [TearDown] public void Dispose () { list = null; } [Test] public void Test () { Assert.IsTrue (IC.seteq (list.UniqueItems ())); Assert.IsTrue (IC.seteq (list.ItemMultiplicities ())); list.AddAll (new int[] { 7, 9, 7 }); Assert.IsTrue (IC.seteq (list.UniqueItems (), 7, 9)); Assert.IsTrue (IC.seteq (list.ItemMultiplicities (), 7, 1, 9, 1)); } } [TestFixture] public class ArrayTest { private HashSet<int> hashset; int[] a; [SetUp] public void Init () { Debug.UseDeterministicHashing = true; hashset = new HashSet<int> (); a = new int[10]; for (int i = 0; i < 10; i++) a [i] = 1000 + i; } [TearDown] public void Dispose () { Debug.UseDeterministicHashing = false; hashset = null; } private string aeq (int[] a, params int[] b) { if (a.Length != b.Length) return "Lengths differ: " + a.Length + " != " + b.Length; for (int i = 0; i < a.Length; i++) if (a [i] != b [i]) return string.Format ("{0}'th elements differ: {1} != {2}", i, a [i], b [i]); return "Alles klar"; } [Test] public void ToArray () { Assert.AreEqual ("Alles klar", aeq (hashset.ToArray ())); hashset.Add (7); hashset.Add (3); hashset.Add (10); int[] r = hashset.ToArray (); Array.Sort (r); Assert.AreEqual ("Alles klar", aeq (r, 3, 7, 10)); } [Test] public void CopyTo () { //Note: for small ints the itemequalityComparer is the identity! hashset.CopyTo (a, 1); Assert.AreEqual ("Alles klar", aeq (a, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009)); hashset.Add (6); hashset.CopyTo (a, 2); Assert.AreEqual ("Alles klar", aeq (a, 1000, 1001, 6, 1003, 1004, 1005, 1006, 1007, 1008, 1009)); hashset.Add (4); hashset.Add (9); hashset.CopyTo (a, 4); //TODO: make test independent on onterequalityComparer Assert.AreEqual ("Alles klar", aeq (a, 1000, 1001, 6, 1003, 6, 9, 4, 1007, 1008, 1009)); hashset.Clear (); hashset.Add (7); hashset.CopyTo (a, 9); Assert.AreEqual ("Alles klar", aeq (a, 1000, 1001, 6, 1003, 6, 9, 4, 1007, 1008, 7)); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void CopyToBad () { hashset.CopyTo (a, 11); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void CopyToBad2 () { hashset.CopyTo (a, -1); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void CopyToTooFar () { hashset.Add (3); hashset.Add (8); hashset.CopyTo (a, 9); } } } namespace EditableCollection { [TestFixture] public class Collision { HashSet<int> hashset; [SetUp] public void Init () { hashset = new HashSet<int> (); } [Test] public void SingleCollision () { hashset.Add (7); hashset.Add (7 - 1503427877); //foreach (int cell in hashset) Console.WriteLine("A: {0}", cell); hashset.Remove (7); Assert.IsTrue (hashset.Contains (7 - 1503427877)); } [TearDown] public void Dispose () { hashset = null; } } [TestFixture] public class Searching { private HashSet<int> hashset; [SetUp] public void Init () { Debug.UseDeterministicHashing = true; hashset = new HashSet<int> (); } [Test] [ExpectedException(typeof(NullReferenceException))] public void NullEqualityComparerinConstructor1 () { new HashSet<int> (null); } [Test] [ExpectedException(typeof(NullReferenceException))] public void NullEqualityComparerinConstructor2 () { new HashSet<int> (5, null); } [Test] [ExpectedException(typeof(NullReferenceException))] public void NullEqualityComparerinConstructor3 () { new HashSet<int> (5, 0.5, null); } [Test] public void Contains () { Assert.IsFalse (hashset.Contains (5)); hashset.Add (5); Assert.IsTrue (hashset.Contains (5)); Assert.IsFalse (hashset.Contains (7)); hashset.Add (8); hashset.Add (10); Assert.IsTrue (hashset.Contains (5)); Assert.IsFalse (hashset.Contains (7)); Assert.IsTrue (hashset.Contains (8)); Assert.IsTrue (hashset.Contains (10)); hashset.Remove (8); Assert.IsTrue (hashset.Contains (5)); Assert.IsFalse (hashset.Contains (7)); Assert.IsFalse (hashset.Contains (8)); Assert.IsTrue (hashset.Contains (10)); hashset.Add (0); hashset.Add (16); hashset.Add (32); hashset.Add (48); hashset.Add (64); Assert.IsTrue (hashset.Contains (0)); Assert.IsTrue (hashset.Contains (16)); Assert.IsTrue (hashset.Contains (32)); Assert.IsTrue (hashset.Contains (48)); Assert.IsTrue (hashset.Contains (64)); Assert.IsTrue (hashset.Check ()); int i = 0, j = i; Assert.IsTrue (hashset.Find (ref i)); Assert.AreEqual (j, i); j = i = 16; Assert.IsTrue (hashset.Find (ref i)); Assert.AreEqual (j, i); j = i = 32; Assert.IsTrue (hashset.Find (ref i)); Assert.AreEqual (j, i); j = i = 48; Assert.IsTrue (hashset.Find (ref i)); Assert.AreEqual (j, i); j = i = 64; Assert.IsTrue (hashset.Find (ref i)); Assert.AreEqual (j, i); j = i = 80; Assert.IsFalse (hashset.Find (ref i)); Assert.AreEqual (j, i); } [Test] public void Many () { int j = 7373; int[] a = new int[j]; for (int i = 0; i < j; i++) { hashset.Add (3 * i + 1); a [i] = 3 * i + 1; } Assert.IsTrue (IC.seteq (hashset, a)); } [Test] public void ContainsCount () { Assert.AreEqual (0, hashset.ContainsCount (5)); hashset.Add (5); Assert.AreEqual (1, hashset.ContainsCount (5)); Assert.AreEqual (0, hashset.ContainsCount (7)); hashset.Add (8); Assert.AreEqual (1, hashset.ContainsCount (5)); Assert.AreEqual (0, hashset.ContainsCount (7)); Assert.AreEqual (1, hashset.ContainsCount (8)); hashset.Add (5); Assert.AreEqual (1, hashset.ContainsCount (5)); Assert.AreEqual (0, hashset.ContainsCount (7)); Assert.AreEqual (1, hashset.ContainsCount (8)); } [Test] public void RemoveAllCopies () { hashset.Add (5); hashset.Add (7); hashset.Add (5); Assert.AreEqual (1, hashset.ContainsCount (5)); Assert.AreEqual (1, hashset.ContainsCount (7)); hashset.RemoveAllCopies (5); Assert.AreEqual (0, hashset.ContainsCount (5)); Assert.AreEqual (1, hashset.ContainsCount (7)); hashset.Add (5); hashset.Add (8); hashset.Add (5); hashset.RemoveAllCopies (8); Assert.IsTrue (IC.eq (hashset, 7, 5)); } [Test] public void ContainsAll () { HashSet<int> list2 = new HashSet<int> (); Assert.IsTrue (hashset.ContainsAll (list2)); list2.Add (4); Assert.IsFalse (hashset.ContainsAll (list2)); hashset.Add (4); Assert.IsTrue (hashset.ContainsAll (list2)); hashset.Add (5); Assert.IsTrue (hashset.ContainsAll (list2)); list2.Add (20); Assert.IsFalse (hashset.ContainsAll (list2)); hashset.Add (20); Assert.IsTrue (hashset.ContainsAll (list2)); } [Test] public void RetainAll () { HashSet<int> list2 = new HashSet<int> (); hashset.Add (4); hashset.Add (5); hashset.Add (6); list2.Add (5); list2.Add (4); list2.Add (7); hashset.RetainAll (list2); Assert.IsTrue (IC.seteq (hashset, 4, 5)); hashset.Add (6); list2.Clear (); list2.Add (7); list2.Add (8); list2.Add (9); hashset.RetainAll (list2); Assert.IsTrue (IC.seteq (hashset)); } //Bug in RetainAll reported by Chris Fesler //The result has different bitsc [Test] public void RetainAll2 () { int LARGE_ARRAY_SIZE = 30; int LARGE_ARRAY_MID = 15; string[] _largeArrayOne = new string[LARGE_ARRAY_SIZE]; string[] _largeArrayTwo = new string[LARGE_ARRAY_SIZE]; for (int i = 0; i < LARGE_ARRAY_SIZE; i++) { _largeArrayOne [i] = "" + i; _largeArrayTwo [i] = "" + (i + LARGE_ARRAY_MID); } HashSet<string> setOne = new HashSet<string> (); setOne.AddAll (_largeArrayOne); HashSet<string> setTwo = new HashSet<string> (); setTwo.AddAll (_largeArrayTwo); setOne.RetainAll (setTwo); Assert.IsTrue (setOne.Check (), "setOne check fails"); for (int i = LARGE_ARRAY_MID; i < LARGE_ARRAY_SIZE; i++) Assert.IsTrue (setOne.Contains (_largeArrayOne [i]), "missing " + i); } [Test] public void RemoveAll () { HashSet<int> list2 = new HashSet<int> (); hashset.Add (4); hashset.Add (5); hashset.Add (6); list2.Add (5); list2.Add (7); list2.Add (4); hashset.RemoveAll (list2); Assert.IsTrue (IC.eq (hashset, 6)); hashset.Add (5); hashset.Add (4); list2.Clear (); list2.Add (6); list2.Add (5); hashset.RemoveAll (list2); Assert.IsTrue (IC.eq (hashset, 4)); list2.Clear (); list2.Add (7); list2.Add (8); list2.Add (9); hashset.RemoveAll (list2); Assert.IsTrue (IC.eq (hashset, 4)); } [Test] public void Remove () { hashset.Add (4); hashset.Add (4); hashset.Add (5); hashset.Add (4); hashset.Add (6); Assert.IsFalse (hashset.Remove (2)); Assert.IsTrue (hashset.Remove (4)); Assert.IsTrue (IC.seteq (hashset, 5, 6)); hashset.Add (7); hashset.Add (21); hashset.Add (37); hashset.Add (53); hashset.Add (69); hashset.Add (85); Assert.IsTrue (hashset.Remove (5)); Assert.IsTrue (IC.seteq (hashset, 6, 7, 21, 37, 53, 69, 85)); Assert.IsFalse (hashset.Remove (165)); Assert.IsTrue (IC.seteq (hashset, 6, 7, 21, 37, 53, 69, 85)); Assert.IsTrue (hashset.Remove (53)); Assert.IsTrue (IC.seteq (hashset, 6, 7, 21, 37, 69, 85)); Assert.IsTrue (hashset.Remove (37)); Assert.IsTrue (IC.seteq (hashset, 6, 7, 21, 69, 85)); Assert.IsTrue (hashset.Remove (85)); Assert.IsTrue (IC.seteq (hashset, 6, 7, 21, 69)); } [Test] public void Clear () { hashset.Add (7); hashset.Add (7); hashset.Clear (); Assert.IsTrue (hashset.IsEmpty); } [TearDown] public void Dispose () { Debug.UseDeterministicHashing = false; hashset = null; } } [TestFixture] public class Combined { private ICollection<KeyValuePair<int, int>> lst; [SetUp] public void Init () { lst = new HashSet<KeyValuePair<int, int>> (new KeyValuePairEqualityComparer<int, int> ()); for (int i = 0; i < 10; i++) lst.Add (new KeyValuePair<int, int> (i, i + 30)); } [TearDown] public void Dispose () { lst = null; } [Test] public void Find () { KeyValuePair<int, int> p = new KeyValuePair<int, int> (3, 78); Assert.IsTrue (lst.Find (ref p)); Assert.AreEqual (3, p.Key); Assert.AreEqual (33, p.Value); p = new KeyValuePair<int, int> (13, 78); Assert.IsFalse (lst.Find (ref p)); } [Test] public void FindOrAdd () { KeyValuePair<int, int> p = new KeyValuePair<int, int> (3, 78); KeyValuePair<int, int> q = new KeyValuePair<int, int> (); Assert.IsTrue (lst.FindOrAdd (ref p)); Assert.AreEqual (3, p.Key); Assert.AreEqual (33, p.Value); p = new KeyValuePair<int, int> (13, 79); Assert.IsFalse (lst.FindOrAdd (ref p)); q.Key = 13; Assert.IsTrue (lst.Find (ref q)); Assert.AreEqual (13, q.Key); Assert.AreEqual (79, q.Value); } [Test] public void Update () { KeyValuePair<int, int> p = new KeyValuePair<int, int> (3, 78); KeyValuePair<int, int> q = new KeyValuePair<int, int> (); Assert.IsTrue (lst.Update (p)); q.Key = 3; Assert.IsTrue (lst.Find (ref q)); Assert.AreEqual (3, q.Key); Assert.AreEqual (78, q.Value); p = new KeyValuePair<int, int> (13, 78); Assert.IsFalse (lst.Update (p)); } [Test] public void UpdateOrAdd1 () { KeyValuePair<int, int> p = new KeyValuePair<int, int> (3, 78); KeyValuePair<int, int> q = new KeyValuePair<int, int> (); Assert.IsTrue (lst.UpdateOrAdd (p)); q.Key = 3; Assert.IsTrue (lst.Find (ref q)); Assert.AreEqual (3, q.Key); Assert.AreEqual (78, q.Value); p = new KeyValuePair<int, int> (13, 79); Assert.IsFalse (lst.UpdateOrAdd (p)); q.Key = 13; Assert.IsTrue (lst.Find (ref q)); Assert.AreEqual (13, q.Key); Assert.AreEqual (79, q.Value); } [Test] public void UpdateOrAdd2 () { ICollection<String> coll = new HashSet<String> (); // s1 and s2 are distinct objects but contain the same text: String old, s1 = "abc", s2 = ("def" + s1).Substring (3); Assert.IsFalse (coll.UpdateOrAdd (s1, out old)); Assert.AreEqual (null, old); Assert.IsTrue (coll.UpdateOrAdd (s2, out old)); Assert.IsTrue (Object.ReferenceEquals (s1, old)); Assert.IsFalse (Object.ReferenceEquals (s2, old)); } [Test] public void RemoveWithReturn () { KeyValuePair<int, int> p = new KeyValuePair<int, int> (3, 78); //KeyValuePair<int,int> q = new KeyValuePair<int,int>(); Assert.IsTrue (lst.Remove (p, out p)); Assert.AreEqual (3, p.Key); Assert.AreEqual (33, p.Value); p = new KeyValuePair<int, int> (13, 78); Assert.IsFalse (lst.Remove (p, out p)); } } } namespace HashingAndEquals { [TestFixture] public class IEditableCollection { private ICollection<int> dit, dat, dut; [SetUp] public void Init () { dit = new HashSet<int> (); dat = new HashSet<int> (); dut = new HashSet<int> (); } [Test] public void EmptyEmpty () { Assert.IsTrue (dit.UnsequencedEquals (dat)); } [Test] public void EmptyNonEmpty () { dit.Add (3); Assert.IsFalse (dit.UnsequencedEquals (dat)); Assert.IsFalse (dat.UnsequencedEquals (dit)); } [Test] public void HashVal () { Assert.AreEqual (CHC.unsequencedhashcode (), dit.GetUnsequencedHashCode ()); dit.Add (3); Assert.AreEqual (CHC.unsequencedhashcode (3), dit.GetUnsequencedHashCode ()); dit.Add (7); Assert.AreEqual (CHC.unsequencedhashcode (3, 7), dit.GetUnsequencedHashCode ()); Assert.AreEqual (CHC.unsequencedhashcode (), dut.GetUnsequencedHashCode ()); dut.Add (3); Assert.AreEqual (CHC.unsequencedhashcode (3), dut.GetUnsequencedHashCode ()); dut.Add (7); Assert.AreEqual (CHC.unsequencedhashcode (7, 3), dut.GetUnsequencedHashCode ()); } [Test] public void EqualHashButDifferent () { dit.Add (-1657792980); dit.Add (-1570288808); dat.Add (1862883298); dat.Add (-272461342); Assert.AreEqual (dit.GetUnsequencedHashCode (), dat.GetUnsequencedHashCode ()); Assert.IsFalse (dit.UnsequencedEquals (dat)); } [Test] public void Normal () { dit.Add (3); dit.Add (7); dat.Add (3); Assert.IsFalse (dit.UnsequencedEquals (dat)); Assert.IsFalse (dat.UnsequencedEquals (dit)); dat.Add (7); Assert.IsTrue (dit.UnsequencedEquals (dat)); Assert.IsTrue (dat.UnsequencedEquals (dit)); } [Test] public void WrongOrder () { dit.Add (3); dut.Add (3); Assert.IsTrue (dit.UnsequencedEquals (dut)); Assert.IsTrue (dut.UnsequencedEquals (dit)); dit.Add (7); dut.Add (7); Assert.IsTrue (dit.UnsequencedEquals (dut)); Assert.IsTrue (dut.UnsequencedEquals (dit)); } [Test] public void Reflexive () { Assert.IsTrue (dit.UnsequencedEquals (dit)); dit.Add (3); Assert.IsTrue (dit.UnsequencedEquals (dit)); dit.Add (7); Assert.IsTrue (dit.UnsequencedEquals (dit)); } [TearDown] public void Dispose () { dit = null; dat = null; dut = null; } } [TestFixture] public class MultiLevelUnorderedOfUnOrdered { private ICollection<int> dit, dat, dut; private ICollection<ICollection<int>> Dit, Dat, Dut; [SetUp] public void Init () { dit = new HashSet<int> (); dat = new HashSet<int> (); dut = new HashSet<int> (); dit.Add (2); dit.Add (1); dat.Add (1); dat.Add (2); dut.Add (3); Dit = new HashSet<ICollection<int>> (); Dat = new HashSet<ICollection<int>> (); Dut = new HashSet<ICollection<int>> (); } [Test] public void Check () { Assert.IsTrue (dit.UnsequencedEquals (dat)); Assert.IsFalse (dit.UnsequencedEquals (dut)); } [Test] public void Multi () { Dit.Add (dit); Dit.Add (dut); Dit.Add (dit); Dat.Add (dut); Dat.Add (dit); Dat.Add (dat); Assert.IsTrue (Dit.UnsequencedEquals (Dat)); Assert.IsFalse (Dit.UnsequencedEquals (Dut)); } [TearDown] public void Dispose () { dit = dat = dut = null; Dit = Dat = Dut = null; } } [TestFixture] public class MultiLevelOrderedOfUnOrdered { private ICollection<int> dit, dat, dut; private ISequenced<ICollection<int>> Dit, Dat, Dut; [SetUp] public void Init () { dit = new HashSet<int> (); dat = new HashSet<int> (); dut = new HashSet<int> (); dit.Add (2); dit.Add (1); dat.Add (1); dat.Add (2); dut.Add (3); Dit = new LinkedList<ICollection<int>> (); Dat = new LinkedList<ICollection<int>> (); Dut = new LinkedList<ICollection<int>> (); } [Test] public void Check () { Assert.IsTrue (dit.UnsequencedEquals (dat)); Assert.IsFalse (dit.UnsequencedEquals (dut)); } [Test] public void Multi () { Dit.Add (dit); Dit.Add (dut); Dit.Add (dit); Dat.Add (dut); Dat.Add (dit); Dat.Add (dat); Dut.Add (dit); Dut.Add (dut); Dut.Add (dat); Assert.IsFalse (Dit.SequencedEquals (Dat)); Assert.IsTrue (Dit.SequencedEquals (Dut)); } [TearDown] public void Dispose () { dit = dat = dut = null; Dit = Dat = Dut = null; } } [TestFixture] public class MultiLevelUnOrderedOfOrdered { private ISequenced<int> dit, dat, dut, dot; private ICollection<ISequenced<int>> Dit, Dat, Dut, Dot; [SetUp] public void Init () { dit = new LinkedList<int> (); dat = new LinkedList<int> (); dut = new LinkedList<int> (); dot = new LinkedList<int> (); dit.Add (2); dit.Add (1); dat.Add (1); dat.Add (2); dut.Add (3); dot.Add (2); dot.Add (1); Dit = new HashSet<ISequenced<int>> (); Dat = new HashSet<ISequenced<int>> (); Dut = new HashSet<ISequenced<int>> (); Dot = new HashSet<ISequenced<int>> (); } [Test] public void Check () { Assert.IsFalse (dit.SequencedEquals (dat)); Assert.IsTrue (dit.SequencedEquals (dot)); Assert.IsFalse (dit.SequencedEquals (dut)); } [Test] public void Multi () { Dit.Add (dit); Dit.Add (dut);//Dit.Add(dit); Dat.Add (dut); Dat.Add (dit); Dat.Add (dat); Dut.Add (dot); Dut.Add (dut);//Dut.Add(dit); Dot.Add (dit); Dot.Add (dit); Dot.Add (dut); Assert.IsTrue (Dit.UnsequencedEquals (Dit)); Assert.IsTrue (Dit.UnsequencedEquals (Dut)); Assert.IsFalse (Dit.UnsequencedEquals (Dat)); Assert.IsTrue (Dit.UnsequencedEquals (Dot)); } [TearDown] public void Dispose () { dit = dat = dut = dot = null; Dit = Dat = Dut = Dot = null; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for VirtualMachineImagesOperations. /// </summary> public static partial class VirtualMachineImagesOperationsExtensions { /// <summary> /// Gets a virtual machine image. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='version'> /// </param> public static VirtualMachineImage Get(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, string version) { return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).GetAsync(location, publisherName, offer, skus, version), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a virtual machine image. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='version'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualMachineImage> GetAsync(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, string version, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(location, publisherName, offer, skus, version, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of virtual machine images. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IList<VirtualMachineImageResource> List(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, ODataQuery<VirtualMachineImageResource> odataQuery = default(ODataQuery<VirtualMachineImageResource>)) { return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListAsync(location, publisherName, offer, skus, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of virtual machine images. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<VirtualMachineImageResource>> ListAsync(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, ODataQuery<VirtualMachineImageResource> odataQuery = default(ODataQuery<VirtualMachineImageResource>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(location, publisherName, offer, skus, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of virtual machine image offers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> public static IList<VirtualMachineImageResource> ListOffers(this IVirtualMachineImagesOperations operations, string location, string publisherName) { return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListOffersAsync(location, publisherName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of virtual machine image offers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<VirtualMachineImageResource>> ListOffersAsync(this IVirtualMachineImagesOperations operations, string location, string publisherName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListOffersWithHttpMessagesAsync(location, publisherName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of virtual machine image publishers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> public static IList<VirtualMachineImageResource> ListPublishers(this IVirtualMachineImagesOperations operations, string location) { return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListPublishersAsync(location), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of virtual machine image publishers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<VirtualMachineImageResource>> ListPublishersAsync(this IVirtualMachineImagesOperations operations, string location, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListPublishersWithHttpMessagesAsync(location, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of virtual machine image skus. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> public static IList<VirtualMachineImageResource> ListSkus(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer) { return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListSkusAsync(location, publisherName, offer), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of virtual machine image skus. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<VirtualMachineImageResource>> ListSkusAsync(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListSkusWithHttpMessagesAsync(location, publisherName, offer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Data; /////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend.// /////////////////////////////////////////////////////////// // This file contains static implementations of the CandidateMetaDataLogic // Add your own static methods by making a new partial class. // You cannot override static methods, instead override the methods // located in CandidateMetaDataLogicBase by making a partial class of CandidateMetaDataLogic // and overriding the base methods. namespace VotingInfo.Database.Logic.Data { public partial class CandidateMetaDataLogic { //Put your code in a separate file. This is auto generated. /// <summary> /// Run CandidateMetaData_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> public static int? InsertNow(int fldContentInspectionId , int fldCandidateId , int fldMetaDataId , string fldMetaDataValue ) { return (new CandidateMetaDataLogic()).Insert(fldContentInspectionId , fldCandidateId , fldMetaDataId , fldMetaDataValue ); } /// <summary> /// Run CandidateMetaData_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> public static int? InsertNow(int fldContentInspectionId , int fldCandidateId , int fldMetaDataId , string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).Insert(fldContentInspectionId , fldCandidateId , fldMetaDataId , fldMetaDataValue , connection, transaction); } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(CandidateMetaDataContract row) { return (new CandidateMetaDataLogic()).Insert(row); } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(CandidateMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).Insert(row, connection, transaction); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<CandidateMetaDataContract> rows) { return (new CandidateMetaDataLogic()).InsertAll(rows); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<CandidateMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).InsertAll(rows, connection, transaction); } /// <summary> /// Run CandidateMetaData_Update. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldCandidateMetaDataId , int fldContentInspectionId , int fldCandidateId , int fldMetaDataId , string fldMetaDataValue ) { return (new CandidateMetaDataLogic()).Update(fldCandidateMetaDataId , fldContentInspectionId , fldCandidateId , fldMetaDataId , fldMetaDataValue ); } /// <summary> /// Run CandidateMetaData_Update. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldCandidateMetaDataId , int fldContentInspectionId , int fldCandidateId , int fldMetaDataId , string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).Update(fldCandidateMetaDataId , fldContentInspectionId , fldCandidateId , fldMetaDataId , fldMetaDataValue , connection, transaction); } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(CandidateMetaDataContract row) { return (new CandidateMetaDataLogic()).Update(row); } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(CandidateMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).Update(row, connection, transaction); } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<CandidateMetaDataContract> rows) { return (new CandidateMetaDataLogic()).UpdateAll(rows); } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<CandidateMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).UpdateAll(rows, connection, transaction); } /// <summary> /// Run CandidateMetaData_Delete. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldCandidateMetaDataId ) { return (new CandidateMetaDataLogic()).Delete(fldCandidateMetaDataId ); } /// <summary> /// Run CandidateMetaData_Delete. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldCandidateMetaDataId , SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).Delete(fldCandidateMetaDataId , connection, transaction); } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(CandidateMetaDataContract row) { return (new CandidateMetaDataLogic()).Delete(row); } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(CandidateMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).Delete(row, connection, transaction); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<CandidateMetaDataContract> rows) { return (new CandidateMetaDataLogic()).DeleteAll(rows); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<CandidateMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).DeleteAll(rows, connection, transaction); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldCandidateMetaDataId ) { return (new CandidateMetaDataLogic()).Exists(fldCandidateMetaDataId ); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldCandidateMetaDataId , SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).Exists(fldCandidateMetaDataId , connection, transaction); } /// <summary> /// Run CandidateMetaData_Search, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SearchNow(string fldMetaDataValue ) { var driver = new CandidateMetaDataLogic(); driver.Search(fldMetaDataValue ); return driver.Results; } /// <summary> /// Run CandidateMetaData_Search, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SearchNow(string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateMetaDataLogic(); driver.Search(fldMetaDataValue , connection, transaction); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectAll, and return results as a list of CandidateMetaDataRow. /// </summary> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectAllNow() { var driver = new CandidateMetaDataLogic(); driver.SelectAll(); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectAll, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateMetaDataLogic(); driver.SelectAll(connection, transaction); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectBy_CandidateMetaDataId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectBy_CandidateMetaDataIdNow(int fldCandidateMetaDataId ) { var driver = new CandidateMetaDataLogic(); driver.SelectBy_CandidateMetaDataId(fldCandidateMetaDataId ); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectBy_CandidateMetaDataId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectBy_CandidateMetaDataIdNow(int fldCandidateMetaDataId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateMetaDataLogic(); driver.SelectBy_CandidateMetaDataId(fldCandidateMetaDataId , connection, transaction); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectBy_ContentInspectionId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId ) { var driver = new CandidateMetaDataLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId ); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectBy_ContentInspectionId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateMetaDataLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId , connection, transaction); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectBy_CandidateId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectBy_CandidateIdNow(int fldCandidateId ) { var driver = new CandidateMetaDataLogic(); driver.SelectBy_CandidateId(fldCandidateId ); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectBy_CandidateId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectBy_CandidateIdNow(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateMetaDataLogic(); driver.SelectBy_CandidateId(fldCandidateId , connection, transaction); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectBy_MetaDataId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectBy_MetaDataIdNow(int fldMetaDataId ) { var driver = new CandidateMetaDataLogic(); driver.SelectBy_MetaDataId(fldMetaDataId ); return driver.Results; } /// <summary> /// Run CandidateMetaData_SelectBy_MetaDataId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public static List<CandidateMetaDataContract> SelectBy_MetaDataIdNow(int fldMetaDataId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateMetaDataLogic(); driver.SelectBy_MetaDataId(fldMetaDataId , connection, transaction); return driver.Results; } /// <summary> /// Read all CandidateMetaData rows from the provided reader into the list structure of CandidateMetaDataRows /// </summary> /// <param name="reader">The result of running a sql command.</param> /// <returns>A populated CandidateMetaDataRows or an empty CandidateMetaDataRows if there are no results.</returns> public static List<CandidateMetaDataContract> ReadAllNow(SqlDataReader reader) { var driver = new CandidateMetaDataLogic(); driver.ReadAll(reader); return driver.Results; } /// <summary>"); /// Advance one, and read values into a CandidateMetaData /// </summary> /// <param name="reader">The result of running a sql command.</param>"); /// <returns>A CandidateMetaData or null if there are no results.</returns> public static CandidateMetaDataContract ReadOneNow(SqlDataReader reader) { var driver = new CandidateMetaDataLogic(); return driver.ReadOne(reader) ? driver.Results[0] : null; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(CandidateMetaDataContract row) { if(row.CandidateMetaDataId == null) { return InsertNow(row); } else { return UpdateNow(row); } } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(CandidateMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { if(row.CandidateMetaDataId == null) { return InsertNow(row, connection, transaction); } else { return UpdateNow(row, connection, transaction); } } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<CandidateMetaDataContract> rows) { return (new CandidateMetaDataLogic()).SaveAll(rows); } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<CandidateMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new CandidateMetaDataLogic()).SaveAll(rows, connection, transaction); } } }
//------------------------------------------------------------------------------ // <copyright file="DbConnectionHelper.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace NAMESPACE { using System; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Globalization; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Threading; using SysTx = System.Transactions; using System.Diagnostics.CodeAnalysis; public sealed partial class CONNECTIONOBJECTNAME : DbConnection { private static readonly DbConnectionFactory _connectionFactory = CONNECTIONFACTORYOBJECTNAME; internal static readonly System.Security.CodeAccessPermission ExecutePermission = CONNECTIONOBJECTNAME.CreateExecutePermission(); private DbConnectionOptions _userConnectionOptions; private DbConnectionPoolGroup _poolGroup; private DbConnectionInternal _innerConnection; private int _closeCount; // used to distinguish between different uses of this object, so we don't have to maintain a list of it's children private static int _objectTypeCount; // Bid counter internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref _objectTypeCount); public CONNECTIONOBJECTNAME() : base() { GC.SuppressFinalize(this); _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance; } // Copy Constructor private void CopyFrom(CONNECTIONOBJECTNAME connection) { // V1.2.3300 ADP.CheckArgumentNull(connection, "connection"); _userConnectionOptions = connection.UserConnectionOptions; _poolGroup = connection.PoolGroup; // SQLBU 432115 // Match the original connection's behavior for whether the connection was never opened, // but ensure Clone is in the closed state. if (DbConnectionClosedNeverOpened.SingletonInstance == connection._innerConnection) { _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance; } else { _innerConnection = DbConnectionClosedPreviouslyOpened.SingletonInstance; } } /// <devdoc>We use the _closeCount to avoid having to know about all our /// children; instead of keeping a collection of all the objects that /// would be affected by a close, we simply increment the _closeCount /// and have each of our children check to see if they're "orphaned" /// </devdoc> internal int CloseCount { get { return _closeCount; } } internal DbConnectionFactory ConnectionFactory { get { return _connectionFactory; } } internal DbConnectionOptions ConnectionOptions { get { System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; return ((null != poolGroup) ? poolGroup.ConnectionOptions : null); } } private string ConnectionString_Get() { Bid.Trace( "<prov.DbConnectionHelper.ConnectionString_Get|API> %d#\n", ObjectID); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); } private void ConnectionString_Set(string value) { DbConnectionPoolKey key = new DbConnectionPoolKey(value); ConnectionString_Set(key); } private void ConnectionString_Set(DbConnectionPoolKey key) { DbConnectionOptions connectionOptions = null; System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions); DbConnectionInternal connectionInternal = InnerConnection; bool flag = connectionInternal.AllowSetConnectionString; if (flag) { //try { // NOTE: There's a race condition with multiple threads changing // ConnectionString and any thread throws an exception // Closed->Busy: prevent Open during set_ConnectionString flag = SetInnerConnectionFrom(DbConnectionClosedBusy.SingletonInstance, connectionInternal); if (flag) { _userConnectionOptions = connectionOptions; _poolGroup = poolGroup; _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance; } //} //catch { // // recover from exceptions to avoid sticking in busy state // SetInnerConnectionFrom(connectionInternal, DbConnectionClosedBusy.SingletonInstance); // throw; //} } if (!flag) { throw ADP.OpenConnectionPropertySet(ADP.ConnectionString, connectionInternal.State); } if (Bid.TraceOn) { string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); Bid.Trace("<prov.DbConnectionHelper.ConnectionString_Set|API> %d#, '%ls'\n", ObjectID, cstr); } } internal DbConnectionInternal InnerConnection { get { return _innerConnection; } } internal System.Data.ProviderBase.DbConnectionPoolGroup PoolGroup { get { return _poolGroup; } set { // when a poolgroup expires and the connection eventually activates, the pool entry will be replaced Debug.Assert(null != value, "null poolGroup"); _poolGroup = value; } } internal DbConnectionOptions UserConnectionOptions { get { return _userConnectionOptions; } } // Open->ClosedPreviouslyOpened, and doom the internal connection too... [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal void Abort(Exception e) { DbConnectionInternal innerConnection = _innerConnection; // Should not cause memory allocation... if (ConnectionState.Open == innerConnection.State) { Interlocked.CompareExchange(ref _innerConnection, DbConnectionClosedPreviouslyOpened.SingletonInstance, innerConnection); innerConnection.DoomThisConnection(); } // NOTE: we put the tracing last, because the ToString() calls (and // the Bid.Trace, for that matter) have no reliability contract and // will end the reliable try... if (e is OutOfMemoryException) { Bid.Trace("<prov.DbConnectionHelper.Abort|RES|INFO|CPOOL> %d#, Aborting operation due to asynchronous exception: %ls\n", ObjectID, "OutOfMemory"); } else { Bid.Trace("<prov.DbConnectionHelper.Abort|RES|INFO|CPOOL> %d#, Aborting operation due to asynchronous exception: %ls\n", ObjectID, e.ToString()); } } internal void AddWeakReference(object value, int tag) { InnerConnection.AddWeakReference(value, tag); } override protected DbCommand CreateDbCommand() { DbCommand command = null; IntPtr hscp; Bid.ScopeEnter(out hscp, "<prov.DbConnectionHelper.CreateDbCommand|API> %d#\n", ObjectID); try { DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; command = providerFactory.CreateCommand(); command.Connection = this; } finally { Bid.ScopeLeave(ref hscp); } return command; } private static System.Security.CodeAccessPermission CreateExecutePermission() { DBDataPermission p = (DBDataPermission)CONNECTIONFACTORYOBJECTNAME.ProviderFactory.CreatePermission(System.Security.Permissions.PermissionState.None); p.Add(String.Empty, String.Empty, KeyRestrictionBehavior.AllowOnly); return p; } override protected void Dispose(bool disposing) { if (disposing) { _userConnectionOptions = null; _poolGroup= null; Close(); } DisposeMe(disposing); base.Dispose(disposing); // notify base classes } partial void RepairInnerConnection(); // NOTE: This is just a private helper because OracleClient V1.1 shipped // with a different argument name and it's a breaking change to not use // the same argument names in V2.0 (VB Named Parameter Binding--Ick) private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITransaction transaction) { System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None); permissionSet.AddPermission(CONNECTIONOBJECTNAME.ExecutePermission); // MDAC 81476 permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)); permissionSet.Demand(); Bid.Trace( "<prov.DbConnectionHelper.EnlistDistributedTransactionHelper|RES|TRAN> %d#, Connection enlisting in a transaction.\n", ObjectID); SysTx.Transaction indigoTransaction = null; if (null != transaction) { indigoTransaction = SysTx.TransactionInterop.GetTransactionFromDtcTransaction((SysTx.IDtcTransaction)transaction); } RepairInnerConnection(); // NOTE: since transaction enlistment involves round trips to the // server, we don't want to lock here, we'll handle the race conditions // elsewhere. InnerConnection.EnlistTransaction(indigoTransaction); // NOTE: If this outer connection were to be GC'd while we're // enlisting, the pooler would attempt to reclaim the inner connection // while we're attempting to enlist; not sure how likely that is but // we should consider a GC.KeepAlive(this) here. GC.KeepAlive(this); } override public void EnlistTransaction(SysTx.Transaction transaction) { CONNECTIONOBJECTNAME.ExecutePermission.Demand(); Bid.Trace( "<prov.DbConnectionHelper.EnlistTransaction|RES|TRAN> %d#, Connection enlisting in a transaction.\n", ObjectID); // If we're currently enlisted in a transaction and we were called // on the EnlistTransaction method (Whidbey) we're not allowed to // enlist in a different transaction. DbConnectionInternal innerConnection = InnerConnection; // NOTE: since transaction enlistment involves round trips to the // server, we don't want to lock here, we'll handle the race conditions // elsewhere. SysTx.Transaction enlistedTransaction = innerConnection.EnlistedTransaction; if (enlistedTransaction != null) { // Allow calling enlist if already enlisted (no-op) if (enlistedTransaction.Equals(transaction)) { return; } // Allow enlisting in a different transaction if the enlisted transaction has completed. if (enlistedTransaction.TransactionInformation.Status == SysTx.TransactionStatus.Active) { throw ADP.TransactionPresent(); } } RepairInnerConnection(); InnerConnection.EnlistTransaction(transaction); // NOTE: If this outer connection were to be GC'd while we're // enlisting, the pooler would attempt to reclaim the inner connection // while we're attempting to enlist; not sure how likely that is but // we should consider a GC.KeepAlive(this) here. GC.KeepAlive(this); } private DbMetaDataFactory GetMetaDataFactory(DbConnectionInternal internalConnection) { return ConnectionFactory.GetMetaDataFactory(_poolGroup, internalConnection); } internal DbMetaDataFactory GetMetaDataFactoryInternal(DbConnectionInternal internalConnection) { return GetMetaDataFactory(internalConnection); } override public DataTable GetSchema() { return this.GetSchema(DbMetaDataCollectionNames.MetaDataCollections, null); } override public DataTable GetSchema(string collectionName) { return this.GetSchema(collectionName, null); } override public DataTable GetSchema(string collectionName, string[] restrictionValues) { // NOTE: This is virtual because not all providers may choose to support // returning schema data CONNECTIONOBJECTNAME.ExecutePermission.Demand(); return InnerConnection.GetSchema(ConnectionFactory, PoolGroup, this, collectionName, restrictionValues); } internal void NotifyWeakReference(int message) { InnerConnection.NotifyWeakReference(message); } internal void PermissionDemand() { Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting"); System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); if ((null == connectionOptions) || connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } DbConnectionOptions userConnectionOptions = UserConnectionOptions; Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions"); userConnectionOptions.DemandPermission(); } internal void RemoveWeakReference(object value) { InnerConnection.RemoveWeakReference(value); } // OpenBusy->Closed (previously opened) // Connecting->Open internal void SetInnerConnectionEvent(DbConnectionInternal to) { // Set's the internal connection without verifying that it's a specific value Debug.Assert(null != _innerConnection, "null InnerConnection"); Debug.Assert(null != to, "to null InnerConnection"); ConnectionState originalState = _innerConnection.State & ConnectionState.Open; ConnectionState currentState = to.State & ConnectionState.Open; if ((originalState != currentState) && (ConnectionState.Closed == currentState)) { // Increment the close count whenever we switch to Closed unchecked { _closeCount++; } } _innerConnection = to; if (ConnectionState.Closed == originalState && ConnectionState.Open == currentState) { OnStateChange(DbConnectionInternal.StateChangeOpen); } else if (ConnectionState.Open == originalState && ConnectionState.Closed == currentState) { OnStateChange(DbConnectionInternal.StateChangeClosed); } else { Debug.Assert(false, "unexpected state switch"); if (originalState != currentState) { OnStateChange(new StateChangeEventArgs(originalState, currentState)); } } } // this method is used to securely change state with the resource being // the open connection protected by the connectionstring via a permission demand // Closed->Connecting: prevent set_ConnectionString during Open // Open->OpenBusy: guarantee internal connection is returned to correct pool // Closed->ClosedBusy: prevent Open during set_ConnectionString internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from) { // Set's the internal connection, verifying that it's a specific value before doing so. Debug.Assert(null != _innerConnection, "null InnerConnection"); Debug.Assert(null != from, "from null InnerConnection"); Debug.Assert(null != to, "to null InnerConnection"); bool result = (from == Interlocked.CompareExchange<DbConnectionInternal>(ref _innerConnection, to, from)); return result; } // ClosedBusy->Closed (never opened) // Connecting->Closed (exception during open, return to previous closed state) internal void SetInnerConnectionTo(DbConnectionInternal to) { // Set's the internal connection without verifying that it's a specific value Debug.Assert(null != _innerConnection, "null InnerConnection"); Debug.Assert(null != to, "to null InnerConnection"); _innerConnection = to; } [ConditionalAttribute("DEBUG")] internal static void VerifyExecutePermission() { try { // use this to help validate this code path is only used after the following permission has been previously demanded in the current codepath CONNECTIONOBJECTNAME.ExecutePermission.Demand(); } catch(System.Security.SecurityException) { System.Diagnostics.Debug.Assert(false, "unexpected SecurityException for current codepath"); throw; } } } }
// 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 Xunit; namespace System.Linq.Tests { public class GroupByTests { public static void AssertGroupingCorrect<TKey, TElement>(IEnumerable<TKey> keys, IEnumerable<TElement> elements, IEnumerable<IGrouping<TKey, TElement>> grouping) { AssertGroupingCorrect<TKey, TElement>(keys, elements, grouping, EqualityComparer<TKey>.Default); } public static void AssertGroupingCorrect<TKey, TElement>(IEnumerable<TKey> keys, IEnumerable<TElement> elements, IEnumerable<IGrouping<TKey, TElement>> grouping, IEqualityComparer<TKey> keyComparer) { if (grouping == null) { Assert.Null(elements); Assert.Null(keys); return; } Assert.NotNull(elements); Assert.NotNull(keys); Dictionary<TKey, List<TElement>> dict = new Dictionary<TKey, List<TElement>>(keyComparer); List<TElement> groupingForNullKeys = new List<TElement>(); using (IEnumerator<TElement> elEn = elements.GetEnumerator()) using (IEnumerator<TKey> keyEn = keys.GetEnumerator()) { while (keyEn.MoveNext()) { Assert.True(elEn.MoveNext()); TKey key = keyEn.Current; if (key == null) { groupingForNullKeys.Add(elEn.Current); } else { List<TElement> list; if (!dict.TryGetValue(key, out list)) dict.Add(key, list = new List<TElement>()); list.Add(elEn.Current); } } Assert.False(elEn.MoveNext()); } foreach (IGrouping<TKey, TElement> group in grouping) { Assert.NotEmpty(group); TKey key = group.Key; List<TElement> list; if (key == null) { Assert.Equal(groupingForNullKeys, group); groupingForNullKeys.Clear(); } else { Assert.True(dict.TryGetValue(key, out list)); Assert.Equal(list, group); dict.Remove(key); } } Assert.Empty(dict); Assert.Empty(groupingForNullKeys); } private class AnagramEqualityComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { if (ReferenceEquals(x, y)) return true; if (x == null | y == null) return false; int length = x.Length; if (length != y.Length) return false; using (var en = x.OrderBy(i => i).GetEnumerator()) { foreach (char c in y.OrderBy(i => i)) { en.MoveNext(); if (c != en.Current) return false; } } return true; } public int GetHashCode(string obj) { int hash = 0; foreach (char c in obj) hash ^= (int)c; return hash; } } public struct Record { public string Name; public int Score; } [Fact] public void SameResultsRepeatCallsStringQuery() { var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" } select x1; ; var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 } select x2; var q = from x3 in q1 from x4 in q2 select new { a1 = x3, a2 = x4 }; Assert.NotNull(q.GroupBy(e => e.a1, e => e.a2)); Assert.Equal(q.GroupBy(e => e.a1, e => e.a2), q.GroupBy(e => e.a1, e => e.a2)); } [Fact] public void Grouping_IList_IsReadOnly() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); foreach (IList<int> grouping in oddsEvens) { Assert.True(grouping.IsReadOnly); } } [Fact] public void Grouping_IList_NotSupported() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); foreach (IList<int> grouping in oddsEvens) { Assert.Throws<NotSupportedException>(() => grouping.Add(5)); Assert.Throws<NotSupportedException>(() => grouping.Clear()); Assert.Throws<NotSupportedException>(() => grouping.Insert(0, 1)); Assert.Throws<NotSupportedException>(() => grouping.Remove(1)); Assert.Throws<NotSupportedException>(() => grouping.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => grouping[0] = 1); } } [Fact] public void Grouping_IList_IndexerGetter() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); IList<int> odds = (IList<int>)e.Current; Assert.Equal(1, odds[0]); Assert.Equal(3, odds[1]); Assert.True(e.MoveNext()); IList<int> evens = (IList<int>)e.Current; Assert.Equal(2, evens[0]); Assert.Equal(4, evens[1]); } [Fact] public void Grouping_IList_IndexGetterOutOfRange() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); IList<int> odds = (IList<int>)e.Current; Assert.Throws<ArgumentOutOfRangeException>("index", () => odds[-1]); Assert.Throws<ArgumentOutOfRangeException>("index", () => odds[23]); } [Fact] public void Grouping_ICollection_Contains() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); ICollection<int> odds = (IList<int>)e.Current; Assert.True(odds.Contains(1)); Assert.True(odds.Contains(3)); Assert.False(odds.Contains(2)); Assert.False(odds.Contains(4)); Assert.True(e.MoveNext()); ICollection<int> evens = (IList<int>)e.Current; Assert.True(evens.Contains(2)); Assert.True(evens.Contains(4)); Assert.False(evens.Contains(1)); Assert.False(evens.Contains(3)); } [Fact] public void Grouping_IList_IndexOf() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); IList<int> odds = (IList<int>)e.Current; Assert.Equal(0, odds.IndexOf(1)); Assert.Equal(1, odds.IndexOf(3)); Assert.Equal(-1, odds.IndexOf(2)); Assert.Equal(-1, odds.IndexOf(4)); Assert.True(e.MoveNext()); IList<int> evens = (IList<int>)e.Current; Assert.Equal(0, evens.IndexOf(2)); Assert.Equal(1, evens.IndexOf(4)); Assert.Equal(-1, evens.IndexOf(1)); Assert.Equal(-1, evens.IndexOf(3)); } [Fact] public void SingleNullKeySingleNullElement() { string[] key = { null }; string[] element = { null }; AssertGroupingCorrect(key, element, new string[] { null }.GroupBy(e => e, e => e, EqualityComparer<string>.Default), EqualityComparer<string>.Default); } [Fact] public void EmptySource() { string[] key = { }; int[] element = { }; Record[] source = { }; Assert.Empty(new Record[] { }.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void SourceIsNull() { Record[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void SourceIsNullResultSelectorUsed() { Record[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); } [Fact] public void SourceIsNullResultSelectorUsedNoComparer() { Record[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum())); } [Fact] public void SourceIsNullResultSelectorUsedNoComparerOrElementSelector() { Record[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score))); } [Fact] public void KeySelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void KeySelectorNullResultSelectorUsed() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); } [Fact] public void KeySelectorNullResultSelectorUsedNoComparer() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<Record, string> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(keySelector, e => e.Score, (k, es) => es.Sum())); } [Fact] public void KeySelectorNullResultSelectorUsedNoElementSelector() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Assert.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer())); } [Fact] public void ElementSelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<Record, int> elementSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => source.GroupBy(e => e.Name, elementSelector, new AnagramEqualityComparer())); } [Fact] public void ElementSelectorNullResultSelectorUsedNoComparer() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<Record, int> elementSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => source.GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum())); } [Fact] public void ResultSelectorNull() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<string, IEnumerable<int>, long> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, e => e.Score, resultSelector, new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNullNoComparer() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<string, IEnumerable<int>, long> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, e => e.Score, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelector() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<string, IEnumerable<Record>, long> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelectorCustomComparer() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Func<string, IEnumerable<Record>, long> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, resultSelector, new AnagramEqualityComparer())); } [Fact] public void EmptySourceWithResultSelector() { string[] key = { }; int[] element = { }; Record[] source = { }; Assert.Empty(new Record[] { }.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void DuplicateKeysCustomComparer() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 240, 365, -600, 63 }; Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void NullComparer() { string[] key = { "Tim", null, null, "Robert", "Chris", "miT" }; int[] element = { 55, 49, 9, -100, 24, 25 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = null, Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = null, Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 165, 58, -600, 120, 75 }; Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null)); } [Fact] public void SingleNonNullElement() { string[] key = { "Tim" }; Record[] source = { new Record { Name = key[0], Score = 60 } }; AssertGroupingCorrect(key, source, source.GroupBy(e => e.Name)); } [Fact] public void AllElementsSameKey() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] scores = { 60, -10, 40, 100 }; var source = key.Zip(scores, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, source, source.GroupBy(e => e.Name, new AnagramEqualityComparer()), new AnagramEqualityComparer()); } [Fact] public void AllElementsDifferentKeyElementSelectorUsed() { string[] key = { "Tim", "Chris", "Robert", "Prakash" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score)); } [Fact] public void SomeDuplicateKeys() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score)); } [Fact] public void SomeDuplicateKeysIncludingNulls() { string[] key = { null, null, "Chris", "Chris", "Prakash", "Prakash" }; int[] element = { 55, 25, 49, 24, 9, 9 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score)); } [Fact] public void SingleElementResultSelectorUsed() { string[] key = { "Tim" }; int[] element = { 60 }; long[] expected = { 180 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => (long)(k ?? " ").Length * es.Sum(e => e.Score))); } [Fact] public void GroupedResultCorrectSize() { var elements = Enumerable.Repeat('q', 5); var result = elements.GroupBy(e => e, (e, f) => new { Key = e, Element = f }); Assert.Equal(1, result.Count()); var grouping = result.First(); Assert.Equal(5, grouping.Element.Count()); Assert.Equal('q', grouping.Key); Assert.True(grouping.Element.All(e => e == 'q')); } [Fact] public void AllElementsDifferentKeyElementSelectorUsedResultSelector() { string[] key = { "Tim", "Chris", "Robert", "Prakash" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); long[] expected = { 180, -50, 240, 700 }; Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum())); } [Fact] public void AllElementsSameKeyResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; long[] expected = { 570 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] } }; Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), new AnagramEqualityComparer())); } [Fact] public void NullComparerResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] }, }; long[] expected = { 150, 420 }; Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), null)); } [Fact] public void GroupingToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; IGrouping<string, Record>[] groupedArray = source.GroupBy(r => r.Name).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name), groupedArray); } [Fact] public void GroupingWithResultsToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; IEnumerable<Record>[] groupedArray = source.GroupBy(r => r.Name, (r, e) => e).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name, (r, e) => e), groupedArray); } } }
// 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.Diagnostics.Contracts; using System.Text; namespace System.IO { // Provides methods for processing file system strings in a cross-platform manner. // Most of the methods don't do a complete parsing (such as examining a UNC hostname), // but they will handle most string operations. public static partial class Path { // Public static readonly variant of the separators. The Path implementation itself is using // internal const variant of the separators for better performance. public static readonly char DirectorySeparatorChar = PathInternal.DirectorySeparatorChar; public static readonly char AltDirectorySeparatorChar = PathInternal.AltDirectorySeparatorChar; public static readonly char VolumeSeparatorChar = PathInternal.VolumeSeparatorChar; public static readonly char PathSeparator = PathInternal.PathSeparator; // For generating random file names // 8 random bytes provides 12 chars in our encoding for the 8.3 name. const int KeyLength = 8; [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] public static readonly char[] InvalidPathChars = GetInvalidPathChars(); // Changes the extension of a file path. The path parameter // specifies a file path, and the extension parameter // specifies a file extension (with a leading period, such as // ".exe" or ".cs"). // // The function returns a file path with the same root, directory, and base // name parts as path, but with the file extension changed to // the specified extension. If path is null, the function // returns null. If path does not contain a file extension, // the new file extension is appended to the path. If extension // is null, any existing extension is removed from path. public static string ChangeExtension(string path, string extension) { if (path != null) { PathInternal.CheckInvalidPathChars(path); string s = path; for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { s = path.Substring(0, i); break; } if (PathInternal.IsDirectoryOrVolumeSeparator(ch)) break; } if (extension != null && path.Length != 0) { s = (extension.Length == 0 || extension[0] != '.') ? s + "." + extension : s + extension; } return s; } return null; } // Returns the directory path of a file path. This method effectively // removes the last element of the given file path, i.e. it returns a // string consisting of all characters up to but not including the last // backslash ("\") in the file path. The returned value is null if the file // path is null or if the file path denotes a root (such as "\", "C:", or // "\\server\share"). public static string GetDirectoryName(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); path = PathInternal.NormalizeDirectorySeparators(path); int root = PathInternal.GetRootLength(path); int i = path.Length; if (i > root) { while (i > root && !PathInternal.IsDirectorySeparator(path[--i])) ; return path.Substring(0, i); } } return null; } // Returns the extension of the given path. The returned value includes the // period (".") character of the extension except when you have a terminal period when you get string.Empty, such as ".exe" or // ".cpp". The returned value is null if the given path is // null or if the given path does not include an extension. [Pure] public static string GetExtension(string path) { if (path == null) return null; PathInternal.CheckInvalidPathChars(path); int length = path.Length; for (int i = length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { if (i != length - 1) return path.Substring(i, length - i); else return string.Empty; } if (PathInternal.IsDirectoryOrVolumeSeparator(ch)) break; } return string.Empty; } // Returns the name and extension parts of the given path. The resulting // string contains the characters of path that follow the last // separator in path. The resulting string is null if path is null. [Pure] public static string GetFileName(string path) { if (path == null) return null; int offset = PathInternal.FindFileNameIndex(path); int count = path.Length - offset; return path.Substring(offset, count); } [Pure] public static string GetFileNameWithoutExtension(string path) { if (path == null) return null; int length = path.Length; int offset = PathInternal.FindFileNameIndex(path); int end = path.LastIndexOf('.', length - 1, length - offset); return end == -1 ? path.Substring(offset) : // No extension was found path.Substring(offset, end - offset); } // Returns a cryptographically strong random 8.3 string that can be // used as either a folder name or a file name. public static unsafe string GetRandomFileName() { byte* pKey = stackalloc byte[KeyLength]; GetCryptoRandomBytes(pKey, KeyLength); const int RandomFileNameLength = 12; char* pRandomFileName = stackalloc char[RandomFileNameLength]; Populate83FileNameFromRandomBytes(pKey, KeyLength, pRandomFileName, RandomFileNameLength); return new string(pRandomFileName, 0, RandomFileNameLength); } // Tests if a path includes a file extension. The result is // true if the characters that follow the last directory // separator ('\\' or '/') or volume separator (':') in the path include // a period (".") other than a terminal period. The result is false otherwise. [Pure] public static bool HasExtension(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { return i != path.Length - 1; } if (PathInternal.IsDirectoryOrVolumeSeparator(ch)) break; } } return false; } public static string Combine(string path1, string path2) { if (path1 == null || path2 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1): nameof(path2)); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); return CombineNoChecks(path1, path2); } public static string Combine(string path1, string path2, string path3) { if (path1 == null || path2 == null || path3 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1): (path2 == null) ? nameof(path2): nameof(path3)); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); PathInternal.CheckInvalidPathChars(path3); return CombineNoChecks(path1, path2, path3); } public static string Combine(string path1, string path2, string path3, string path4) { if (path1 == null || path2 == null || path3 == null || path4 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1): (path2 == null) ? nameof(path2): (path3 == null) ? nameof(path3): nameof(path4)); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); PathInternal.CheckInvalidPathChars(path3); PathInternal.CheckInvalidPathChars(path4); return CombineNoChecks(path1, path2, path3, path4); } public static string Combine(params string[] paths) { if (paths == null) { throw new ArgumentNullException(nameof(paths)); } Contract.EndContractBlock(); int finalSize = 0; int firstComponent = 0; // We have two passes, the first calculates how large a buffer to allocate and does some precondition // checks on the paths passed in. The second actually does the combination. for (int i = 0; i < paths.Length; i++) { if (paths[i] == null) { throw new ArgumentNullException(nameof(paths)); } if (paths[i].Length == 0) { continue; } PathInternal.CheckInvalidPathChars(paths[i]); if (IsPathRooted(paths[i])) { firstComponent = i; finalSize = paths[i].Length; } else { finalSize += paths[i].Length; } char ch = paths[i][paths[i].Length - 1]; if (!PathInternal.IsDirectoryOrVolumeSeparator(ch)) finalSize++; } StringBuilder finalPath = StringBuilderCache.Acquire(finalSize); for (int i = firstComponent; i < paths.Length; i++) { if (paths[i].Length == 0) { continue; } if (finalPath.Length == 0) { finalPath.Append(paths[i]); } else { char ch = finalPath[finalPath.Length - 1]; if (!PathInternal.IsDirectoryOrVolumeSeparator(ch)) { finalPath.Append(PathInternal.DirectorySeparatorChar); } finalPath.Append(paths[i]); } } return StringBuilderCache.GetStringAndRelease(finalPath); } private static string CombineNoChecks(string path1, string path2) { if (path2.Length == 0) return path1; if (path1.Length == 0) return path2; if (IsPathRooted(path2)) return path2; char ch = path1[path1.Length - 1]; return PathInternal.IsDirectoryOrVolumeSeparator(ch) ? path1 + path2 : path1 + PathInternal.DirectorySeparatorCharAsString + path2; } private static string CombineNoChecks(string path1, string path2, string path3) { if (path1.Length == 0) return CombineNoChecks(path2, path3); if (path2.Length == 0) return CombineNoChecks(path1, path3); if (path3.Length == 0) return CombineNoChecks(path1, path2); if (IsPathRooted(path3)) return path3; if (IsPathRooted(path2)) return CombineNoChecks(path2, path3); bool hasSep1 = PathInternal.IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]); bool hasSep2 = PathInternal.IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]); if (hasSep1 && hasSep2) { return path1 + path2 + path3; } else if (hasSep1) { return path1 + path2 + PathInternal.DirectorySeparatorCharAsString + path3; } else if (hasSep2) { return path1 + PathInternal.DirectorySeparatorCharAsString + path2 + path3; } else { // string.Concat only has string-based overloads up to four arguments; after that requires allocating // a params string[]. Instead, try to use a cached StringBuilder. StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + 2); sb.Append(path1) .Append(PathInternal.DirectorySeparatorChar) .Append(path2) .Append(PathInternal.DirectorySeparatorChar) .Append(path3); return StringBuilderCache.GetStringAndRelease(sb); } } private static string CombineNoChecks(string path1, string path2, string path3, string path4) { if (path1.Length == 0) return CombineNoChecks(path2, path3, path4); if (path2.Length == 0) return CombineNoChecks(path1, path3, path4); if (path3.Length == 0) return CombineNoChecks(path1, path2, path4); if (path4.Length == 0) return CombineNoChecks(path1, path2, path3); if (IsPathRooted(path4)) return path4; if (IsPathRooted(path3)) return CombineNoChecks(path3, path4); if (IsPathRooted(path2)) return CombineNoChecks(path2, path3, path4); bool hasSep1 = PathInternal.IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]); bool hasSep2 = PathInternal.IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]); bool hasSep3 = PathInternal.IsDirectoryOrVolumeSeparator(path3[path3.Length - 1]); if (hasSep1 && hasSep2 && hasSep3) { // Use string.Concat overload that takes four strings return path1 + path2 + path3 + path4; } else { // string.Concat only has string-based overloads up to four arguments; after that requires allocating // a params string[]. Instead, try to use a cached StringBuilder. StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + path4.Length + 3); sb.Append(path1); if (!hasSep1) { sb.Append(PathInternal.DirectorySeparatorChar); } sb.Append(path2); if (!hasSep2) { sb.Append(PathInternal.DirectorySeparatorChar); } sb.Append(path3); if (!hasSep3) { sb.Append(PathInternal.DirectorySeparatorChar); } sb.Append(path4); return StringBuilderCache.GetStringAndRelease(sb); } } private static readonly char[] s_base32Char = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5'}; private static unsafe void Populate83FileNameFromRandomBytes(byte* bytes, int byteCount, char* chars, int charCount) { Debug.Assert(bytes != null); Debug.Assert(chars != null); // This method requires bytes of length 8 and chars of length 12. Debug.Assert(byteCount == 8, $"Unexpected {nameof(byteCount)}"); Debug.Assert(charCount == 12, $"Unexpected {nameof(charCount)}"); byte b0 = bytes[0]; byte b1 = bytes[1]; byte b2 = bytes[2]; byte b3 = bytes[3]; byte b4 = bytes[4]; // Consume the 5 Least significant bits of the first 5 bytes chars[0] = s_base32Char[b0 & 0x1F]; chars[1] = s_base32Char[b1 & 0x1F]; chars[2] = s_base32Char[b2 & 0x1F]; chars[3] = s_base32Char[b3 & 0x1F]; chars[4] = s_base32Char[b4 & 0x1F]; // Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4 chars[5] = s_base32Char[( ((b0 & 0xE0) >> 5) | ((b3 & 0x60) >> 2))]; chars[6] = s_base32Char[( ((b1 & 0xE0) >> 5) | ((b4 & 0x60) >> 2))]; // Consume 3 MSB bits of b2, 1 MSB bit of b3, b4 b2 >>= 5; Debug.Assert(((b2 & 0xF8) == 0), "Unexpected set bits"); if ((b3 & 0x80) != 0) b2 |= 0x08; if ((b4 & 0x80) != 0) b2 |= 0x10; chars[7] = s_base32Char[b2]; // Set the file extension separator chars[8] = '.'; // Consume the 5 Least significant bits of the remaining 3 bytes chars[9] = s_base32Char[(bytes[5] & 0x1F)]; chars[10] = s_base32Char[(bytes[6] & 0x1F)]; chars[11] = s_base32Char[(bytes[7] & 0x1F)]; } /// <summary> /// Create a relative path from one path to another. Paths will be resolved before calculating the difference. /// Default path comparison for the active platform will be used (OrdinalIgnoreCase for Windows or Mac, Ordinal for Unix). /// </summary> /// <param name="relativeTo">The source path the output should be relative to. This path is always considered to be a directory.</param> /// <param name="path">The destination path.</param> /// <returns>The relative path or <paramref name="path"/> if the paths don't share the same root.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="relativeTo"/> or <paramref name="path"/> is <c>null</c> or an empty string.</exception> public static string GetRelativePath(string relativeTo, string path) { return GetRelativePath(relativeTo, path, StringComparison); } private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType) { if (string.IsNullOrEmpty(relativeTo)) throw new ArgumentNullException(nameof(relativeTo)); if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException(nameof(path)); Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); relativeTo = GetFullPath(relativeTo); path = GetFullPath(path); // Need to check if the roots are different- if they are we need to return the "to" path. if (!PathInternal.AreRootsEqual(relativeTo, path, comparisonType)) return path; int commonLength = PathInternal.GetCommonPathLength(relativeTo, path, ignoreCase: comparisonType == StringComparison.OrdinalIgnoreCase); // If there is nothing in common they can't share the same root, return the "to" path as is. if (commonLength == 0) return path; // Trailing separators aren't significant for comparison int relativeToLength = relativeTo.Length; if (PathInternal.EndsInDirectorySeparator(relativeTo)) relativeToLength--; bool pathEndsInSeparator = PathInternal.EndsInDirectorySeparator(path); int pathLength = path.Length; if (pathEndsInSeparator) pathLength--; // If we have effectively the same path, return "." if (relativeToLength == pathLength && commonLength >= relativeToLength) return "."; // We have the same root, we need to calculate the difference now using the // common Length and Segment count past the length. // // Some examples: // // C:\Foo C:\Bar L3, S1 -> ..\Bar // C:\Foo C:\Foo\Bar L6, S0 -> Bar // C:\Foo\Bar C:\Bar\Bar L3, S2 -> ..\..\Bar\Bar // C:\Foo\Foo C:\Foo\Bar L7, S1 -> ..\Bar StringBuilder sb = StringBuilderCache.Acquire(Math.Max(relativeTo.Length, path.Length)); // Add parent segments for segments past the common on the "from" path if (commonLength < relativeToLength) { sb.Append(PathInternal.ParentDirectoryPrefix); for (int i = commonLength; i < relativeToLength; i++) { if (PathInternal.IsDirectorySeparator(relativeTo[i])) { sb.Append(PathInternal.ParentDirectoryPrefix); } } } else if (PathInternal.IsDirectorySeparator(path[commonLength])) { // No parent segments and we need to eat the initial separator // (C:\Foo C:\Foo\Bar case) commonLength++; } // Now add the rest of the "to" path, adding back the trailing separator int count = pathLength - commonLength; if (pathEndsInSeparator) count++; sb.Append(path, commonLength, count); return StringBuilderCache.GetStringAndRelease(sb); } // StringComparison and IsCaseSensitive are also available in PathInternal.CaseSensitivity but we are // too low in System.Runtime.Extensions to use it (no FileStream, etc.) /// <summary>Returns a comparison that can be used to compare file and directory names for equality.</summary> internal static StringComparison StringComparison { get { return IsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; } } } }
using Duende.IdentityServer.Events; using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; using IdentityModel; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace DuendeDynamicProviders.Pages.Consent; [Authorize] [SecurityHeadersAttribute] public class Index : PageModel { private readonly IIdentityServerInteractionService _interaction; private readonly IEventService _events; private readonly ILogger<Index> _logger; public Index( IIdentityServerInteractionService interaction, IEventService events, ILogger<Index> logger) { _interaction = interaction; _events = events; _logger = logger; } public ViewModel View { get; set; } [BindProperty] public InputModel Input { get; set; } public async Task<IActionResult> OnGet(string returnUrl) { View = await BuildViewModelAsync(returnUrl); if (View == null) { return RedirectToPage("/Error/Index"); } Input = new InputModel { ReturnUrl = returnUrl, }; return Page(); } public async Task<IActionResult> OnPost() { // validate return url is still valid var request = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl); if (request == null) return RedirectToPage("/Error/Index"); ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (Input?.Button == "no") { grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied }; // emit event await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues)); } // user clicked 'yes' - validate the data else if (Input?.Button == "yes") { // if the user consented to some scope, build the response model if (Input.ScopesConsented != null && Input.ScopesConsented.Any()) { var scopes = Input.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = Input.RememberConsent, ScopesValuesConsented = scopes.ToArray(), Description = Input.Description }; // emit event await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent)); } else { ModelState.AddModelError("", ConsentOptions.MustChooseOneErrorMessage); } } else { ModelState.AddModelError("", ConsentOptions.InvalidSelectionErrorMessage); } if (grantedConsent != null) { // communicate outcome of consent back to identityserver await _interaction.GrantConsentAsync(request, grantedConsent); // redirect back to authorization endpoint if (request.IsNativeClient() == true) { // The client is native, so this change in how to // return the response is for better UX for the end user. return this.LoadingPage(Input.ReturnUrl); } return Redirect(Input.ReturnUrl); } // we need to redisplay the consent UI View = await BuildViewModelAsync(Input.ReturnUrl, Input); return Page(); } private async Task<ViewModel> BuildViewModelAsync(string returnUrl, InputModel model = null) { var request = await _interaction.GetAuthorizationContextAsync(returnUrl); if (request != null) { return CreateConsentViewModel(model, returnUrl, request); } else { _logger.LogError("No consent request matching request: {0}", returnUrl); } return null; } private ViewModel CreateConsentViewModel( InputModel model, string returnUrl, AuthorizationRequest request) { var vm = new ViewModel { ClientName = request.Client.ClientName ?? request.Client.ClientId, ClientUrl = request.Client.ClientUri, ClientLogoUrl = request.Client.LogoUri, AllowRememberConsent = request.Client.AllowRememberConsent }; vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources .Select(x => CreateScopeViewModel(x, model?.ScopesConsented == null || model.ScopesConsented?.Contains(x.Name) == true)) .ToArray(); var resourceIndicators = request.Parameters.GetValues(OidcConstants.AuthorizeRequest.Resource) ?? Enumerable.Empty<string>(); var apiResources = request.ValidatedResources.Resources.ApiResources.Where(x => resourceIndicators.Contains(x.Name)); var apiScopes = new List<ScopeViewModel>(); foreach (var parsedScope in request.ValidatedResources.ParsedScopes) { var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName); if (apiScope != null) { var scopeVm = CreateScopeViewModel(parsedScope, apiScope, model == null || model.ScopesConsented?.Contains(parsedScope.RawValue) == true); scopeVm.Resources = apiResources.Where(x => x.Scopes.Contains(parsedScope.ParsedName)) .Select(x => new ResourceViewModel { Name = x.Name, DisplayName = x.DisplayName ?? x.Name, }).ToArray(); apiScopes.Add(scopeVm); } } if (ConsentOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess) { apiScopes.Add(GetOfflineAccessScope(model == null || model.ScopesConsented?.Contains(Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess) == true)); } vm.ApiScopes = apiScopes; return vm; } private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check) { return new ScopeViewModel { Name = identity.Name, Value = identity.Name, DisplayName = identity.DisplayName ?? identity.Name, Description = identity.Description, Emphasize = identity.Emphasize, Required = identity.Required, Checked = check || identity.Required }; } public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check) { var displayName = apiScope.DisplayName ?? apiScope.Name; if (!String.IsNullOrWhiteSpace(parsedScopeValue.ParsedParameter)) { displayName += ":" + parsedScopeValue.ParsedParameter; } return new ScopeViewModel { Name = parsedScopeValue.ParsedName, Value = parsedScopeValue.RawValue, DisplayName = displayName, Description = apiScope.Description, Emphasize = apiScope.Emphasize, Required = apiScope.Required, Checked = check || apiScope.Required }; } private ScopeViewModel GetOfflineAccessScope(bool check) { return new ScopeViewModel { Value = Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess, DisplayName = ConsentOptions.OfflineAccessDisplayName, Description = ConsentOptions.OfflineAccessDescription, Emphasize = true, Checked = check }; } }
using System; using System.IO; using System.Collections; using System.Text; using System.Text.RegularExpressions; using System.Xml.Serialization; using System.Xml; using System.Collections.Generic; #if SILVERLIGHT using System.Linq; #endif namespace FlickrNet { /// <summary> /// Internal class providing certain utility functions to other classes. /// </summary> public sealed class UtilityMethods { private static readonly DateTime unixStartDate = new DateTime(1970, 1, 1, 0, 0, 0); private UtilityMethods() { } /* /// <summary> /// Converts <see cref="AuthLevel"/> to a string. /// </summary> /// <param name="level">The level to convert.</param> /// <returns></returns> public static string AuthLevelToString(AuthLevel level) { switch (level) { case AuthLevel.Delete: return "delete"; case AuthLevel.Read: return "read"; case AuthLevel.Write: return "write"; case AuthLevel.None: return "none"; default: return String.Empty; } }*/ /// <summary> /// Convert a <see cref="TagMode"/> to a string used when passing to Flickr. /// </summary> /// <param name="tagMode">The tag mode to convert.</param> /// <returns>The string to pass to Flickr.</returns> public static string TagModeToString(TagMode tagMode) { switch (tagMode) { case TagMode.None: return String.Empty; case TagMode.AllTags: return "all"; case TagMode.AnyTag: return "any"; case TagMode.Boolean: return "bool"; default: return String.Empty; } } /// <summary> /// Convert a <see cref="MachineTagMode"/> to a string used when passing to Flickr. /// </summary> /// <param name="machineTagMode">The machine tag mode to convert.</param> /// <returns>The string to pass to Flickr.</returns> public static string MachineTagModeToString(MachineTagMode machineTagMode) { switch (machineTagMode) { case MachineTagMode.None: return String.Empty; case MachineTagMode.AllTags: return "all"; case MachineTagMode.AnyTag: return "any"; default: return String.Empty; } } /// <summary> /// Encodes a URL quesrystring data component. /// </summary> /// <param name="data">The data to encode.</param> /// <returns>The URL encoded string.</returns> public static string UrlEncode(string data) { return Uri.EscapeDataString(data); } /// <summary> /// Converts a <see cref="DateTime"/> object into a unix timestamp number. /// </summary> /// <param name="date">The date to convert.</param> /// <returns>A long for the number of seconds since 1st January 1970, as per unix specification.</returns> public static string DateToUnixTimestamp(DateTime date) { TimeSpan ts = date - unixStartDate; return ts.TotalSeconds.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); } /// <summary> /// Converts a string, representing a unix timestamp number into a <see cref="DateTime"/> object. /// </summary> /// <param name="timestamp">The timestamp, as a string.</param> /// <returns>The <see cref="DateTime"/> object the time represents.</returns> public static DateTime UnixTimestampToDate(string timestamp) { if (String.IsNullOrEmpty(timestamp)) return DateTime.MinValue; try { return UnixTimestampToDate(Int64.Parse(timestamp, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo)); } catch (FormatException) { return DateTime.MinValue; } } /// <summary> /// Converts a <see cref="long"/>, representing a unix timestamp number into a <see cref="DateTime"/> object. /// </summary> /// <param name="timestamp">The unix timestamp.</param> /// <returns>The <see cref="DateTime"/> object the time represents.</returns> public static DateTime UnixTimestampToDate(long timestamp) { return unixStartDate.AddSeconds(timestamp); } /// <summary> /// Utility method to convert the <see cref="PhotoSearchExtras"/> enum to a string. /// </summary> /// <example> /// <code> /// PhotoSearchExtras extras = PhotoSearchExtras.DateTaken &amp; PhotoSearchExtras.IconServer; /// string val = Utils.ExtrasToString(extras); /// Console.WriteLine(val); /// </code> /// outputs: "date_taken,icon_server"; /// </example> /// <param name="extras"></param> /// <returns></returns> public static string ExtrasToString(PhotoSearchExtras extras) { List<string> extraList = new List<string>(); if ((extras & PhotoSearchExtras.DateTaken) == PhotoSearchExtras.DateTaken) extraList.Add("date_taken"); if ((extras & PhotoSearchExtras.DateUploaded) == PhotoSearchExtras.DateUploaded) extraList.Add("date_upload"); if ((extras & PhotoSearchExtras.IconServer) == PhotoSearchExtras.IconServer) extraList.Add("icon_server"); if ((extras & PhotoSearchExtras.License) == PhotoSearchExtras.License) extraList.Add("license"); if ((extras & PhotoSearchExtras.OwnerName) == PhotoSearchExtras.OwnerName) extraList.Add("owner_name"); if ((extras & PhotoSearchExtras.OriginalFormat) == PhotoSearchExtras.OriginalFormat) extraList.Add("original_format"); if ((extras & PhotoSearchExtras.LastUpdated) == PhotoSearchExtras.LastUpdated) extraList.Add("last_update"); if ((extras & PhotoSearchExtras.Tags) == PhotoSearchExtras.Tags) extraList.Add("tags"); if ((extras & PhotoSearchExtras.Geo) == PhotoSearchExtras.Geo) extraList.Add("geo"); if ((extras & PhotoSearchExtras.MachineTags) == PhotoSearchExtras.MachineTags) extraList.Add("machine_tags"); if ((extras & PhotoSearchExtras.OriginalDimensions) == PhotoSearchExtras.OriginalDimensions) extraList.Add("o_dims"); if ((extras & PhotoSearchExtras.Views) == PhotoSearchExtras.Views) extraList.Add("views"); if ((extras & PhotoSearchExtras.Media) == PhotoSearchExtras.Media) extraList.Add("media"); if ((extras & PhotoSearchExtras.PathAlias) == PhotoSearchExtras.PathAlias) extraList.Add("path_alias"); if ((extras & PhotoSearchExtras.SquareUrl) == PhotoSearchExtras.SquareUrl) extraList.Add("url_sq"); if ((extras & PhotoSearchExtras.ThumbnailUrl) == PhotoSearchExtras.ThumbnailUrl) extraList.Add("url_t"); if ((extras & PhotoSearchExtras.SmallUrl) == PhotoSearchExtras.SmallUrl) extraList.Add("url_s"); if ((extras & PhotoSearchExtras.MediumUrl) == PhotoSearchExtras.MediumUrl) extraList.Add("url_m"); if ((extras & PhotoSearchExtras.Medium640Url) == PhotoSearchExtras.Medium640Url) extraList.Add("url_z"); if ((extras & PhotoSearchExtras.LargeSquareUrl) == PhotoSearchExtras.LargeSquareUrl) extraList.Add("url_q"); if ((extras & PhotoSearchExtras.Small320Url) == PhotoSearchExtras.Small320Url) extraList.Add("url_n"); if ((extras & PhotoSearchExtras.LargeUrl) == PhotoSearchExtras.LargeUrl) extraList.Add("url_l"); if ((extras & PhotoSearchExtras.OriginalUrl) == PhotoSearchExtras.OriginalUrl) extraList.Add("url_o"); if ((extras & PhotoSearchExtras.Description) == PhotoSearchExtras.Description) extraList.Add("description"); if ((extras & PhotoSearchExtras.Usage) == PhotoSearchExtras.Usage) extraList.Add("usage"); if ((extras & PhotoSearchExtras.Visibility) == PhotoSearchExtras.Visibility) extraList.Add("visibility"); if ((extras & PhotoSearchExtras.Rotation) == PhotoSearchExtras.Rotation) extraList.Add("rotation"); return String.Join(",", extraList.ToArray()); } /// <summary> /// Converts a <see cref="PhotoSearchSortOrder"/> into a string for use by the Flickr API. /// </summary> /// <param name="order">The sort order to convert.</param> /// <returns>The string representative for the sort order.</returns> public static string SortOrderToString(PhotoSearchSortOrder order) { switch (order) { case PhotoSearchSortOrder.DatePostedAscending: return "date-posted-asc"; case PhotoSearchSortOrder.DatePostedDescending: return "date-posted-desc"; case PhotoSearchSortOrder.DateTakenAscending: return "date-taken-asc"; case PhotoSearchSortOrder.DateTakenDescending: return "date-taken-desc"; case PhotoSearchSortOrder.InterestingnessAscending: return "interestingness-asc"; case PhotoSearchSortOrder.InterestingnessDescending: return "interestingness-desc"; case PhotoSearchSortOrder.Relevance: return "relevance"; default: return String.Empty; } } /* /// <summary> /// Converts a <see cref="PopularitySort"/> enum to a string. /// </summary> /// <param name="sortOrder">The value to convert.</param> /// <returns></returns> public static string SortOrderToString(PopularitySort sortOrder) { switch (sortOrder) { case PopularitySort.Comments: return "comments"; case PopularitySort.Favorites: return "favorites"; case PopularitySort.Views: return "views"; default: return String.Empty; } } /// <summary> /// Adds the partial options to the passed in <see cref="Hashtable"/>. /// </summary> /// <param name="options">The options to convert to an array.</param> /// <param name="parameters">The <see cref="Hashtable"/> to add the option key value pairs to.</param> public static void PartialOptionsIntoArray(PartialSearchOptions options, Dictionary<string, string> parameters) { if (options.MinUploadDate != DateTime.MinValue) parameters.Add("min_uploaded_date", UtilityMethods.DateToUnixTimestamp(options.MinUploadDate).ToString()); if (options.MaxUploadDate != DateTime.MinValue) parameters.Add("max_uploaded_date", UtilityMethods.DateToUnixTimestamp(options.MaxUploadDate).ToString()); if (options.MinTakenDate != DateTime.MinValue) parameters.Add("min_taken_date", DateToMySql(options.MinTakenDate)); if (options.MaxTakenDate != DateTime.MinValue) parameters.Add("max_taken_date", DateToMySql(options.MaxTakenDate)); if (options.Extras != PhotoSearchExtras.None) parameters.Add("extras", options.ExtrasString); if (options.SortOrder != PhotoSearchSortOrder.None) parameters.Add("sort", options.SortOrderString); if (options.PerPage > 0) parameters.Add("per_page", options.PerPage.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); if (options.Page > 0) parameters.Add("page", options.Page.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); if (options.PrivacyFilter != PrivacyFilter.None) parameters.Add("privacy_filter", options.PrivacyFilter.ToString("d")); } */ internal static void WriteInt32(Stream s, int i) { s.WriteByte((byte)(i & 0xFF)); s.WriteByte((byte)((i >> 8) & 0xFF)); s.WriteByte((byte)((i >> 16) & 0xFF)); s.WriteByte((byte)((i >> 24) & 0xFF)); } internal static void WriteString(Stream s, string str) { WriteInt32(s, str.Length); foreach (char c in str) { s.WriteByte((byte)(c & 0xFF)); s.WriteByte((byte)((c >> 8) & 0xFF)); } } internal static int ReadInt32(Stream s) { int i = 0, b; for (int j = 0; j < 4; j++) { b = s.ReadByte(); if (b == -1) throw new IOException("Unexpected EOF encountered"); i |= b << (j * 8); } return i; } internal static string ReadString(Stream s) { int len = ReadInt32(s); char[] chars = new char[len]; for (int i = 0; i < len; i++) { int hi, lo; lo = s.ReadByte(); hi = s.ReadByte(); if (lo == -1 || hi == -1) throw new IOException("Unexpected EOF encountered"); chars[i] = (char)(lo | (hi << 8)); } return new string(chars); } private const string PhotoUrlFormat = "http://farm{0}.staticflickr.com/{1}/{2}_{3}{4}.{5}"; internal static string UrlFormat(Photo p, string size, string extension) { if (size == "_o" || size == "original") return UrlFormat(p.Farm, p.Server, p.PhotoId, p.OriginalSecret, size, extension); else return UrlFormat(p.Farm, p.Server, p.PhotoId, p.Secret, size, extension); } internal static string UrlFormat(PhotoInfo p, string size, string extension) { if (size == "_o" || size == "original") return UrlFormat(p.Farm, p.Server, p.PhotoId, p.OriginalSecret, size, extension); else return UrlFormat(p.Farm, p.Server, p.PhotoId, p.Secret, size, extension); } internal static string UrlFormat(Photoset p, string size, string extension) { return UrlFormat(p.Farm, p.Server, p.PrimaryPhotoId, p.Secret, size, extension); } internal static string UrlFormat(string farm, string server, string photoid, string secret, string size, string extension) { switch (size) { case "square": size = "_s"; break; case "thumbnail": size = "_t"; break; case "small": size = "_m"; break; case "medium": size = String.Empty; break; case "large": size = "_b"; break; case "original": size = "_o"; break; } return UrlFormat(PhotoUrlFormat, farm, server, photoid, secret, size, extension); } private static string UrlFormat(string format, params object[] parameters) { return String.Format(System.Globalization.CultureInfo.InvariantCulture, format, parameters); } /* internal static MemberTypes ParseIdToMemberType(string memberTypeId) { switch (memberTypeId) { case "1": return MemberTypes.Narwhal; case "2": return MemberTypes.Member; case "3": return MemberTypes.Moderator; case "4": return MemberTypes.Admin; default: return MemberTypes.None; } } internal static string MemberTypeToString(MemberTypes memberTypes) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if ((memberTypes & MemberTypes.Member) == MemberTypes.Member) sb.Append("2"); if ((memberTypes & MemberTypes.Moderator) == MemberTypes.Moderator) { if (sb.Length > 0) sb.Append(","); sb.Append("3"); } if ((memberTypes & MemberTypes.Admin) == MemberTypes.Admin) { if (sb.Length > 0) sb.Append(","); sb.Append("4"); } if ((memberTypes & MemberTypes.Narwhal) == MemberTypes.Narwhal) { if (sb.Length > 0) sb.Append(","); sb.Append("1"); } return sb.ToString(); } */ /// <summary> /// Generates an MD5 Hash of the passed in string. /// </summary> /// <param name="data">The unhashed string.</param> /// <returns>The MD5 hash string.</returns> public static string MD5Hash(string data) { #if SILVERLIGHT byte[] hashedBytes = MD5Core.GetHash(data, Encoding.UTF8); #else System.Security.Cryptography.MD5CryptoServiceProvider csp = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data); byte[] hashedBytes = csp.ComputeHash(bytes, 0, bytes.Length); #endif return BitConverter.ToString(hashedBytes).Replace("-", String.Empty).ToLower(System.Globalization.CultureInfo.InvariantCulture); } /// <summary> /// Parses a date which may contain only a vald year component. /// </summary> /// <param name="date">The date, as a string, to be parsed.</param> /// <returns>The parsed <see cref="DateTime"/>.</returns> public static DateTime ParseDateWithGranularity(string date) { DateTime output = DateTime.MinValue; if (String.IsNullOrEmpty(date)) return output; if (date == "0000-00-00 00:00:00") return output; if (date.EndsWith("-00-01 00:00:00")) { output = new DateTime(int.Parse(date.Substring(0, 4), System.Globalization.NumberFormatInfo.InvariantInfo), 1, 1); return output; } string format = "yyyy-MM-dd HH:mm:ss"; try { output = DateTime.ParseExact(date, format, System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None); } catch (FormatException) { #if DEBUG throw; #endif } return output; } internal static string DateToMySql(DateTime date) { return date.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo); } /// <summary> /// Converts a <see cref="MediaType"/> enumeration into a string used by Flickr. /// </summary> /// <param name="mediaType">The <see cref="MediaType"/> value to convert.</param> /// <returns></returns> public static string MediaTypeToString(MediaType mediaType) { switch (mediaType) { case MediaType.All: return "all"; case MediaType.Photos: return "photos"; case MediaType.Videos: return "videos"; default: return String.Empty; } } /// <summary> /// If an unknown element is found and the DLL is a debug DLL then a <see cref="ParsingException"/> is thrown. /// </summary> /// <param name="reader">The <see cref="XmlReader"/> containing the unknown xml node.</param> [System.Diagnostics.Conditional("DEBUG")] public static void CheckParsingException(XmlReader reader) { if (reader.NodeType == XmlNodeType.Attribute) { throw new ParsingException("Unknown attribute: " + reader.Name + "=" + reader.Value); } if (!String.IsNullOrEmpty(reader.Value)) throw new ParsingException("Unknown " + reader.NodeType.ToString() + ": " + reader.Name + "=" + reader.Value); else throw new ParsingException("Unknown element: " + reader.Name); } /// <summary> /// Returns the buddy icon for a given set of server, farm and userid. If no server is present then returns the standard buddy icon. /// </summary> /// <param name="server"></param> /// <param name="farm"></param> /// <param name="userId"></param> /// <returns></returns> public static string BuddyIcon(string server, string farm, string userId) { if (String.IsNullOrEmpty(server) || server == "0") return "http://www.flickr.com/images/buddyicon.jpg"; else return String.Format(System.Globalization.CultureInfo.InvariantCulture, "http://farm{0}.staticflickr.com/{1}/buddyicons/{2}.jpg", farm, server, userId); } /// <summary> /// Converts a URL parameter encoded string into a dictionary. /// </summary> /// <remarks> /// e.g. ab=cd&amp;ef=gh will return a dictionary of { "ab" => "cd", "ef" => "gh" }.</remarks> /// <param name="response"></param> /// <returns></returns> public static Dictionary<string, string> StringToDictionary(string response) { Dictionary<string, string> dic = new Dictionary<string, string>(); string[] parts = response.Split('&'); foreach (string part in parts) { #if WindowsCE || SILVERLIGHT string[] bits = part.Split('='); #else string[] bits = part.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries); #endif if (bits.Length == 1) dic.Add(bits[0], ""); else dic.Add(bits[0], Uri.UnescapeDataString(bits[1])); } return dic; } /// <summary> /// Escapes a string for use with OAuth. /// </summary> /// <remarks>The only valid characters are Alphanumerics and "-", "_", "." and "~". Everything else is hex encoded.</remarks> /// <param name="text">The text to escape.</param> /// <returns>The escaped string.</returns> public static string EscapeOAuthString(string text) { string value = text; value = Uri.EscapeDataString(value).Replace("+", "%20"); // UrlEncode escapes with lowercase characters (e.g. %2f) but oAuth needs %2F value = Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper()); // these characters are not escaped by UrlEncode() but needed to be escaped value = value.Replace("(", "%28").Replace(")", "%29").Replace("$", "%24").Replace("!", "%21").Replace( "*", "%2A").Replace("'", "%27"); // these characters are escaped by UrlEncode() but will fail if unescaped! value = value.Replace("%7E", "~"); return value; //string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; //StringBuilder result = new StringBuilder(text.Length * 2); //foreach (char symbol in text) //{ // if (unreservedChars.IndexOf(symbol) != -1) // { // result.Append(symbol); // } // else // { // result.Append('%' + String.Format("{0:X2}", (int)symbol)); // } //} //return result.ToString(); } } }
using System; using EncompassRest.Loans.Enums; using EncompassRest.Schema; namespace EncompassRest.Loans { /// <summary> /// AdditionalLoan /// </summary> [Entity(SerializeWholeListWhenDirty = true)] public sealed partial class AdditionalLoan : DirtyExtensibleObject, IIdentifiable { private DirtyValue<StringEnumValue<AccountType>>? _accountType; private DirtyValue<DateTime?>? _additionalLoanRequestDate; private DirtyValue<bool?>? _affordableLoan; private DirtyValue<string?>? _altId; private DirtyValue<decimal?>? _amountAppliedToDownpayment; private DirtyValue<string?>? _attention; private DirtyValue<StringEnumValue<Owner>>? _borrowerType; private DirtyValue<EntityReference?>? _contact; private DirtyValue<bool?>? _entityDeleted; private DirtyValue<decimal?>? _hELOCCreditLimitAmount; private DirtyValue<decimal?>? _hELOCInitialDraw; private DirtyValue<string?>? _holderAddressCity; private DirtyValue<string?>? _holderAddressPostalCode; private DirtyValue<StringEnumValue<State>>? _holderAddressState; private DirtyValue<string?>? _holderAddressStreetLine1; private DirtyValue<string?>? _holderEmail; private DirtyValue<string?>? _holderFax; private DirtyValue<string?>? _holderName; private DirtyValue<string?>? _holderPhone; private DirtyValue<string?>? _id; private DirtyValue<bool?>? _individualCreditorIndicator; private DirtyValue<StringEnumValue<AdditionalLoanLienPosition>>? _lienPosition; private DirtyValue<bool?>? _linkedPiggybackIndicator; private DirtyValue<decimal?>? _maximumPILoanAmount; private DirtyValue<decimal?>? _maximumPINoteRate; private DirtyValue<int?>? _maximumPITerm; private DirtyValue<decimal?>? _maximumPrincipalAndInterestIn5Years; private DirtyValue<decimal?>? _monthlyPILoanAmount; private DirtyValue<decimal?>? _monthlyPINoteRate; private DirtyValue<int?>? _monthlyPITerm; private DirtyValue<decimal?>? _monthlyPrincipalAndInterest; private DirtyValue<bool?>? _paymentDeferredFirstFiveYears; private DirtyValue<bool?>? _printAttachmentIndicator; private DirtyValue<bool?>? _printUserJobTitleIndicator; private DirtyValue<bool?>? _printUserNameIndicator; private DirtyValue<StringEnumValue<SourceOfFunds>>? _sourceOfFunds; private DirtyValue<string?>? _title; private DirtyValue<string?>? _titleFax; private DirtyValue<string?>? _titlePhone; /// <summary> /// Additional Loans AccountType [URLARALNN16] /// </summary> public StringEnumValue<AccountType> AccountType { get => _accountType; set => SetField(ref _accountType, value); } /// <summary> /// Additional Loans Request Date [URLARALNN98] /// </summary> public DateTime? AdditionalLoanRequestDate { get => _additionalLoanRequestDate; set => SetField(ref _additionalLoanRequestDate, value); } /// <summary> /// Additional Loans Affordable Loan Indicator [URLARALNN24] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Affordable Loan \"}")] public bool? AffordableLoan { get => _affordableLoan; set => SetField(ref _affordableLoan, value); } /// <summary> /// Additional Loans ID [URLARALNN99] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? AltId { get => _altId; set => SetField(ref _altId, value); } /// <summary> /// Additional Loans Amount Applied To Downpayment [URLARALNN22] /// </summary> public decimal? AmountAppliedToDownpayment { get => _amountAppliedToDownpayment; set => SetField(ref _amountAppliedToDownpayment, value); } /// <summary> /// Depository Attention Contact [URLARALNN03] /// </summary> public string? Attention { get => _attention; set => SetField(ref _attention, value); } /// <summary> /// Additional Loans Borrower Type [URLARALNN01] /// </summary> public StringEnumValue<Owner> BorrowerType { get => _borrowerType; set => SetField(ref _borrowerType, value); } /// <summary> /// AdditionalLoan Contact /// </summary> public EntityReference? Contact { get => _contact; set => SetField(ref _contact, value); } /// <summary> /// AdditionalLoan EntityDeleted /// </summary> public bool? EntityDeleted { get => _entityDeleted; set => SetField(ref _entityDeleted, value); } /// <summary> /// Additional Loans : Loan Amount/HELOC Credit Limit [URLARALNN20] /// </summary> public decimal? HELOCCreditLimitAmount { get => _hELOCCreditLimitAmount; set => SetField(ref _hELOCCreditLimitAmount, value); } /// <summary> /// Additional Loans HELOC Initial Draw [URLARALNN21] /// </summary> public decimal? HELOCInitialDraw { get => _hELOCInitialDraw; set => SetField(ref _hELOCInitialDraw, value); } /// <summary> /// Depository Attention City [URLARALNN05] /// </summary> public string? HolderAddressCity { get => _holderAddressCity; set => SetField(ref _holderAddressCity, value); } /// <summary> /// Depository Attention Zipcode [URLARALNN07] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? HolderAddressPostalCode { get => _holderAddressPostalCode; set => SetField(ref _holderAddressPostalCode, value); } /// <summary> /// Depository Attention State [URLARALNN06] /// </summary> public StringEnumValue<State> HolderAddressState { get => _holderAddressState; set => SetField(ref _holderAddressState, value); } /// <summary> /// Depository Address [URLARALNN04] /// </summary> public string? HolderAddressStreetLine1 { get => _holderAddressStreetLine1; set => SetField(ref _holderAddressStreetLine1, value); } /// <summary> /// Depository Email [URLARALNN10] /// </summary> public string? HolderEmail { get => _holderEmail; set => SetField(ref _holderEmail, value); } /// <summary> /// Depository Fax [URLARALNN09] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? HolderFax { get => _holderFax; set => SetField(ref _holderFax, value); } /// <summary> /// Depository Name [URLARALNN02] /// </summary> public string? HolderName { get => _holderName; set => SetField(ref _holderName, value); } /// <summary> /// Depository Phone [URLARALNN08] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? HolderPhone { get => _holderPhone; set => SetField(ref _holderPhone, value); } /// <summary> /// AdditionalLoan Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// Creditor is an individual Indicator [URLARALNN32] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Creditor is an individual\"}")] public bool? IndividualCreditorIndicator { get => _individualCreditorIndicator; set => SetField(ref _individualCreditorIndicator, value); } /// <summary> /// Additional Loans Lien Position [URLARALNN17] /// </summary> public StringEnumValue<AdditionalLoanLienPosition> LienPosition { get => _lienPosition; set => SetField(ref _lienPosition, value); } /// <summary> /// Additional Loans Linked Piggyback Indicator [URLARALNN25] /// </summary> [LoanFieldProperty(ReadOnly = true, OptionsJson = "{\"Y\":\"Linked Piggyback Indicator \"}")] public bool? LinkedPiggybackIndicator { get => _linkedPiggybackIndicator; set => SetField(ref _linkedPiggybackIndicator, value); } /// <summary> /// Additional Loans MaximumPILoanAmount [URLARALNN31] /// </summary> public decimal? MaximumPILoanAmount { get => _maximumPILoanAmount; set => SetField(ref _maximumPILoanAmount, value); } /// <summary> /// Additional Loans : MaximumPINoteRate [URLARALNN29] /// </summary> public decimal? MaximumPINoteRate { get => _maximumPINoteRate; set => SetField(ref _maximumPINoteRate, value); } /// <summary> /// Additional Loans MaximumPITerm [URLARALNN30] /// </summary> public int? MaximumPITerm { get => _maximumPITerm; set => SetField(ref _maximumPITerm, value); } /// <summary> /// Additional Loans Maximum Principal and Interest within 5 Years [URLARALNN19] /// </summary> public decimal? MaximumPrincipalAndInterestIn5Years { get => _maximumPrincipalAndInterestIn5Years; set => SetField(ref _maximumPrincipalAndInterestIn5Years, value); } /// <summary> /// Additional Loans MonthlyPILoanAmount [URLARALNN28] /// </summary> public decimal? MonthlyPILoanAmount { get => _monthlyPILoanAmount; set => SetField(ref _monthlyPILoanAmount, value); } /// <summary> /// Additional Loans calculator : MonthlyPINoteRate [URLARALNN26] /// </summary> public decimal? MonthlyPINoteRate { get => _monthlyPINoteRate; set => SetField(ref _monthlyPINoteRate, value); } /// <summary> /// Additional Loans MonthlyPITerm [URLARALNN27] /// </summary> public int? MonthlyPITerm { get => _monthlyPITerm; set => SetField(ref _monthlyPITerm, value); } /// <summary> /// Additional Loans Monthly Principal and Interest [URLARALNN18] /// </summary> public decimal? MonthlyPrincipalAndInterest { get => _monthlyPrincipalAndInterest; set => SetField(ref _monthlyPrincipalAndInterest, value); } /// <summary> /// Additional Loans Payment Deferred First Five Years [URLARALNN23] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Payment Deferred for First Five Years\"}")] public bool? PaymentDeferredFirstFiveYears { get => _paymentDeferredFirstFiveYears; set => SetField(ref _paymentDeferredFirstFiveYears, value); } /// <summary> /// Depository Print - See Attached Authorization [URLARALNN15] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Print \\\"See attached borrower's authorization\\\" on signature line.\"}")] public bool? PrintAttachmentIndicator { get => _printAttachmentIndicator; set => SetField(ref _printAttachmentIndicator, value); } /// <summary> /// Depository Print User Job Title [URLARALNN64] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Print user's job title\"}")] public bool? PrintUserJobTitleIndicator { get => _printUserJobTitleIndicator; set => SetField(ref _printUserJobTitleIndicator, value); } /// <summary> /// Depository Print User Name as Title [URLARALNN12] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Print user's name as title\"}")] public bool? PrintUserNameIndicator { get => _printUserNameIndicator; set => SetField(ref _printUserNameIndicator, value); } /// <summary> /// Source of Funds [URLARALNN33] /// </summary> public StringEnumValue<SourceOfFunds> SourceOfFunds { get => _sourceOfFunds; set => SetField(ref _sourceOfFunds, value); } /// <summary> /// Depository From Title [URLARALNN11] /// </summary> public string? Title { get => _title; set => SetField(ref _title, value); } /// <summary> /// Depository From Fax [URLARALNN14] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? TitleFax { get => _titleFax; set => SetField(ref _titleFax, value); } /// <summary> /// Depository From Phone [URLARALNN13] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? TitlePhone { get => _titlePhone; set => SetField(ref _titlePhone, value); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using Microsoft.Graphics.Canvas.Geometry; using Microsoft.Graphics.Canvas.Text; using Microsoft.Graphics.Canvas.UI.Xaml; using System; using System.Collections.Generic; using System.Numerics; using Windows.Foundation; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Input; namespace ExampleGallery { public sealed partial class ArcOptions : UserControl { // Which of the two CanvasPathBuilder.AddArc method overloads are we currently demonstrating? public enum AddArcOverload { AroundEllipse, PointToPoint, }; public AddArcOverload CurrentOverload { get; set; } // Parameters used by both AddArc overloads. Vector2[] arcPoints = new Vector2[2]; // Parameters used by AddArcOverload.AroundEllipse. public float ArcStartAngle { get; set; } public float ArcSweepAngle { get; set; } // Parameters used by AddArcOverload.PointToPoint. public float ArcRadiusX { get; set; } public float ArcRadiusY { get; set; } public float ArcRotation { get; set; } public CanvasSweepDirection ArcSweepDirection { get; set; } public CanvasArcSize ArcSize { get; set; } // Enum metadata for XAML databinding. public List<AddArcOverload> AddArcOverloads { get { return Utils.GetEnumAsList<AddArcOverload>(); } } public List<CanvasSweepDirection> SweepDirections { get { return Utils.GetEnumAsList<CanvasSweepDirection>(); } } public List<CanvasArcSize> ArcSizes { get { return Utils.GetEnumAsList<CanvasArcSize>(); } } // Pointer input state. int? activeDrag; Vector2 dragOffset; const float hitTestRadius = 32; // Rendering settings for displaying the arc. const float strokeWidth = 12; CanvasStrokeStyle strokeStyle = new CanvasStrokeStyle() { StartCap = CanvasCapStyle.Round, EndCap = CanvasCapStyle.Triangle, }; CanvasTextFormat textFormat = new CanvasTextFormat() { HorizontalAlignment = CanvasHorizontalAlignment.Center, VerticalAlignment = CanvasVerticalAlignment.Center, }; public ArcOptions() { this.InitializeComponent(); } void Canvas_Loaded(object sender, RoutedEventArgs e) { arcPoints[0] = new Vector2(40); arcPoints[1] = Vector2.Min(new Vector2(480, 320), canvas.Size.ToVector2() - new Vector2(40)); ArcStartAngle = 205; ArcSweepAngle = -165; ArcRadiusX = ArcRadiusY = Vector2.Distance(arcPoints[0], arcPoints[1]); } void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args) { var ds = args.DrawingSession; var centerPoint = (arcPoints[0] + arcPoints[1]) / 2; // Draw the end point markers. if (!ThumbnailGenerator.IsDrawingThumbnail) { for (int i = 0; i < 2; i++) { ds.DrawCircle(arcPoints[i], hitTestRadius, (i == activeDrag) ? Colors.White : Colors.Gray); } } switch (CurrentOverload) { case AddArcOverload.AroundEllipse: // Compute positions. var ellipseRadius = (arcPoints[1] - arcPoints[0]) / 2; ellipseRadius.X = Math.Abs(ellipseRadius.X); ellipseRadius.Y = Math.Abs(ellipseRadius.Y); float startAngle = Utils.DegreesToRadians(ArcStartAngle); float sweepAngle = Utils.DegreesToRadians(ArcSweepAngle); var startPoint = centerPoint + Vector2.Transform(Vector2.UnitX, Matrix3x2.CreateRotation(startAngle)) * ellipseRadius; // Draw the bounding rectangle. if (!ThumbnailGenerator.IsDrawingThumbnail) { ds.DrawRectangle(new Rect(arcPoints[0].ToPoint(), arcPoints[1].ToPoint()), Color.FromArgb(255, 64, 64, 64)); } // Draw the arc. using (var builder = new CanvasPathBuilder(sender)) { builder.BeginFigure(startPoint); builder.AddArc(centerPoint, ellipseRadius.X, ellipseRadius.Y, startAngle, sweepAngle); builder.EndFigure(CanvasFigureLoop.Open); using (var geometry = CanvasGeometry.CreatePath(builder)) { ds.DrawGeometry(geometry, Colors.Yellow, strokeWidth, strokeStyle); } } break; case AddArcOverload.PointToPoint: // Display a warning if this is an invalid arc configuration. bool isRadiusTooSmall = IsArcRadiusTooSmall(); if (isRadiusTooSmall) { ds.DrawText("Radius is less than the\ndistance between the\nstart and end points", centerPoint, Colors.Red, textFormat); } // Draw the arc. using (var builder = new CanvasPathBuilder(sender)) { builder.BeginFigure(arcPoints[0]); builder.AddArc(arcPoints[1], ArcRadiusX, ArcRadiusY, Utils.DegreesToRadians(ArcRotation), ArcSweepDirection, ArcSize); builder.EndFigure(CanvasFigureLoop.Open); using (var geometry = CanvasGeometry.CreatePath(builder)) { ds.DrawGeometry(geometry, isRadiusTooSmall ? Colors.Red : Colors.Yellow, strokeWidth, strokeStyle); } } break; } } bool IsArcRadiusTooSmall() { // Get the distance between the arc start/end points. Vector2 arc = arcPoints[1] - arcPoints[0]; // Compensate for any ellipse rotation. arc = Vector2.Transform(arc, Matrix3x2.CreateRotation(-Utils.DegreesToRadians(ArcRotation))); // Normalize to a unit circle. arc /= new Vector2(ArcRadiusX, ArcRadiusY); // If the length is greater than 2, there is no possible way to fit an arc of // the specified radius between the specified endpoints. D2D will compensate // by scaling up the radius, but the result may not be what was intended. return arc.Length() > 2; } void canvas_PointerPressed(object sender, PointerRoutedEventArgs e) { var pointerPos = e.GetCurrentPoint(canvas).Position.ToVector2(); float[] targetDistances = { Vector2.Distance(pointerPos, arcPoints[0]), Vector2.Distance(pointerPos, arcPoints[1]), }; int closestTarget = (targetDistances[0] < targetDistances[1]) ? 0 : 1; if (targetDistances[closestTarget] <= hitTestRadius) { activeDrag = closestTarget; dragOffset = pointerPos - arcPoints[closestTarget]; canvas.Invalidate(); } } void canvas_PointerReleased(object sender, PointerRoutedEventArgs e) { if (activeDrag.HasValue) { activeDrag = null; canvas.Invalidate(); } } void canvas_PointerMoved(object sender, PointerRoutedEventArgs e) { if (activeDrag.HasValue) { var pointerPos = e.GetCurrentPoint(canvas).Position.ToVector2(); arcPoints[activeDrag.Value] = pointerPos - dragOffset; canvas.Invalidate(); } } void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { canvas.Invalidate(); } void Slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { canvas.Invalidate(); } void Overload_SelectionChanged(object sender, SelectionChangedEventArgs e) { aroundEllipseControls.Visibility = (CurrentOverload == AddArcOverload.AroundEllipse) ? Visibility.Visible : Visibility.Collapsed; pointToPointControls.Visibility = (CurrentOverload == AddArcOverload.PointToPoint) ? Visibility.Visible : Visibility.Collapsed; canvas.Invalidate(); } private void control_Unloaded(object sender, RoutedEventArgs e) { // Explicitly remove references to allow the Win2D controls to get garbage collected canvas.RemoveFromVisualTree(); canvas = null; } } }
using Avalonia.Controls; using Avalonia.Controls.Shapes; using Avalonia.Layout; using Avalonia.Media; using Xunit; #if AVALONIA_SKIA namespace Avalonia.Skia.RenderTests #else namespace Avalonia.Direct2D1.RenderTests.Shapes #endif { using System.Threading.Tasks; using Avalonia.Collections; public class PathTests : TestBase { public PathTests() : base(@"Shapes\Path") { } [Fact] public async Task Line_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M 10,190 L 190,10 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Line_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M10,190 l190,-190 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task HorizontalLine_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,100 H10 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task HorizontalLine_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,100 h-180 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task VerticalLine_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M100,190 V10 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task VerticalLine_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M100,190 V-180 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task CubicBezier_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,0 C10,10 190,190 10,190 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task CubicBezier_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,0 c-180,10 0,190 -180,190 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Arc_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,100 A90,90 0 1,0 10,100 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Arc_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,100 a90,90 0 1,0 -180,0 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_100px_Triangle_Centered() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 2, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M 0,100 L 100,100 50,0 Z"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_Tick_Scaled() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 2, Stretch = Stretch.Uniform, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M 1145.607177734375,430 C1145.607177734375,430 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1138,434.5538330078125 1138,434.5538330078125 1138,434.5538330078125 1141.482177734375,438 1141.482177734375,438 1141.482177734375,438 1141.96875,437.9375 1141.96875,437.9375 1141.96875,437.9375 1147,431.34619140625 1147,431.34619140625 1147,431.34619140625 1145.607177734375,430 1145.607177734375,430 z"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_Tick_Scaled_Stroke_8px() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 8, Stretch = Stretch.Uniform, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M 1145.607177734375,430 C1145.607177734375,430 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1138,434.5538330078125 1138,434.5538330078125 1138,434.5538330078125 1141.482177734375,438 1141.482177734375,438 1141.482177734375,438 1141.96875,437.9375 1141.96875,437.9375 1141.96875,437.9375 1147,431.34619140625 1147,431.34619140625 1147,431.34619140625 1145.607177734375,430 1145.607177734375,430 z"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_Expander_With_Border() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Border { BorderBrush = Brushes.Red, BorderThickness = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Child = new Path { Fill = Brushes.Black, Stroke = Brushes.Black, StrokeThickness = 1, Stretch = Stretch.Uniform, Data = StreamGeometry.Parse("M 0 2 L 4 6 L 0 10 Z"), } } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_With_PenLineCap() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Black, StrokeThickness = 10, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, StrokeDashArray = new AvaloniaList<double>(3, 1), StrokeLineCap = PenLineCap.Round, Data = StreamGeometry.Parse("M 20,20 L 180,180"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_With_Rotated_Geometry() { var target = new Border { Width = 200, Height = 200, Background = Brushes.White, Child = new Path { Fill = Brushes.Red, Data = new RectangleGeometry { Rect = new Rect(50, 50, 100, 100), Transform = new RotateTransform(45), } } }; await RenderToFile(target); CompareImages(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type int with 2 columns and 2 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct imat2 : IReadOnlyList<int>, IEquatable<imat2> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public int m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public int m01; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public int m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public int m11; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public imat2(int m00, int m01, int m10, int m11) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; } /// <summary> /// Constructs this matrix from a imat2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(imat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a imat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(imat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a imat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(imat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a imat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(imat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a imat3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(imat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a imat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(imat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a imat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(imat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a imat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(imat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a imat4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(imat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2(ivec2 c0, ivec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public int[,] Values => new[,] { { m00, m01 }, { m10, m11 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public int[] Values1D => new[] { m00, m01, m10, m11 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public ivec2 Column0 { get { return new ivec2(m00, m01); } set { m00 = value.x; m01 = value.y; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public ivec2 Column1 { get { return new ivec2(m10, m11); } set { m10 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public ivec2 Row0 { get { return new ivec2(m00, m10); } set { m00 = value.x; m10 = value.y; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public ivec2 Row1 { get { return new ivec2(m01, m11); } set { m01 = value.x; m11 = value.y; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static imat2 Zero { get; } = new imat2(0, 0, 0, 0); /// <summary> /// Predefined all-ones matrix /// </summary> public static imat2 Ones { get; } = new imat2(1, 1, 1, 1); /// <summary> /// Predefined identity matrix /// </summary> public static imat2 Identity { get; } = new imat2(1, 0, 0, 1); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static imat2 AllMaxValue { get; } = new imat2(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static imat2 DiagonalMaxValue { get; } = new imat2(int.MaxValue, 0, 0, int.MaxValue); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static imat2 AllMinValue { get; } = new imat2(int.MinValue, int.MinValue, int.MinValue, int.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static imat2 DiagonalMinValue { get; } = new imat2(int.MinValue, 0, 0, int.MinValue); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<int> GetEnumerator() { yield return m00; yield return m01; yield return m10; yield return m11; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (2 x 2 = 4). /// </summary> public int Count => 4; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public int this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m10; case 3: return m11; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m10 = value; break; case 3: this.m11 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public int this[int col, int row] { get { return this[col * 2 + row]; } set { this[col * 2 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(imat2 rhs) => ((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is imat2 && Equals((imat2) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(imat2 lhs, imat2 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(imat2 lhs, imat2 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public imat2 Transposed => new imat2(m00, m10, m01, m11); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public int MinElement => Math.Min(Math.Min(Math.Min(m00, m01), m10), m11); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public int MaxElement => Math.Max(Math.Max(Math.Max(m00, m01), m10), m11); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public float Length => (float)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public float LengthSqr => ((m00*m00 + m01*m01) + (m10*m10 + m11*m11)); /// <summary> /// Returns the sum of all fields. /// </summary> public int Sum => ((m00 + m01) + (m10 + m11)); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public float Norm => (float)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public float Norm1 => ((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m10) + Math.Abs(m11))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public float Norm2 => (float)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public int NormMax => Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m10)), Math.Abs(m11)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow(((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))), 1 / p); /// <summary> /// Returns determinant of this matrix. /// </summary> public int Determinant => m00 * m11 - m10 * m01; /// <summary> /// Returns the adjunct of this matrix. /// </summary> public imat2 Adjugate => new imat2(m11, -m01, -m10, m00); /// <summary> /// Returns the inverse of this matrix (use with caution). /// </summary> public imat2 Inverse => Adjugate / Determinant; /// <summary> /// Executes a matrix-matrix-multiplication imat2 * imat2 -> imat2. /// </summary> public static imat2 operator*(imat2 lhs, imat2 rhs) => new imat2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11)); /// <summary> /// Executes a matrix-matrix-multiplication imat2 * imat3x2 -> imat3x2. /// </summary> public static imat3x2 operator*(imat2 lhs, imat3x2 rhs) => new imat3x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21)); /// <summary> /// Executes a matrix-matrix-multiplication imat2 * imat4x2 -> imat4x2. /// </summary> public static imat4x2 operator*(imat2 lhs, imat4x2 rhs) => new imat4x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static ivec2 operator*(imat2 m, ivec2 v) => new ivec2((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y)); /// <summary> /// Executes a matrix-matrix-divison A / B == A * B^-1 (use with caution). /// </summary> public static imat2 operator/(imat2 A, imat2 B) => A * B.Inverse; /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static imat2 CompMul(imat2 A, imat2 B) => new imat2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static imat2 CompDiv(imat2 A, imat2 B) => new imat2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11); /// <summary> /// Executes a component-wise + (add). /// </summary> public static imat2 CompAdd(imat2 A, imat2 B) => new imat2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static imat2 CompSub(imat2 A, imat2 B) => new imat2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11); /// <summary> /// Executes a component-wise + (add). /// </summary> public static imat2 operator+(imat2 lhs, imat2 rhs) => new imat2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static imat2 operator+(imat2 lhs, int rhs) => new imat2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static imat2 operator+(int lhs, imat2 rhs) => new imat2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static imat2 operator-(imat2 lhs, imat2 rhs) => new imat2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static imat2 operator-(imat2 lhs, int rhs) => new imat2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static imat2 operator-(int lhs, imat2 rhs) => new imat2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static imat2 operator/(imat2 lhs, int rhs) => new imat2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static imat2 operator/(int lhs, imat2 rhs) => new imat2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static imat2 operator*(imat2 lhs, int rhs) => new imat2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static imat2 operator*(int lhs, imat2 rhs) => new imat2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11); /// <summary> /// Executes a component-wise % (modulo). /// </summary> public static imat2 operator%(imat2 lhs, imat2 rhs) => new imat2(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static imat2 operator%(imat2 lhs, int rhs) => new imat2(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m10 % rhs, lhs.m11 % rhs); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static imat2 operator%(int lhs, imat2 rhs) => new imat2(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m10, lhs % rhs.m11); /// <summary> /// Executes a component-wise ^ (xor). /// </summary> public static imat2 operator^(imat2 lhs, imat2 rhs) => new imat2(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static imat2 operator^(imat2 lhs, int rhs) => new imat2(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static imat2 operator^(int lhs, imat2 rhs) => new imat2(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m10, lhs ^ rhs.m11); /// <summary> /// Executes a component-wise | (bitwise-or). /// </summary> public static imat2 operator|(imat2 lhs, imat2 rhs) => new imat2(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static imat2 operator|(imat2 lhs, int rhs) => new imat2(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m10 | rhs, lhs.m11 | rhs); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static imat2 operator|(int lhs, imat2 rhs) => new imat2(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m10, lhs | rhs.m11); /// <summary> /// Executes a component-wise &amp; (bitwise-and). /// </summary> public static imat2 operator&(imat2 lhs, imat2 rhs) => new imat2(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static imat2 operator&(imat2 lhs, int rhs) => new imat2(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m10 & rhs, lhs.m11 & rhs); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static imat2 operator&(int lhs, imat2 rhs) => new imat2(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m10, lhs & rhs.m11); /// <summary> /// Executes a component-wise left-shift with a scalar. /// </summary> public static imat2 operator<<(imat2 lhs, int rhs) => new imat2(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m10 << rhs, lhs.m11 << rhs); /// <summary> /// Executes a component-wise right-shift with a scalar. /// </summary> public static imat2 operator>>(imat2 lhs, int rhs) => new imat2(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat2 operator<(imat2 lhs, imat2 rhs) => new bmat2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2 operator<(imat2 lhs, int rhs) => new bmat2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2 operator<(int lhs, imat2 rhs) => new bmat2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat2 operator<=(imat2 lhs, imat2 rhs) => new bmat2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2 operator<=(imat2 lhs, int rhs) => new bmat2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2 operator<=(int lhs, imat2 rhs) => new bmat2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat2 operator>(imat2 lhs, imat2 rhs) => new bmat2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2 operator>(imat2 lhs, int rhs) => new bmat2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2 operator>(int lhs, imat2 rhs) => new bmat2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat2 operator>=(imat2 lhs, imat2 rhs) => new bmat2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2 operator>=(imat2 lhs, int rhs) => new bmat2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2 operator>=(int lhs, imat2 rhs) => new bmat2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11); } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Egl { /// <summary> /// [EGL] Value of EGL_NO_OUTPUT_LAYER_EXT symbol. /// </summary> [RequiredByFeature("EGL_EXT_output_base")] public const int NO_OUTPUT_LAYER_EXT = 0; /// <summary> /// [EGL] Value of EGL_NO_OUTPUT_PORT_EXT symbol. /// </summary> [RequiredByFeature("EGL_EXT_output_base")] public const int NO_OUTPUT_PORT_EXT = 0; /// <summary> /// [EGL] Value of EGL_BAD_OUTPUT_LAYER_EXT symbol. /// </summary> [RequiredByFeature("EGL_EXT_output_base")] public const int BAD_OUTPUT_LAYER_EXT = 0x322D; /// <summary> /// [EGL] Value of EGL_BAD_OUTPUT_PORT_EXT symbol. /// </summary> [RequiredByFeature("EGL_EXT_output_base")] public const int BAD_OUTPUT_PORT_EXT = 0x322E; /// <summary> /// [EGL] Value of EGL_SWAP_INTERVAL_EXT symbol. /// </summary> [RequiredByFeature("EGL_EXT_output_base")] public const int SWAP_INTERVAL_EXT = 0x322F; /// <summary> /// [EGL] eglGetOutputLayersEXT: Binding for eglGetOutputLayersEXT. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attrib_list"> /// A <see cref="T:IntPtr[]"/>. /// </param> /// <param name="layers"> /// A <see cref="T:IntPtr[]"/>. /// </param> /// <param name="max_layers"> /// A <see cref="T:int"/>. /// </param> /// <param name="num_layers"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("EGL_EXT_output_base")] public static bool GetOutputLayersEXT(IntPtr dpy, IntPtr[] attrib_list, [Out] IntPtr[] layers, int max_layers, [Out] int[] num_layers) { bool retValue; unsafe { fixed (IntPtr* p_attrib_list = attrib_list) fixed (IntPtr* p_layers = layers) fixed (int* p_num_layers = num_layers) { Debug.Assert(Delegates.peglGetOutputLayersEXT != null, "peglGetOutputLayersEXT not implemented"); retValue = Delegates.peglGetOutputLayersEXT(dpy, p_attrib_list, p_layers, max_layers, p_num_layers); LogCommand("eglGetOutputLayersEXT", retValue, dpy, attrib_list, layers, max_layers, num_layers ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglGetOutputPortsEXT: Binding for eglGetOutputPortsEXT. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attrib_list"> /// A <see cref="T:IntPtr[]"/>. /// </param> /// <param name="ports"> /// A <see cref="T:IntPtr[]"/>. /// </param> /// <param name="max_ports"> /// A <see cref="T:int"/>. /// </param> /// <param name="num_ports"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("EGL_EXT_output_base")] public static bool GetOutputPortsEXT(IntPtr dpy, IntPtr[] attrib_list, [Out] IntPtr[] ports, int max_ports, [Out] int[] num_ports) { bool retValue; unsafe { fixed (IntPtr* p_attrib_list = attrib_list) fixed (IntPtr* p_ports = ports) fixed (int* p_num_ports = num_ports) { Debug.Assert(Delegates.peglGetOutputPortsEXT != null, "peglGetOutputPortsEXT not implemented"); retValue = Delegates.peglGetOutputPortsEXT(dpy, p_attrib_list, p_ports, max_ports, p_num_ports); LogCommand("eglGetOutputPortsEXT", retValue, dpy, attrib_list, ports, max_ports, num_ports ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglOutputLayerAttribEXT: Binding for eglOutputLayerAttribEXT. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="layer"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attribute"> /// A <see cref="T:int"/>. /// </param> /// <param name="value"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("EGL_EXT_output_base")] public static bool OutputLayerAttribEXT(IntPtr dpy, IntPtr layer, int attribute, IntPtr value) { bool retValue; Debug.Assert(Delegates.peglOutputLayerAttribEXT != null, "peglOutputLayerAttribEXT not implemented"); retValue = Delegates.peglOutputLayerAttribEXT(dpy, layer, attribute, value); LogCommand("eglOutputLayerAttribEXT", retValue, dpy, layer, attribute, value ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglQueryOutputLayerAttribEXT: Binding for eglQueryOutputLayerAttribEXT. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="layer"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attribute"> /// A <see cref="T:int"/>. /// </param> /// <param name="value"> /// A <see cref="T:IntPtr[]"/>. /// </param> [RequiredByFeature("EGL_EXT_output_base")] public static bool QueryOutputLayerAttribEXT(IntPtr dpy, IntPtr layer, int attribute, IntPtr[] value) { bool retValue; unsafe { fixed (IntPtr* p_value = value) { Debug.Assert(Delegates.peglQueryOutputLayerAttribEXT != null, "peglQueryOutputLayerAttribEXT not implemented"); retValue = Delegates.peglQueryOutputLayerAttribEXT(dpy, layer, attribute, p_value); LogCommand("eglQueryOutputLayerAttribEXT", retValue, dpy, layer, attribute, value ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglQueryOutputLayerStringEXT: Binding for eglQueryOutputLayerStringEXT. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="layer"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="name"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("EGL_EXT_output_base")] public static string QueryOutputLayerStringEXT(IntPtr dpy, IntPtr layer, int name) { IntPtr retValue; Debug.Assert(Delegates.peglQueryOutputLayerStringEXT != null, "peglQueryOutputLayerStringEXT not implemented"); retValue = Delegates.peglQueryOutputLayerStringEXT(dpy, layer, name); LogCommand("eglQueryOutputLayerStringEXT", PtrToString(retValue), dpy, layer, name ); DebugCheckErrors(retValue); return (PtrToString(retValue)); } /// <summary> /// [EGL] eglOutputPortAttribEXT: Binding for eglOutputPortAttribEXT. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="port"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attribute"> /// A <see cref="T:int"/>. /// </param> /// <param name="value"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("EGL_EXT_output_base")] public static bool OutputPortAttribEXT(IntPtr dpy, IntPtr port, int attribute, IntPtr value) { bool retValue; Debug.Assert(Delegates.peglOutputPortAttribEXT != null, "peglOutputPortAttribEXT not implemented"); retValue = Delegates.peglOutputPortAttribEXT(dpy, port, attribute, value); LogCommand("eglOutputPortAttribEXT", retValue, dpy, port, attribute, value ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglQueryOutputPortAttribEXT: Binding for eglQueryOutputPortAttribEXT. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="port"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attribute"> /// A <see cref="T:int"/>. /// </param> /// <param name="value"> /// A <see cref="T:IntPtr[]"/>. /// </param> [RequiredByFeature("EGL_EXT_output_base")] public static bool QueryOutputPortAttribEXT(IntPtr dpy, IntPtr port, int attribute, IntPtr[] value) { bool retValue; unsafe { fixed (IntPtr* p_value = value) { Debug.Assert(Delegates.peglQueryOutputPortAttribEXT != null, "peglQueryOutputPortAttribEXT not implemented"); retValue = Delegates.peglQueryOutputPortAttribEXT(dpy, port, attribute, p_value); LogCommand("eglQueryOutputPortAttribEXT", retValue, dpy, port, attribute, value ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglQueryOutputPortStringEXT: Binding for eglQueryOutputPortStringEXT. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="port"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="name"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("EGL_EXT_output_base")] public static string QueryOutputPortStringEXT(IntPtr dpy, IntPtr port, int name) { IntPtr retValue; Debug.Assert(Delegates.peglQueryOutputPortStringEXT != null, "peglQueryOutputPortStringEXT not implemented"); retValue = Delegates.peglQueryOutputPortStringEXT(dpy, port, name); LogCommand("eglQueryOutputPortStringEXT", PtrToString(retValue), dpy, port, name ); DebugCheckErrors(retValue); return (PtrToString(retValue)); } internal static unsafe partial class Delegates { [RequiredByFeature("EGL_EXT_output_base")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglGetOutputLayersEXT(IntPtr dpy, IntPtr* attrib_list, IntPtr* layers, int max_layers, int* num_layers); [RequiredByFeature("EGL_EXT_output_base")] internal static eglGetOutputLayersEXT peglGetOutputLayersEXT; [RequiredByFeature("EGL_EXT_output_base")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglGetOutputPortsEXT(IntPtr dpy, IntPtr* attrib_list, IntPtr* ports, int max_ports, int* num_ports); [RequiredByFeature("EGL_EXT_output_base")] internal static eglGetOutputPortsEXT peglGetOutputPortsEXT; [RequiredByFeature("EGL_EXT_output_base")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglOutputLayerAttribEXT(IntPtr dpy, IntPtr layer, int attribute, IntPtr value); [RequiredByFeature("EGL_EXT_output_base")] internal static eglOutputLayerAttribEXT peglOutputLayerAttribEXT; [RequiredByFeature("EGL_EXT_output_base")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglQueryOutputLayerAttribEXT(IntPtr dpy, IntPtr layer, int attribute, IntPtr* value); [RequiredByFeature("EGL_EXT_output_base")] internal static eglQueryOutputLayerAttribEXT peglQueryOutputLayerAttribEXT; [RequiredByFeature("EGL_EXT_output_base")] [SuppressUnmanagedCodeSecurity] internal delegate IntPtr eglQueryOutputLayerStringEXT(IntPtr dpy, IntPtr layer, int name); [RequiredByFeature("EGL_EXT_output_base")] internal static eglQueryOutputLayerStringEXT peglQueryOutputLayerStringEXT; [RequiredByFeature("EGL_EXT_output_base")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglOutputPortAttribEXT(IntPtr dpy, IntPtr port, int attribute, IntPtr value); [RequiredByFeature("EGL_EXT_output_base")] internal static eglOutputPortAttribEXT peglOutputPortAttribEXT; [RequiredByFeature("EGL_EXT_output_base")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglQueryOutputPortAttribEXT(IntPtr dpy, IntPtr port, int attribute, IntPtr* value); [RequiredByFeature("EGL_EXT_output_base")] internal static eglQueryOutputPortAttribEXT peglQueryOutputPortAttribEXT; [RequiredByFeature("EGL_EXT_output_base")] [SuppressUnmanagedCodeSecurity] internal delegate IntPtr eglQueryOutputPortStringEXT(IntPtr dpy, IntPtr port, int name); [RequiredByFeature("EGL_EXT_output_base")] internal static eglQueryOutputPortStringEXT peglQueryOutputPortStringEXT; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Management.Automation.Runspaces; using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation.Host { /// <summary> /// Defines the properties and facilities providing by an application hosting an MSH <see /// cref="System.Management.Automation.Runspaces.Runspace"/>. /// </summary> /// <remarks> /// A hosting application derives from this class and /// overrides the abstract methods and properties. The hosting application creates an instance of its derived class and /// passes it to the <see cref="System.Management.Automation.Runspaces.RunspaceFactory"/> CreateRunspace method. /// /// From the moment that the instance of the derived class (the "host class") is passed to CreateRunspace, the MSH runtime /// can call any of the methods of that class. The instance must not be destroyed until after the Runspace is closed. /// /// There is a 1:1 relationship between the instance of the host class and the Runspace instance to which it is passed. In /// other words, it is not legal to pass the same instance of the host class to more than one call to CreateRunspace. (It /// is perfectly legal to call CreateRunspace more than once, as long as each call is supplied a unique instance of the host /// class.) /// /// Methods of the host class can be called by the Runspace or any cmdlet or script executed in that Runspace in any order /// and from any thread. It is the responsibility of the hosting application to define the host class methods in a /// threadsafe fashion. An implementation of the host class should not depend on method execution order. /// /// The instance of the host class that is passed to a Runspace is exposed by the Runspace to the cmdlets, scripts, and /// providers that are executed in that Runspace. Scripts access the host class via the $Host built-in variable. Cmdlets /// access the host via the Host property of the Cmdlet base class. /// </remarks> /// <seealso cref="System.Management.Automation.Runspaces.Runspace"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface"/> /// <seealso cref="System.Management.Automation.Host.PSHostRawUserInterface"/> public abstract class PSHost { /// <summary> /// The powershell spec states that 128 is the maximum nesting depth. /// </summary> internal const int MaximumNestedPromptLevel = 128; internal static bool IsStdOutputRedirected; /// <summary> /// Protected constructor which does nothing. Provided per .Net design guidelines section 4.3.1. /// </summary> protected PSHost() { // do nothing } /// <summary> /// Gets the hosting application's identification in some user-friendly fashion. This name can be referenced by scripts and cmdlets /// to identify the host that is executing them. The format of the value is not defined, but a short, simple string is /// recommended. /// </summary> /// <remarks> /// In implementing this member, you should return some sort of informative string describing the nature /// your hosting application. For the default console host shipped by Microsoft this is ConsoleHost. /// </remarks> /// <value> /// The name identifier of the hosting application. /// </value> /// <example> /// <MSH> /// if ($Host.Name -ieq "ConsoleHost") { write-host "I'm running in the Console Host" } /// </MSH> /// </example> public abstract string Name { get; } /// <summary> /// Gets the version of the hosting application. This value should remain invariant for a particular build of the /// host. This value may be referenced by scripts and cmdlets. /// </summary> /// <remarks> /// When implementing this member, it should return the product version number for the product /// that is hosting the Monad engine. /// </remarks> /// <value> /// The version number of the hosting application. /// </value> public abstract System.Version Version { get; } /// <summary> /// Gets a GUID that uniquely identifies this instance of the host. The value should remain invariant for the lifetime of /// this instance. /// </summary> public abstract System.Guid InstanceId { get; } /// <summary> /// Gets the hosting application's implementation of the /// <see cref="System.Management.Automation.Host.PSHostUserInterface"/> abstract base class. A host /// that does not want to support user interaction should return null. /// </summary> /// <value> /// A reference to an instance of the hosting application's implementation of a class derived from /// <see cref="System.Management.Automation.Host.PSHostUserInterface"/>, or null to indicate that user /// interaction is not supported. /// </value> /// <remarks> /// The implementation of this routine should return an instance of the appropriate /// implementation of PSHostUserInterface for this application. As an alternative, /// for simple scenarios, just returning null is sufficient. /// </remarks> public abstract System.Management.Automation.Host.PSHostUserInterface UI { get; } /// <summary> /// Gets the host's culture: the culture that the runspace should use to set the CurrentCulture on new threads. /// </summary> /// <value> /// A CultureInfo object representing the host's current culture. Returning null is not allowed. /// </value> /// <remarks> /// The runspace will set the thread current culture to this value each time it starts a pipeline. Thus, cmdlets are /// encouraged to use Thread.CurrentThread.CurrentCulture. /// </remarks> public abstract System.Globalization.CultureInfo CurrentCulture { get; } /// <summary> /// Gets the host's UI culture: the culture that the runspace and cmdlets should use to do resource loading. /// /// The runspace will set the thread current ui culture to this value each time it starts a pipeline. /// </summary> /// <value> /// A CultureInfo object representing the host's current UI culture. Returning null is not allowed. /// </value> public abstract System.Globalization.CultureInfo CurrentUICulture { get; } /// <summary> /// Request by the engine to end the current engine runspace (to shut down and terminate the host's root runspace). /// </summary> /// <remarks> /// This method is called by the engine to request the host shutdown the engine. This is invoked by the exit keyword /// or by any other facility by which a runspace instance wishes to be shut down. /// /// To honor this request, the host should stop accepting and submitting commands to the engine and close the runspace. /// </remarks> /// <param name="exitCode"> /// The exit code accompanying the exit keyword. Typically, after exiting a runspace, a host will also terminate. The /// exitCode parameter can be used to set the host's process exit code. /// </param> public abstract void SetShouldExit(int exitCode); /// <summary> /// Instructs the host to interrupt the currently running pipeline and start a new, "nested" input loop, where an input /// loop is the cycle of prompt, input, execute. /// </summary> /// <remarks> /// Typically called by the engine in response to some user action that suspends the currently executing pipeline, such /// as choosing the "suspend" option of a ConfirmProcessing call. Before calling this method, the engine should set /// various shell variables to the express the state of the interrupted input loop (current pipeline, current object in /// pipeline, depth of nested input loops, etc.) /// /// A non-interactive host may throw a "not implemented" exception here. /// /// If the UI property returns null, the engine should not call this method. /// <!--Was: ExecuteSubShell. "subshell" implies a new child engine, which is not the case here. This is called during the /// interruption of a pipeline to allow nested pipeline(s) to be run as a way to the user to suspend execution while he /// evaluates other commands. It does not create a truly new engine instance with new session state.--> /// </remarks> /// <seealso cref="System.Management.Automation.Host.PSHost.ExitNestedPrompt"/> public abstract void EnterNestedPrompt(); /// <summary> /// Causes the host to end the currently running input loop. If the input loop was created by a prior call to /// EnterNestedPrompt, the enclosing pipeline will be resumed. If the current input loop is the top-most loop, then the /// host will act as though SetShouldExit was called. /// </summary> /// <remarks> /// Typically called by the engine in response to some user action that resumes a suspended pipeline, such as with the /// 'continue-command' intrinsic cmdlet. Before calling this method, the engine should clear out the loop-specific /// variables that were set when the loop was created. /// /// If the UI Property returns a null, the engine should not call this method. /// </remarks> /// <seealso cref="EnterNestedPrompt"/> public abstract void ExitNestedPrompt(); /// <summary> /// Used to allow the host to pass private data through a Runspace to cmdlets running inside that Runspace's /// runspace. The type and nature of that data is entirely defined by the host, but there are some caveats: /// </summary> /// <returns> /// The default implementation returns null. /// </returns> /// <remarks> /// If the host is using an out-of-process Runspace, then the value of this property is serialized when crossing /// that process boundary in the same fashion as any object in a pipeline is serialized when crossing process boundaries. /// In this case, the BaseObject property of the value will be null. /// /// If the host is using an in-process Runspace, then the BaseObject property can be a non-null value a live object. /// No guarantees are made as to the app domain or thread that the BaseObject is accessed if it is accessed in the /// runspace. No guarantees of threadsafety or reentrancy are made. The object set in the BaseObject property of /// the value returned by this method is responsible for ensuring its own threadsafety and re-entrance safety. /// Note that thread(s) accessing that object may not necessarily be the same from one access to the next. /// /// The return value should have value-semantics: that is, changes to the state of the instance returned are not /// reflected across processes. Ex: if a cmdlet reads this property, then changes the state of the result, that /// change will not be visible to the host if the host is in another process. Therefore, the implementation of /// get for this property should always return a unique instance. /// </remarks> public virtual PSObject PrivateData { get { return null; } } /// <summary> /// Called by the engine to notify the host that it is about to execute a "legacy" command line application. A legacy /// application is defined as a console-mode executable that may do one or more of the following: /// . reads from stdin /// . writes to stdout /// . writes to stderr /// . uses any of the win32 console APIs. /// </summary> /// <remarks> /// Notifying the host allows the host to do such things as save off any state that might need to be restored when the /// legacy application terminates, set or remove break handler hooks, redirect stream handles, and so forth. /// /// The engine will always call this method and the NotifyEndApplication method in matching pairs. /// /// The engine may call this method several times in the course of a single pipeline. For instance, the pipeline: /// /// foo.exe | bar-cmdlet | baz.exe /// /// Will result in a sequence of calls similar to the following: /// NotifyBeginApplication - called once when foo.exe is started /// NotifyBeginApplication - called once when baz.exe is started /// NotifyEndApplication - called once when baz.exe terminates /// NotifyEndApplication - called once when foo.exe terminates /// /// Note that the order in which the NotifyEndApplication call follows the corresponding call to NotifyBeginApplication /// with respect to any other call to NotifyBeginApplication is not defined, and should not be depended upon. In other /// words, NotifyBeginApplication may be called several times before NotifyEndApplication is called. The only thing /// that is guaranteed is that there will be an equal number of calls to NotifyEndApplication as to /// NotifyBeginApplication. /// </remarks> /// <seealso cref="System.Management.Automation.Host.PSHost.NotifyEndApplication"/> public abstract void NotifyBeginApplication(); /// <summary> /// Called by the engine to notify the host that the execution of a legacy command has completed. /// </summary> /// <seealso cref="System.Management.Automation.Host.PSHost.NotifyBeginApplication"/> public abstract void NotifyEndApplication(); /// <summary> /// Used by hosting applications to notify PowerShell engine that it is /// being hosted in a console based application and the Pipeline execution /// thread should call SetThreadUILanguage(0). This property is currently /// used by ConsoleHost only and in future releases we may consider /// exposing this publicly. /// </summary> internal bool ShouldSetThreadUILanguageToZero { get; set; } /// <summary> /// This property enables and disables the host debugger if debugging is supported. /// </summary> public virtual bool DebuggerEnabled { get { return false; } set { throw new PSNotImplementedException(); } } } /// <summary> /// This interface needs to be implemented by PSHost objects that want to support the PushRunspace /// and PopRunspace functionality. /// </summary> public interface IHostSupportsInteractiveSession { /// <summary> /// Called by the engine to notify the host that a runspace push has been requested. /// </summary> /// <seealso cref="System.Management.Automation.Host.IHostSupportsInteractiveSession.PushRunspace"/> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "runspace")] void PushRunspace(Runspace runspace); /// <summary> /// Called by the engine to notify the host that a runspace pop has been requested. /// </summary> /// <seealso cref="System.Management.Automation.Host.IHostSupportsInteractiveSession.PopRunspace"/> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] void PopRunspace(); /// <summary> /// True if a runspace is pushed; false otherwise. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] bool IsRunspacePushed { get; } /// <summary> /// Returns the current runspace associated with this host. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] Runspace Runspace { get; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Linq; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; using System.Diagnostics.CodeAnalysis; using AutoRest.Core.Model; using AutoRest.Core.Utilities; using AutoRest.Swagger.Properties; using AutoRest.Core.Validation; using AutoRest.Swagger.Validation; using Newtonsoft.Json; using static AutoRest.Core.Utilities.DependencyInjection; namespace AutoRest.Swagger.Model { /// <summary> /// Describes a single operation determining with this object is mandatory. /// https://github.com/wordnik/swagger-spec/blob/master/versions/2.0.md#parameterObject /// </summary> [Serializable] [Rule(typeof(DefaultMustBeInEnum))] [Rule(typeof(RefsMustNotHaveSiblings))] public abstract class SwaggerObject : SwaggerBase { private string _description; public virtual bool IsRequired { get; set; } /// <summary> /// The type of the parameter. /// </summary> public virtual DataType? Type { get; set; } /// <summary> /// The extending format for the previously mentioned type. /// </summary> [Rule(typeof(ValidFormats))] public virtual string Format { get; set; } /// <summary> /// Returns the KnownFormat of the Format string (provided it matches a KnownFormat) /// Otherwise, returns KnownFormat.none /// </summary> public KnownFormat KnownFormat => KnownFormatExtensions.Parse(Format); /// <summary> /// Describes the type of items in the array. /// </summary> public virtual Schema Items { get; set; } [JsonProperty(PropertyName = "$ref")] public string Reference { get; set; } /// <summary> /// Describes the type of additional properties in the data type. /// </summary> public virtual Schema AdditionalProperties { get; set; } [Rule(typeof(DescriptiveDescriptionRequired))] public virtual string Description { get { return _description; } set { _description = value.StripControlCharacters(); } } /// <summary> /// Determines the format of the array if type array is used. /// </summary> public virtual CollectionFormat CollectionFormat { get; set; } /// <summary> /// Sets a default value to the parameter. /// </summary> public virtual string Default { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MultipleOf { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string Maximum { get; set; } [Rule(typeof(InvalidConstraint))] public virtual bool ExclusiveMaximum { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string Minimum { get; set; } [Rule(typeof(InvalidConstraint))] public virtual bool ExclusiveMinimum { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MaxLength { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MinLength { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string Pattern { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MaxItems { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MinItems { get; set; } [Rule(typeof(InvalidConstraint))] public virtual bool UniqueItems { get; set; } public virtual IList<string> Enum { get; set; } public ObjectBuilder GetBuilder(SwaggerModeler swaggerSpecBuilder) { if (this is SwaggerParameter) { return new ParameterBuilder(this as SwaggerParameter, swaggerSpecBuilder); } if (this is Schema) { return new SchemaBuilder(this as Schema, swaggerSpecBuilder); } return new ObjectBuilder(this, swaggerSpecBuilder); } /// <summary> /// Returns the PrimaryType that the SwaggerObject maps to, given the Type and the KnownFormat. /// /// Note: Since a given language still may interpret the value of the Format after this, /// it is possible the final implemented type may not be the type given here. /// /// This allows languages to not have a specific PrimaryType decided by the Modeler. /// /// For example, if the Type is DataType.String, and the KnownFormat is 'char' the C# generator /// will end up creating a char type in the generated code, but other languages will still /// use string. /// </summary> /// <returns> /// The PrimaryType that best represents this object. /// </returns> public PrimaryType ToType() { switch (Type) { case DataType.String: switch (KnownFormat) { case KnownFormat.date: return New<PrimaryType>(KnownPrimaryType.Date); case KnownFormat.date_time: return New<PrimaryType>(KnownPrimaryType.DateTime); case KnownFormat.date_time_rfc1123: return New<PrimaryType>(KnownPrimaryType.DateTimeRfc1123); case KnownFormat.@byte: return New<PrimaryType>(KnownPrimaryType.ByteArray); case KnownFormat.duration: return New<PrimaryType>(KnownPrimaryType.TimeSpan); case KnownFormat.uuid: return New<PrimaryType>(KnownPrimaryType.Uuid); case KnownFormat.base64url: return New<PrimaryType>(KnownPrimaryType.Base64Url); default: return New<PrimaryType>(KnownPrimaryType.String); } case DataType.Number: switch (KnownFormat) { case KnownFormat.@decimal: return New<PrimaryType>(KnownPrimaryType.Decimal); default: return New<PrimaryType>(KnownPrimaryType.Double); } case DataType.Integer: switch (KnownFormat) { case KnownFormat.int64: return New<PrimaryType>(KnownPrimaryType.Long); case KnownFormat.unixtime: return New<PrimaryType>(KnownPrimaryType.UnixTime); default: return New<PrimaryType>(KnownPrimaryType.Int); } case DataType.Boolean: return New<PrimaryType>(KnownPrimaryType.Boolean); case DataType.Object: case DataType.Array: case null: return New<PrimaryType>(KnownPrimaryType.Object); case DataType.File: return New<PrimaryType>(KnownPrimaryType.Stream); default: throw new NotImplementedException( string.Format(CultureInfo.InvariantCulture, Resources.InvalidTypeInSwaggerSchema, Type)); } } /// <summary> /// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes. /// </summary> /// <param name="context">The modified document context.</param> /// <param name="previous">The original document model.</param> /// <returns>A list of messages from the comparison.</returns> public override IEnumerable<ComparisonMessage> Compare(ComparisonContext context, SwaggerBase previous) { var prior = previous as SwaggerObject; if (prior == null) { throw new ArgumentNullException("priorVersion"); } if (context == null) { throw new ArgumentNullException("context"); } base.Compare(context, previous); if (Reference != null && !Reference.Equals(prior.Reference)) { context.LogBreakingChange(ComparisonMessages.ReferenceRedirection); } if (IsRequired != prior.IsRequired) { if (context.Direction != DataDirection.Response) { if (IsRequired && !prior.IsRequired) { context.LogBreakingChange(ComparisonMessages.RequiredStatusChange); } else { context.LogInfo(ComparisonMessages.RequiredStatusChange); } } } // Are the types the same? if (prior.Type.HasValue != Type.HasValue || (Type.HasValue && prior.Type.Value != Type.Value)) { context.LogBreakingChange(ComparisonMessages.TypeChanged); } // What about the formats? CompareFormats(context, prior); CompareItems(context, prior); if (Default != null && !Default.Equals(prior.Default) || (Default == null && !string.IsNullOrEmpty(prior.Default))) { context.LogBreakingChange(ComparisonMessages.DefaultValueChanged); } if (Type.HasValue && Type.Value == DataType.Array && prior.CollectionFormat != CollectionFormat) { context.LogBreakingChange(ComparisonMessages.ArrayCollectionFormatChanged); } CompareConstraints(context, prior); CompareProperties(context, prior); CompareEnums(context, prior); return context.Messages; } private void CompareEnums(ComparisonContext context, SwaggerObject prior) { if (prior.Enum == null && this.Enum == null) return; bool relaxes = (prior.Enum != null && this.Enum == null); bool constrains = (prior.Enum == null && this.Enum != null); if (!relaxes && !constrains) { // 1. Look for removed elements (constraining). constrains = prior.Enum.Any(str => !this.Enum.Contains(str)); // 2. Look for added elements (relaxing). relaxes = this.Enum.Any(str => !prior.Enum.Contains(str)); } if (context.Direction == DataDirection.Request) { if (constrains) { context.LogBreakingChange(relaxes ? ComparisonMessages.ConstraintChanged : ComparisonMessages.ConstraintIsStronger, "enum"); return; } } else if (context.Direction == DataDirection.Response) { if (relaxes) { context.LogBreakingChange(constrains ? ComparisonMessages.ConstraintChanged : ComparisonMessages.ConstraintIsWeaker, "enum"); return; } } if (relaxes && constrains) context.LogInfo(ComparisonMessages.ConstraintChanged, "enum"); else if (relaxes || constrains) context.LogInfo(relaxes ? ComparisonMessages.ConstraintIsWeaker : ComparisonMessages.ConstraintIsStronger, "enum"); } private void CompareProperties(ComparisonContext context, SwaggerObject prior) { // Additional properties if (prior.AdditionalProperties == null && AdditionalProperties != null) { context.LogBreakingChange(ComparisonMessages.AddedAdditionalProperties); } else if (prior.AdditionalProperties != null && AdditionalProperties == null) { context.LogBreakingChange(ComparisonMessages.RemovedAdditionalProperties); } else if (AdditionalProperties != null) { context.PushProperty("additionalProperties"); AdditionalProperties.Compare(context, prior.AdditionalProperties); context.Pop(); } } protected void CompareFormats(ComparisonContext context, SwaggerObject prior) { if (prior == null) { throw new ArgumentNullException("prior"); } if (context == null) { throw new ArgumentNullException("context"); } if (prior.Format == null && Format != null || prior.Format != null && Format == null || prior.Format != null && Format != null && !prior.Format.Equals(Format)) { context.LogBreakingChange(ComparisonMessages.TypeFormatChanged); } } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "It may look complex, but it really isn't.")] protected void CompareConstraints(ComparisonContext context, SwaggerObject prior) { if (prior == null) { throw new ArgumentNullException("prior"); } if (context == null) { throw new ArgumentNullException("context"); } if ((prior.MultipleOf == null && MultipleOf != null) || (prior.MultipleOf != null && !prior.MultipleOf.Equals(MultipleOf))) { context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "multipleOf"); } if ((prior.Maximum == null && Maximum != null) || (prior.Maximum != null && !prior.Maximum.Equals(Maximum)) || prior.ExclusiveMaximum != ExclusiveMaximum) { // Flag stricter constraints for requests and relaxed constraints for responses. if (prior.ExclusiveMaximum != ExclusiveMaximum || context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "maximum"); else if (context.Direction == DataDirection.Request && Narrows(prior.Maximum, Maximum, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "maximum"); else if (context.Direction == DataDirection.Response && Widens(prior.Maximum, Maximum, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "maximum"); else if (Narrows(prior.Maximum, Maximum, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "maximum"); else if (Widens(prior.Maximum, Maximum, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "maximum"); } if ((prior.Minimum == null && Minimum != null) || (prior.Minimum != null && !prior.Minimum.Equals(Minimum)) || prior.ExclusiveMinimum != ExclusiveMinimum) { // Flag stricter constraints for requests and relaxed constraints for responses. if (prior.ExclusiveMinimum != ExclusiveMinimum || context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "minimum"); else if (context.Direction == DataDirection.Request && Narrows(prior.Minimum, Minimum, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "minimum"); else if (context.Direction == DataDirection.Response && Widens(prior.Minimum, Minimum, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "minimum"); else if (Narrows(prior.Minimum, Minimum, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "minimum"); else if (Widens(prior.Minimum, Minimum, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "minimum"); } if ((prior.MaxLength == null && MaxLength != null) || (prior.MaxLength != null && !prior.MaxLength.Equals(MaxLength))) { // Flag stricter constraints for requests and relaxed constraints for responses. if (context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "maxLength"); else if (context.Direction == DataDirection.Request && Narrows(prior.MaxLength, MaxLength, false)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "maxLength"); else if (context.Direction == DataDirection.Response && Widens(prior.MaxLength, MaxLength, false)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "maxLength"); else if (Narrows(prior.MaxLength, MaxLength, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "maxLength"); else if (Widens(prior.MaxLength, MaxLength, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "maxLength"); } if ((prior.MinLength == null && MinLength != null) || (prior.MinLength != null && !prior.MinLength.Equals(MinLength))) { // Flag stricter constraints for requests and relaxed constraints for responses. if (context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "minLength"); else if (context.Direction == DataDirection.Request && Narrows(prior.MinLength, MinLength, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "minimum"); else if (context.Direction == DataDirection.Response && Widens(prior.MinLength, MinLength, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "minimum"); else if (Narrows(prior.MinLength, MinLength, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "minLength"); else if (Widens(prior.MinLength, MinLength, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "minLength"); } if ((prior.Pattern == null && Pattern != null) || (prior.Pattern != null && !prior.Pattern.Equals(Pattern))) { context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "pattern"); } if ((prior.MaxItems == null && MaxItems != null) || (prior.MaxItems != null && !prior.MaxItems.Equals(MaxItems))) { // Flag stricter constraints for requests and relaxed constraints for responses. if (context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "maxItems"); else if (context.Direction == DataDirection.Request && Narrows(prior.MaxItems, MaxItems, false)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "maxItems"); else if (context.Direction == DataDirection.Response && Widens(prior.MaxItems, MaxItems, false)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "maxItems"); else if (Narrows(prior.MaxItems, MaxItems, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "maxItems"); else if (Widens(prior.MaxItems, MaxItems, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "maxItems"); } if ((prior.MinItems == null && MinItems != null) || (prior.MinItems != null && !prior.MinItems.Equals(MinItems))) { // Flag stricter constraints for requests and relaxed constraints for responses. if (context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "minItems"); else if (context.Direction == DataDirection.Request && Narrows(prior.MinItems, MinItems, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "minItems"); else if (context.Direction == DataDirection.Response && Widens(prior.MinItems, MinItems, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "minItems"); else if (Narrows(prior.MinItems, MinItems, true)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "minItems"); else if (Widens(prior.MinItems, MinItems, true)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "minItems"); } if (prior.UniqueItems != UniqueItems) { context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "uniqueItems"); } } private bool Narrows(string previous, string current, bool isLowerBound) { int p = 0; int c = 0; return int.TryParse(previous, out p) && int.TryParse(current, out c) && (isLowerBound ? (c > p) : (c < p)); } private bool Widens(string previous, string current, bool isLowerBound) { int p = 0; int c = 0; return int.TryParse(previous, out p) && int.TryParse(current, out c) && (isLowerBound ? (c < p) : (c > p)); } protected void CompareItems(ComparisonContext context, SwaggerObject prior) { if (prior == null) { throw new ArgumentNullException("prior"); } if (context == null) { throw new ArgumentNullException("context"); } if (prior.Items != null && Items != null) { context.PushProperty("items"); Items.Compare(context, prior.Items); context.Pop(); } } } }
using System; using System.Collections.ObjectModel; using System.Text.RegularExpressions; using NUnit.Framework; using OpenQA.Selenium.Environment; using System.Text; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { [TestFixture] public class CookieImplementationTest : DriverTestFixture { private Random random = new Random(); private bool isOnAlternativeHostName; private string hostname; [SetUp] public void GoToSimplePageAndDeleteCookies() { GotoValidDomainAndClearCookies("animals"); AssertNoCookiesArePresent(); } [Test] [Category("JavaScript")] public void ShouldGetCookieByName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key = string.Format("key_{0}", new Random().Next()); ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key); Cookie cookie = driver.Manage().Cookies.GetCookieNamed(key); Assert.AreEqual("set", cookie.Value); } [Test] [Category("JavaScript")] public void ShouldBeAbleToAddCookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key = GenerateUniqueKey(); string value = "foo"; Cookie cookie = new Cookie(key, value); AssertCookieIsNotPresentWithName(key); driver.Manage().Cookies.AddCookie(cookie); AssertCookieHasValue(key, value); Assert.That(driver.Manage().Cookies.AllCookies.Contains(cookie), "Cookie was not added successfully"); } [Test] public void GetAllCookies() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key1 = GenerateUniqueKey(); string key2 = GenerateUniqueKey(); AssertCookieIsNotPresentWithName(key1); AssertCookieIsNotPresentWithName(key2); ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies; int count = cookies.Count; Cookie one = new Cookie(key1, "value"); Cookie two = new Cookie(key2, "value"); driver.Manage().Cookies.AddCookie(one); driver.Manage().Cookies.AddCookie(two); driver.Url = simpleTestPage; cookies = driver.Manage().Cookies.AllCookies; Assert.AreEqual(count + 2, cookies.Count); Assert.IsTrue(cookies.Contains(one)); Assert.IsTrue(cookies.Contains(two)); } [Test] [Category("JavaScript")] public void DeleteAllCookies() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = 'foo=set';"); AssertSomeCookiesArePresent(); driver.Manage().Cookies.DeleteAllCookies(); AssertNoCookiesArePresent(); } [Test] [Category("JavaScript")] public void DeleteCookieWithName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key1 = GenerateUniqueKey(); string key2 = GenerateUniqueKey(); ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key1); ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key2); AssertCookieIsPresentWithName(key1); AssertCookieIsPresentWithName(key2); driver.Manage().Cookies.DeleteCookieNamed(key1); AssertCookieIsNotPresentWithName(key1); AssertCookieIsPresentWithName(key2); } [Test] public void ShouldNotDeleteCookiesWithASimilarName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieOneName = "fish"; Cookie cookie1 = new Cookie(cookieOneName, "cod"); Cookie cookie2 = new Cookie(cookieOneName + "x", "earth"); IOptions options = driver.Manage(); AssertCookieIsNotPresentWithName(cookie1.Name); options.Cookies.AddCookie(cookie1); options.Cookies.AddCookie(cookie2); AssertCookieIsPresentWithName(cookie1.Name); options.Cookies.DeleteCookieNamed(cookieOneName); Assert.IsFalse(driver.Manage().Cookies.AllCookies.Contains(cookie1)); Assert.IsTrue(driver.Manage().Cookies.AllCookies.Contains(cookie2)); } [Test] public void AddCookiesWithDifferentPathsThatAreRelatedToOurs() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string basePath = EnvironmentManager.Instance.UrlBuilder.Path; Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals"); Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/"); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); options.Cookies.AddCookie(cookie2); UrlBuilder builder = EnvironmentManager.Instance.UrlBuilder; driver.Url = builder.WhereIs("animals"); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; AssertCookieIsPresentWithName(cookie1.Name); AssertCookieIsPresentWithName(cookie2.Name); driver.Url = builder.WhereIs("simpleTest.html"); AssertCookieIsNotPresentWithName(cookie1.Name); } [Test] [IgnoreBrowser(Browser.Opera)] public void CannotGetCookiesWithPathDifferingOnlyInCase() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieName = "fish"; driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod", "/Common/animals")); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); Assert.IsNull(driver.Manage().Cookies.GetCookieNamed(cookieName)); } [Test] public void ShouldNotGetCookieOnDifferentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieName = "fish"; driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod")); AssertCookieIsPresentWithName(cookieName); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html"); AssertCookieIsNotPresentWithName(cookieName); } [Test] public void ShouldBeAbleToAddToADomainWhichIsRelatedToTheCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } AssertCookieIsNotPresentWithName("name"); Regex replaceRegex = new Regex(".*?\\."); string shorter = replaceRegex.Replace(this.hostname, "", 1); Cookie cookie = new Cookie("name", "value", shorter, "/", GetTimeInTheFuture()); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsPresentWithName("name"); } [Test] [Ignore("Cannot run without creating subdomains in test environment")] public void ShouldNotGetCookiesRelatedToCurrentDomainWithoutLeadingPeriod() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieName = "name"; AssertCookieIsNotPresentWithName(cookieName); Regex replaceRegex = new Regex(".*?\\."); string shorter = replaceRegex.Replace(this.hostname, ".", 1); Cookie cookie = new Cookie(cookieName, "value", shorter, "/", GetTimeInTheFuture()); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsNotPresentWithName(cookieName); } [Test] public void ShouldBeAbleToIncludeLeadingPeriodInDomainName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } AssertCookieIsNotPresentWithName("name"); // Replace the first part of the name with a period Regex replaceRegex = new Regex(".*?\\."); string shorter = replaceRegex.Replace(this.hostname, ".", 1); Cookie cookie = new Cookie("name", "value", shorter, "/", DateTime.Now.AddSeconds(100000)); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsPresentWithName("name"); } [Test] public void ShouldBeAbleToSetDomainToTheCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } Uri url = new Uri(driver.Url); String host = url.Host + ":" + url.Port.ToString(); Cookie cookie1 = new Cookie("fish", "cod", host, "/", null); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); driver.Url = javascriptPage; ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.IsTrue(cookies.Contains(cookie1)); } [Test] public void ShouldWalkThePathToDeleteACookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string basePath = EnvironmentManager.Instance.UrlBuilder.Path; Cookie cookie1 = new Cookie("fish", "cod"); driver.Manage().Cookies.AddCookie(cookie1); int count = driver.Manage().Cookies.AllCookies.Count; driver.Url = childPage; Cookie cookie2 = new Cookie("rodent", "hamster", "/" + basePath + "/child"); driver.Manage().Cookies.AddCookie(cookie2); count = driver.Manage().Cookies.AllCookies.Count; driver.Url = grandchildPage; Cookie cookie3 = new Cookie("dog", "dalmation", "/" + basePath + "/child/grandchild/"); driver.Manage().Cookies.AddCookie(cookie3); count = driver.Manage().Cookies.AllCookies.Count; driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("child/grandchild")); driver.Manage().Cookies.DeleteCookieNamed("rodent"); count = driver.Manage().Cookies.AllCookies.Count; Assert.IsNull(driver.Manage().Cookies.GetCookieNamed("rodent")); ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies; Assert.AreEqual(2, cookies.Count); Assert.IsTrue(cookies.Contains(cookie1)); Assert.IsTrue(cookies.Contains(cookie3)); driver.Manage().Cookies.DeleteAllCookies(); driver.Url = grandchildPage; AssertNoCookiesArePresent(); } [Test] public void ShouldIgnoreThePortNumberOfTheHostWhenSettingTheCookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } Uri uri = new Uri(driver.Url); string host = string.Format("{0}:{1}", uri.Host, uri.Port); string cookieName = "name"; AssertCookieIsNotPresentWithName(cookieName); Cookie cookie = new Cookie(cookieName, "value", host, "/", null); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsPresentWithName(cookieName); } [Test] [IgnoreBrowser(Browser.Opera)] public void CookieEqualityAfterSetAndGet() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); DateTime time = DateTime.Now.AddDays(1); Cookie cookie1 = new Cookie("fish", "cod", null, "/common/animals", time); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Cookie retrievedCookie = null; foreach (Cookie tempCookie in cookies) { if (cookie1.Equals(tempCookie)) { retrievedCookie = tempCookie; break; } } Assert.IsNotNull(retrievedCookie); //Cookie.equals only compares name, domain and path Assert.AreEqual(cookie1, retrievedCookie); } [Test] [IgnoreBrowser(Browser.Opera)] public void ShouldRetainCookieExpiry() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); // DateTime.Now contains milliseconds; the returned cookie expire date // will not. So we need to truncate the milliseconds. DateTime current = DateTime.Now; DateTime expireDate = new DateTime(current.Year, current.Month, current.Day, current.Hour, current.Minute, current.Second, DateTimeKind.Local).AddDays(1); Cookie addCookie = new Cookie("fish", "cod", "/common/animals", expireDate); IOptions options = driver.Manage(); options.Cookies.AddCookie(addCookie); Cookie retrieved = options.Cookies.GetCookieNamed("fish"); Assert.IsNotNull(retrieved); Assert.AreEqual(addCookie.Expiry, retrieved.Expiry, "Cookies are not equal"); } [Test] [IgnoreBrowser(Browser.IE, "Browser does not handle untrusted SSL certificates.")] [IgnoreBrowser(Browser.PhantomJS, "Untested browser")] [IgnoreBrowser(Browser.Safari, "Untested browser")] public void ShouldRetainCookieSecure() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("animals"); ReturnedCookie addedCookie = new ReturnedCookie("fish", "cod", string.Empty, "/common/animals", null, true, false); driver.Manage().Cookies.AddCookie(addedCookie); driver.Navigate().Refresh(); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.IsNotNull(retrieved); Assert.IsTrue(retrieved.Secure); } [Test] [IgnoreBrowser(Browser.Safari)] public void ShouldRetainHttpOnlyFlag() { StringBuilder url = new StringBuilder(EnvironmentManager.Instance.UrlBuilder.WhereElseIs("cookie")); url.Append("?action=add"); url.Append("&name=").Append("fish"); url.Append("&value=").Append("cod"); url.Append("&path=").Append("/common/animals"); url.Append("&httpOnly=").Append("true"); driver.Url = url.ToString(); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.IsNotNull(retrieved); Assert.IsTrue(retrieved.IsHttpOnly); } [Test] public void SettingACookieThatExpiredInThePast() { string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); DateTime expires = DateTime.Now.AddSeconds(-1000); Cookie cookie = new Cookie("expired", "yes", "/common/animals", expires); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie); cookie = options.Cookies.GetCookieNamed("expired"); Assert.IsNull(cookie, "Cookie expired before it was set, so nothing should be returned: " + cookie); } [Test] public void CanSetCookieWithoutOptionalFieldsSet() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key = GenerateUniqueKey(); string value = "foo"; Cookie cookie = new Cookie(key, value); AssertCookieIsNotPresentWithName(key); driver.Manage().Cookies.AddCookie(cookie); AssertCookieHasValue(key, value); } ////////////////////////////////////////////// // Tests unique to the .NET language bindings ////////////////////////////////////////////// [Test] [IgnoreBrowser(Browser.Chrome)] public void CanSetCookiesOnADifferentPathOfTheSameHost() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string basePath = EnvironmentManager.Instance.UrlBuilder.Path; Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals"); Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/galaxy"); IOptions options = driver.Manage(); ReadOnlyCollection<Cookie> count = options.Cookies.AllCookies; options.Cookies.AddCookie(cookie1); options.Cookies.AddCookie(cookie2); string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); driver.Url = url; ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.IsTrue(cookies.Contains(cookie1)); Assert.IsFalse(cookies.Contains(cookie2)); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("galaxy"); cookies = options.Cookies.AllCookies; Assert.IsFalse(cookies.Contains(cookie1)); Assert.IsTrue(cookies.Contains(cookie2)); } [Test] public void ShouldNotBeAbleToSetDomainToSomethingThatIsUnrelatedToTheCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } Cookie cookie1 = new Cookie("fish", "cod"); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html"); driver.Url = url; Assert.IsNull(options.Cookies.GetCookieNamed("fish")); } [Test] public void GetCookieDoesNotRetriveBeyondCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } Cookie cookie1 = new Cookie("fish", "cod"); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); String url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs(""); driver.Url = url; ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.IsFalse(cookies.Contains(cookie1)); } [Test] public void ShouldAddCookieToCurrentDomainAndPath() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Homer", "Simpson", this.hostname, "/" + EnvironmentManager.Instance.UrlBuilder.Path, null); options.Cookies.AddCookie(cookie); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies.Contains(cookie), "Valid cookie was not returned"); } [Test] public void ShouldNotShowCookieAddedToDifferentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { Assert.Ignore("Not on a standard domain for cookies (localhost doesn't count)."); } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Bart", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName + ".com", EnvironmentManager.Instance.UrlBuilder.Path, null); Assert.Throws<WebDriverException>(() => options.Cookies.AddCookie(cookie)); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.IsFalse(cookies.Contains(cookie), "Invalid cookie was returned"); } [Test] public void ShouldNotShowCookieAddedToDifferentPath() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Lisa", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName, "/" + EnvironmentManager.Instance.UrlBuilder.Path + "IDoNotExist", null); options.Cookies.AddCookie(cookie); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.IsFalse(cookies.Contains(cookie), "Invalid cookie was returned"); } // TODO(JimEvans): Disabling this test for now. If your network is using // something like OpenDNS or Google DNS which you may be automatically // redirected to a search page, which will be a valid page and will allow a // cookie to be created. Need to investigate further. // [Test] // [ExpectedException(typeof(InvalidOperationException))] public void ShouldThrowExceptionWhenAddingCookieToNonExistingDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } driver.Url = macbethPage; driver.Url = "doesnot.noireallyreallyreallydontexist.com"; IOptions options = driver.Manage(); Cookie cookie = new Cookie("question", "dunno"); options.Cookies.AddCookie(cookie); } [Test] public void ShouldReturnNullBecauseCookieRetainsExpiry() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); Cookie addCookie = new Cookie("fish", "cod", "/common/animals", DateTime.Now.AddHours(-1)); IOptions options = driver.Manage(); options.Cookies.AddCookie(addCookie); Cookie retrieved = options.Cookies.GetCookieNamed("fish"); Assert.IsNull(retrieved); } [Test] public void ShouldAddCookieToCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Marge", "Simpson", "/"); options.Cookies.AddCookie(cookie); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies.Contains(cookie), "Valid cookie was not returned"); } [Test] public void ShouldDeleteCookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookieToDelete = new Cookie("answer", "42"); Cookie cookieToKeep = new Cookie("canIHaz", "Cheeseburguer"); options.Cookies.AddCookie(cookieToDelete); options.Cookies.AddCookie(cookieToKeep); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; options.Cookies.DeleteCookie(cookieToDelete); ReadOnlyCollection<Cookie> cookies2 = options.Cookies.AllCookies; Assert.IsFalse(cookies2.Contains(cookieToDelete), "Cookie was not deleted successfully"); Assert.That(cookies2.Contains(cookieToKeep), "Valid cookie was not returned"); } ////////////////////////////////////////////// // Support functions ////////////////////////////////////////////// private void GotoValidDomainAndClearCookies(string page) { this.hostname = null; String hostname = EnvironmentManager.Instance.UrlBuilder.HostName; if (IsValidHostNameForCookieTests(hostname)) { this.isOnAlternativeHostName = false; this.hostname = hostname; } hostname = EnvironmentManager.Instance.UrlBuilder.AlternateHostName; if (this.hostname == null && IsValidHostNameForCookieTests(hostname)) { this.isOnAlternativeHostName = true; this.hostname = hostname; } GoToPage(page); driver.Manage().Cookies.DeleteAllCookies(); } private bool CheckIsOnValidHostNameForCookieTests() { bool correct = this.hostname != null && IsValidHostNameForCookieTests(this.hostname); if (!correct) { System.Console.WriteLine("Skipping test: unable to find domain name to use"); } return correct; } private void GoToPage(String pageName) { driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName); } private void GoToOtherPage(String pageName) { driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName); } private bool IsValidHostNameForCookieTests(string hostname) { // TODO(JimEvan): Some coverage is better than none, so we // need to ignore the fact that localhost cookies are problematic. // Reenable this when we have a better solution per DanielWagnerHall. // ChromeDriver2 has trouble with localhost. IE and Firefox don't. // return !IsIpv4Address(hostname) && "localhost" != hostname; bool isLocalHostOkay = true; if ("localhost" == hostname && TestUtilities.IsChrome(driver)) { isLocalHostOkay = false; } return !IsIpv4Address(hostname) && isLocalHostOkay; } private static bool IsIpv4Address(string addrString) { return Regex.IsMatch(addrString, "\\d{1,3}(?:\\.\\d{1,3}){3}"); } private string GenerateUniqueKey() { return string.Format("key_{0}", random.Next()); } private string GetDocumentCookieOrNull() { IJavaScriptExecutor jsDriver = driver as IJavaScriptExecutor; if (jsDriver == null) { return null; } try { return (string)jsDriver.ExecuteScript("return document.cookie"); } catch (InvalidOperationException) { return null; } } private void AssertNoCookiesArePresent() { Assert.IsTrue(driver.Manage().Cookies.AllCookies.Count == 0, "Cookies were not empty"); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.AreEqual(string.Empty, documentCookie, "Cookies were not empty"); } } private void AssertSomeCookiesArePresent() { Assert.IsFalse(driver.Manage().Cookies.AllCookies.Count == 0, "Cookies were empty"); String documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.AreNotEqual(string.Empty, documentCookie, "Cookies were empty"); } } private void AssertCookieIsNotPresentWithName(string key) { Assert.IsNull(driver.Manage().Cookies.GetCookieNamed(key), "Cookie was present with name " + key); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.IsFalse(documentCookie.Contains(key + "="), "Cookie was present with name " + key); } } private void AssertCookieIsPresentWithName(string key) { Assert.IsNotNull(driver.Manage().Cookies.GetCookieNamed(key), "Cookie was present with name " + key); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.IsTrue(documentCookie.Contains(key + "="), "Cookie was present with name " + key); } } private void AssertCookieHasValue(string key, string value) { Assert.AreEqual(value, driver.Manage().Cookies.GetCookieNamed(key).Value, "Cookie had wrong value"); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.IsTrue(documentCookie.Contains(key + "=" + value), "Cookie was present with name " + key); } } private DateTime GetTimeInTheFuture() { return DateTime.Now.Add(TimeSpan.FromMilliseconds(100000)); } } }
namespace Oculus.Platform { using System; using System.IO; using UnityEditor; using UnityEngine; using UnityEngine.Networking; // This classes implements a UI to edit the PlatformSettings class. // The UI is accessible from a the menu bar via: Oculus Platform -> Edit Settings [CustomEditor(typeof(PlatformSettings))] public class OculusPlatformSettingsEditor : Editor { private bool isUnityEditorSettingsExpanded; private bool isBuildSettingsExpanded; private UnityWebRequest getAccessTokenRequest; private void OnEnable() { isUnityEditorSettingsExpanded = true; isBuildSettingsExpanded = true; } [UnityEditor.MenuItem("Oculus/Platform/Edit Settings")] public static void Edit() { UnityEditor.Selection.activeObject = PlatformSettings.Instance; } public override void OnInspectorGUI() { // // Application IDs section // EditorGUILayout.LabelField("Application ID:"); GUIContent riftAppIDLabel = new GUIContent("Oculus Rift [?]", "This AppID will be used when building to the Windows target."); GUIContent mobileAppIDLabel = new GUIContent("Oculus Go/Quest or Gear VR [?]", "This AppID will be used when building to the Android target"); PlatformSettings.AppID = MakeTextBox(riftAppIDLabel, PlatformSettings.AppID); PlatformSettings.MobileAppID = MakeTextBox(mobileAppIDLabel, PlatformSettings.MobileAppID); if (GUILayout.Button("Create / Find your app on https://dashboard.oculus.com")) { UnityEngine.Application.OpenURL("https://dashboard.oculus.com/"); } #if UNITY_ANDROID if (String.IsNullOrEmpty(PlatformSettings.MobileAppID)) { EditorGUILayout.HelpBox("Please enter a valid Oculus Go/Quest or Gear VR App ID.", MessageType.Error); } else { var msg = "Configured to connect with App ID " + PlatformSettings.MobileAppID; EditorGUILayout.HelpBox(msg, MessageType.Info); } #else if (String.IsNullOrEmpty(PlatformSettings.AppID)) { EditorGUILayout.HelpBox("Please enter a valid Oculus Rift App ID.", MessageType.Error); } else { var msg = "Configured to connect with App ID " + PlatformSettings.AppID; EditorGUILayout.HelpBox(msg, MessageType.Info); } #endif EditorGUILayout.Separator(); // // Unity Editor Settings section // isUnityEditorSettingsExpanded = EditorGUILayout.Foldout(isUnityEditorSettingsExpanded, "Unity Editor Settings"); if (isUnityEditorSettingsExpanded) { GUIHelper.HInset(6, () => { bool HasTestAccessToken = !String.IsNullOrEmpty(StandalonePlatformSettings.OculusPlatformTestUserAccessToken); if (PlatformSettings.UseStandalonePlatform) { if (!HasTestAccessToken && (String.IsNullOrEmpty(StandalonePlatformSettings.OculusPlatformTestUserEmail) || String.IsNullOrEmpty(StandalonePlatformSettings.OculusPlatformTestUserPassword))) { EditorGUILayout.HelpBox("Please enter a valid user credentials.", MessageType.Error); } else { var msg = "The Unity editor will use the supplied test user credentials and operate in standalone mode. Some user data will be mocked."; EditorGUILayout.HelpBox(msg, MessageType.Info); } } else { var msg = "The Unity editor will use the user credentials from the Oculus application."; EditorGUILayout.HelpBox(msg, MessageType.Info); } var useStandaloneLabel = "Use Standalone Platform [?]"; var useStandaloneHint = "If this is checked your app will use a debug platform with the User info below. " + "Otherwise your app will connect to the Oculus Platform. This setting only applies to the Unity Editor"; PlatformSettings.UseStandalonePlatform = MakeToggle(new GUIContent(useStandaloneLabel, useStandaloneHint), PlatformSettings.UseStandalonePlatform); GUI.enabled = PlatformSettings.UseStandalonePlatform; if (!HasTestAccessToken) { var emailLabel = "Test User Email: "; var emailHint = "Test users can be configured at " + "https://dashboard.oculus.com/organizations/<your org ID>/testusers " + "however any valid Oculus account email may be used."; StandalonePlatformSettings.OculusPlatformTestUserEmail = MakeTextBox(new GUIContent(emailLabel, emailHint), StandalonePlatformSettings.OculusPlatformTestUserEmail); var passwdLabel = "Test User Password: "; var passwdHint = "Password associated with the email address."; StandalonePlatformSettings.OculusPlatformTestUserPassword = MakePasswordBox(new GUIContent(passwdLabel, passwdHint), StandalonePlatformSettings.OculusPlatformTestUserPassword); var isLoggingIn = (getAccessTokenRequest != null); var loginLabel = (!isLoggingIn) ? "Login" : "Logging in..."; GUI.enabled = !isLoggingIn; if (GUILayout.Button(loginLabel)) { WWWForm form = new WWWForm(); form.AddField("email", StandalonePlatformSettings.OculusPlatformTestUserEmail); form.AddField("password", StandalonePlatformSettings.OculusPlatformTestUserPassword); // Start the WWW request to get the access token getAccessTokenRequest = UnityWebRequest.Post("https://graph.oculus.com/login", form); getAccessTokenRequest.SetRequestHeader("Authorization", "Bearer OC|1141595335965881|"); getAccessTokenRequest.SendWebRequest(); EditorApplication.update += GetAccessToken; } GUI.enabled = true; } else { var loggedInMsg = "Currently using the credentials associated with " + StandalonePlatformSettings.OculusPlatformTestUserEmail; EditorGUILayout.HelpBox(loggedInMsg, MessageType.Info); var logoutLabel = "Clear Credentials"; if (GUILayout.Button(logoutLabel)) { StandalonePlatformSettings.OculusPlatformTestUserAccessToken = ""; } } GUI.enabled = true; }); } EditorGUILayout.Separator(); // // Build Settings section // isBuildSettingsExpanded = EditorGUILayout.Foldout(isBuildSettingsExpanded, "Build Settings"); if (isBuildSettingsExpanded) { GUIHelper.HInset(6, () => { if (!PlayerSettings.virtualRealitySupported) { EditorGUILayout.HelpBox("VR Support isn't enabled in the Player Settings", MessageType.Warning); } else { EditorGUILayout.HelpBox("VR Support is enabled", MessageType.Info); } PlayerSettings.virtualRealitySupported = MakeToggle(new GUIContent("Virtual Reality Support"), PlayerSettings.virtualRealitySupported); PlayerSettings.bundleVersion = MakeTextBox(new GUIContent("Bundle Version"), PlayerSettings.bundleVersion); #if UNITY_5_3 || UNITY_5_4 || UNITY_5_5 PlayerSettings.bundleIdentifier = MakeTextBox(new GUIContent("Bundle Identifier"), PlayerSettings.bundleIdentifier); #else BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup; PlayerSettings.SetApplicationIdentifier( buildTargetGroup, MakeTextBox( new GUIContent("Bundle Identifier"), PlayerSettings.GetApplicationIdentifier(buildTargetGroup))); #endif bool canEnableARM64Support = false; #if UNITY_2018_1_OR_NEWER canEnableARM64Support = true; #endif if (!canEnableARM64Support) { var msg = "Update your Unity Editor to 2018.1.x or newer to enable Arm64 support"; EditorGUILayout.HelpBox(msg, MessageType.Warning); if (IsArm64PluginPlatformEnabled()) { DisablePluginPlatform(PluginPlatform.Android64); } } else { if (!IsArm64PluginPlatformEnabled()) { EnablePluginPlatform(PluginPlatform.Android64); } } GUI.enabled = true; }); } EditorGUILayout.Separator(); } // Asyncronously fetch the access token with the given credentials private void GetAccessToken() { if (getAccessTokenRequest != null && getAccessTokenRequest.isDone) { // Clear the password StandalonePlatformSettings.OculusPlatformTestUserPassword = ""; if (String.IsNullOrEmpty(getAccessTokenRequest.error)) { var Response = JsonUtility.FromJson<OculusStandalonePlatformResponse>(getAccessTokenRequest.downloadHandler.text); StandalonePlatformSettings.OculusPlatformTestUserAccessToken = Response.access_token; } GUI.changed = true; EditorApplication.update -= GetAccessToken; getAccessTokenRequest.Dispose(); getAccessTokenRequest = null; } } private string MakeTextBox(GUIContent label, string variable) { return GUIHelper.MakeControlWithLabel(label, () => { GUI.changed = false; var result = EditorGUILayout.TextField(variable); SetDirtyOnGUIChange(); return result; }); } private string MakePasswordBox(GUIContent label, string variable) { return GUIHelper.MakeControlWithLabel(label, () => { GUI.changed = false; var result = EditorGUILayout.PasswordField(variable); SetDirtyOnGUIChange(); return result; }); } private bool MakeToggle(GUIContent label, bool variable) { return GUIHelper.MakeControlWithLabel(label, () => { GUI.changed = false; var result = EditorGUILayout.Toggle(variable); SetDirtyOnGUIChange(); return result; }); } private void SetDirtyOnGUIChange() { if (GUI.changed) { EditorUtility.SetDirty(PlatformSettings.Instance); GUI.changed = false; } } // TODO: Merge this with core utilities plugin updater functionality. Piggybacking here to avoid an orphaned delete in the future. private const string PluginSubPathAndroid32 = @"/Plugins/Android32/libovrplatformloader.so"; private const string PluginSubPathAndroid64 = @"/Plugins/Android64/libovrplatformloader.so"; private const string PluginDisabledSuffix = @".disabled"; public enum PluginPlatform { Android32, Android64 } private static string GetCurrentProjectPath() { return Directory.GetParent(UnityEngine.Application.dataPath).FullName; } private static string GetPlatformRootPath() { // use the path to OculusPluginUpdaterStub as a relative path anchor point var so = ScriptableObject.CreateInstance(typeof(OculusPluginUpdaterStub)); var script = MonoScript.FromScriptableObject(so); string assetPath = AssetDatabase.GetAssetPath(script); string editorDir = Directory.GetParent(assetPath).FullName; string platformDir = Directory.GetParent(editorDir).FullName; return platformDir; } private static string GetPlatformPluginPath(PluginPlatform platform) { string path = GetPlatformRootPath(); switch (platform) { case PluginPlatform.Android32: path += PluginSubPathAndroid32; break; case PluginPlatform.Android64: path += PluginSubPathAndroid64; break; default: throw new ArgumentException("Attempted to enable platform support for unsupported platform: " + platform); } return path; } //[UnityEditor.MenuItem("Oculus/Platform/EnforcePluginPlatformSettings")] public static void EnforcePluginPlatformSettings() { EnforcePluginPlatformSettings(PluginPlatform.Android32); EnforcePluginPlatformSettings(PluginPlatform.Android64); } public static void EnforcePluginPlatformSettings(PluginPlatform platform) { string path = GetPlatformPluginPath(platform); if (!Directory.Exists(path) && !File.Exists(path)) { path += PluginDisabledSuffix; } if ((Directory.Exists(path)) || (File.Exists(path))) { string basePath = GetCurrentProjectPath(); string relPath = path.Substring(basePath.Length + 1); PluginImporter pi = PluginImporter.GetAtPath(relPath) as PluginImporter; if (pi == null) { return; } // Disable support for all platforms, then conditionally enable desired support below pi.SetCompatibleWithEditor(false); pi.SetCompatibleWithAnyPlatform(false); pi.SetCompatibleWithPlatform(BuildTarget.Android, false); pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); pi.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); #if !UNITY_2019_2_OR_NEWER pi.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); pi.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); #endif #if UNITY_2017_3_OR_NEWER pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false); #else pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); #endif switch (platform) { case PluginPlatform.Android32: pi.SetCompatibleWithPlatform(BuildTarget.Android, true); pi.SetPlatformData(BuildTarget.Android, "CPU", "ARMv7"); break; case PluginPlatform.Android64: pi.SetCompatibleWithPlatform(BuildTarget.Android, true); pi.SetPlatformData(BuildTarget.Android, "CPU", "ARM64"); break; default: throw new ArgumentException("Attempted to enable platform support for unsupported platform: " + platform); } AssetDatabase.ImportAsset(relPath, ImportAssetOptions.ForceUpdate); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); } } public static bool IsArm64PluginPlatformEnabled() { string path = GetPlatformPluginPath(PluginPlatform.Android64); bool pathAlreadyExists = Directory.Exists(path) || File.Exists(path); return pathAlreadyExists; } public static void EnablePluginPlatform(PluginPlatform platform) { string path = GetPlatformPluginPath(platform); string disabledPath = path + PluginDisabledSuffix; bool pathAlreadyExists = Directory.Exists(path) || File.Exists(path); bool disabledPathDoesNotExist = !Directory.Exists(disabledPath) && !File.Exists(disabledPath); if (pathAlreadyExists || disabledPathDoesNotExist) { return; } string basePath = GetCurrentProjectPath(); string relPath = path.Substring(basePath.Length + 1); string relDisabledPath = relPath + PluginDisabledSuffix; AssetDatabase.MoveAsset(relDisabledPath, relPath); AssetDatabase.ImportAsset(relPath, ImportAssetOptions.ForceUpdate); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); // Force reserialization of platform settings meta data EnforcePluginPlatformSettings(platform); } public static void DisablePluginPlatform(PluginPlatform platform) { string path = GetPlatformPluginPath(platform); string disabledPath = path + PluginDisabledSuffix; bool pathDoesNotExist = !Directory.Exists(path) && !File.Exists(path); bool disabledPathAlreadyExists = Directory.Exists(disabledPath) || File.Exists(disabledPath); if (pathDoesNotExist || disabledPathAlreadyExists) { return; } string basePath = GetCurrentProjectPath(); string relPath = path.Substring(basePath.Length + 1); string relDisabledPath = relPath + PluginDisabledSuffix; AssetDatabase.MoveAsset(relPath, relDisabledPath); AssetDatabase.ImportAsset(relDisabledPath, ImportAssetOptions.ForceUpdate); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); } } }
using ASCompletion.Settings; using NavigationBar.Localization; using System; using System.ComponentModel; namespace NavigationBar { public delegate void SettingsChangesEvent(); [Serializable] public class Settings { [field: NonSerialized] public event SettingsChangesEvent OnSettingsChanged; private const bool DEFAULT_SHOW_NAVIGATION_TOOLBAR = false; private const bool DEFAULT_SHOW_IMPORTED_CLASSES = false; private const bool DEFAULT_SHOW_SUPER_CLASSES = false; private const bool DEFAULT_SHOW_INHERITED_MEMBERS = false; private const bool DEFAULT_SHOW_QUALIFIED_CLASS_NAME = true; private const bool DEFAULT_LABEL_PROPERTIES_LIKE_FUNCTIONS = false; private const bool DEFAULT_IGNORE_UNDERSCORE = false; private const OutlineSorting DEFAULT_MEMBER_SORT_METHOD = OutlineSorting.Sorted; private const bool DEFAULT_DROPDOWN_MULTIKEY_SEARCH_ENABLED = true; private const int DEFAULT_DROPDOWN_MULTIKEY_SEARCH_TIMER = 1000; private const bool DEFAULT_DROPDOWN_FULLWORD_SEARCH_ENABLED = true; private bool _showNavigationToolbar = DEFAULT_SHOW_NAVIGATION_TOOLBAR; private bool _showImportedClasses = DEFAULT_SHOW_IMPORTED_CLASSES; private bool _showSuperClasses = DEFAULT_SHOW_SUPER_CLASSES; private bool _showInheritedMembers = DEFAULT_SHOW_INHERITED_MEMBERS; private bool _showQualifiedClassName = DEFAULT_SHOW_QUALIFIED_CLASS_NAME; private bool _labelPropertiesLikeFunctions = DEFAULT_LABEL_PROPERTIES_LIKE_FUNCTIONS; private bool _ignoreUnderscore = DEFAULT_IGNORE_UNDERSCORE; private OutlineSorting _memberSortMethod = DEFAULT_MEMBER_SORT_METHOD; private bool _dropDownMultiKeySearchEnabled = false; private int _dropDownMultiKeySearchTimer = 0; private bool _dropDownFullWordSearchEnabled = false; [LocalizedCategory("NavigationBar.Category.Visibility")] [LocalizedDisplayName("NavigationBar.Label.ShowNavigationToolbar")] [LocalizedDescription("NavigationBar.Description.ShowNavigationToolbar")] [DefaultValue(DEFAULT_SHOW_NAVIGATION_TOOLBAR)] public bool ShowNavigationToolbar { get { return _showNavigationToolbar; } set { if (_showNavigationToolbar != value) { _showNavigationToolbar = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Visibility")] [LocalizedDisplayName("NavigationBar.Label.ShowImportedClasses")] [LocalizedDescription("NavigationBar.Description.ShowImportedClasses")] [DefaultValue(DEFAULT_SHOW_IMPORTED_CLASSES)] public bool ShowImportedClasses { get { return _showImportedClasses; } set { if (_showImportedClasses != value) { _showImportedClasses = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Visibility")] [LocalizedDisplayName("NavigationBar.Label.ShowSuperClasses")] [LocalizedDescription("NavigationBar.Description.ShowSuperClasses")] [DefaultValue(DEFAULT_SHOW_SUPER_CLASSES)] public bool ShowSuperClasses { get { return _showSuperClasses; } set { if (_showSuperClasses != value) { _showSuperClasses = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Visibility")] [LocalizedDisplayName("NavigationBar.Label.ShowInheritedMembers")] [LocalizedDescription("NavigationBar.Description.ShowInheritedMembers")] [DefaultValue(DEFAULT_SHOW_INHERITED_MEMBERS)] public bool ShowInheritedMembers { get { return _showInheritedMembers; } set { if (_showInheritedMembers != value) { _showInheritedMembers = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Labeling")] [LocalizedDisplayName("NavigationBar.Label.ShowQualifiedClassNames")] [LocalizedDescription("NavigationBar.Description.ShowQualifiedClassNames")] [DefaultValue(DEFAULT_SHOW_QUALIFIED_CLASS_NAME)] public bool ShowQualifiedClassName { get { return _showQualifiedClassName; } set { if (_showQualifiedClassName != value) { _showQualifiedClassName = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Labeling")] [LocalizedDisplayName("NavigationBar.Label.LabelPropertiesLikeFunctions")] [LocalizedDescription("NavigationBar.Description.LabelPropertiesLikeFunctions")] [DefaultValue(DEFAULT_LABEL_PROPERTIES_LIKE_FUNCTIONS)] public bool LabelPropertiesLikeFunctions { get { return _labelPropertiesLikeFunctions; } set { if (_labelPropertiesLikeFunctions != value) { _labelPropertiesLikeFunctions = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Navigation")] [LocalizedDisplayName("NavigationBar.Label.IgnoreUnderscore")] [LocalizedDescription("NavigationBar.Description.IgnoreUnderscore")] [DefaultValue(DEFAULT_IGNORE_UNDERSCORE)] public bool IgnoreUnderscore { get { return _ignoreUnderscore; } set { if (_ignoreUnderscore != value) { _ignoreUnderscore = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Navigation")] [LocalizedDisplayName("NavigationBar.Label.SortingMethod")] [LocalizedDescription("NavigationBar.Description.SortingMethod")] [DefaultValue(DEFAULT_MEMBER_SORT_METHOD)] public OutlineSorting MemberSortMethod { get { return _memberSortMethod; } set { if (_memberSortMethod != value) { _memberSortMethod = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Search")] [LocalizedDisplayName("NavigationBar.Label.DropDownMultiKeyEnabled")] [LocalizedDescription("NavigationBar.Description.DropDownMultiKeyEnabled")] [DefaultValue(DEFAULT_DROPDOWN_MULTIKEY_SEARCH_ENABLED)] public bool DropDownMultiKeyEnabled { get { return _dropDownMultiKeySearchEnabled; } set { if (_dropDownMultiKeySearchEnabled != value) { _dropDownMultiKeySearchEnabled = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Search")] [LocalizedDisplayName("NavigationBar.Label.DropDownMultiKeyTimer")] [LocalizedDescription("NavigationBar.Description.DropDownMultiKeyTimer")] [DefaultValue(DEFAULT_DROPDOWN_MULTIKEY_SEARCH_TIMER)] public int DropDownMultiKeyTimer { get { return _dropDownMultiKeySearchTimer; } set { if (_dropDownMultiKeySearchTimer != value) { _dropDownMultiKeySearchTimer = value; FireChanged(); } } } [LocalizedCategory("NavigationBar.Category.Search")] [LocalizedDisplayName("NavigationBar.Label.DropDownFullWordSearchEnabled")] [LocalizedDescription("NavigationBar.Description.DropDownFullWordSearchEnabled")] [DefaultValue(DEFAULT_DROPDOWN_FULLWORD_SEARCH_ENABLED)] public bool DropDownFullWordSearchEnabled { get { return _dropDownFullWordSearchEnabled; } set { if (_dropDownFullWordSearchEnabled != value) { _dropDownFullWordSearchEnabled = value; FireChanged(); } } } private void FireChanged() { if (OnSettingsChanged != null) OnSettingsChanged(); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Xml.Serialization; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Data; ////////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend. // //Override methods in the logic front class. // ////////////////////////////////////////////////////////////// namespace VotingInfo.Database.Logic.Data { [Serializable] public abstract partial class ElectionLevelMetaDataXrefLogicBase : LogicBase<ElectionLevelMetaDataXrefLogicBase> { //Put your code in a separate file. This is auto generated. [XmlArray] public List<ElectionLevelMetaDataXrefContract> Results; public ElectionLevelMetaDataXrefLogicBase() { Results = new List<ElectionLevelMetaDataXrefContract>(); } /// <summary> /// Run ElectionLevelMetaDataXref_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldElectionLevelId">Value for ElectionLevelId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldContentInspectionId , int fldElectionLevelId , string fldMetaDataId ) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@ElectionLevelId", fldElectionLevelId) , new SqlParameter("@MetaDataId", fldMetaDataId) }); result = (int?)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Run ElectionLevelMetaDataXref_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldElectionLevelId">Value for ElectionLevelId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldContentInspectionId , int fldElectionLevelId , string fldMetaDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@ElectionLevelId", fldElectionLevelId) , new SqlParameter("@MetaDataId", fldMetaDataId) }); return (int?)cmd.ExecuteScalar(); } } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>1, if insert was successful</returns> public int Insert(ElectionLevelMetaDataXrefContract row) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@ElectionLevelId", row.ElectionLevelId) , new SqlParameter("@MetaDataId", row.MetaDataId) }); result = (int?)cmd.ExecuteScalar(); row.ElectionLevelMetaDataXrefId = result; } }); return result != null ? 1 : 0; } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>1, if insert was successful</returns> public int Insert(ElectionLevelMetaDataXrefContract row, SqlConnection connection, SqlTransaction transaction) { int? result = null; using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@ElectionLevelId", row.ElectionLevelId) , new SqlParameter("@MetaDataId", row.MetaDataId) }); result = (int?)cmd.ExecuteScalar(); row.ElectionLevelMetaDataXrefId = result; } return result != null ? 1 : 0; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<ElectionLevelMetaDataXrefContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = InsertAll(rows, x, null); }); return rowCount; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<ElectionLevelMetaDataXrefContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Insert(row, connection, transaction); return rowCount; } /// <summary> /// Run ElectionLevelMetaDataXref_Update. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldElectionLevelMetaDataXrefId">Value for ElectionLevelMetaDataXrefId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldElectionLevelId">Value for ElectionLevelId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> public virtual int Update(int fldElectionLevelMetaDataXrefId , int fldContentInspectionId , int fldElectionLevelId , string fldMetaDataId ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", fldElectionLevelMetaDataXrefId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@ElectionLevelId", fldElectionLevelId) , new SqlParameter("@MetaDataId", fldMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run ElectionLevelMetaDataXref_Update. /// </summary> /// <param name="fldElectionLevelMetaDataXrefId">Value for ElectionLevelMetaDataXrefId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldElectionLevelId">Value for ElectionLevelId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(int fldElectionLevelMetaDataXrefId , int fldContentInspectionId , int fldElectionLevelId , string fldMetaDataId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", fldElectionLevelMetaDataXrefId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@ElectionLevelId", fldElectionLevelId) , new SqlParameter("@MetaDataId", fldMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(ElectionLevelMetaDataXrefContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", row.ElectionLevelMetaDataXrefId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@ElectionLevelId", row.ElectionLevelId) , new SqlParameter("@MetaDataId", row.MetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(ElectionLevelMetaDataXrefContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", row.ElectionLevelMetaDataXrefId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@ElectionLevelId", row.ElectionLevelId) , new SqlParameter("@MetaDataId", row.MetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<ElectionLevelMetaDataXrefContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = UpdateAll(rows, x, null); }); return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<ElectionLevelMetaDataXrefContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Update(row, connection, transaction); return rowCount; } /// <summary> /// Run ElectionLevelMetaDataXref_Delete. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldElectionLevelMetaDataXrefId">Value for ElectionLevelMetaDataXrefId</param> public virtual int Delete(int fldElectionLevelMetaDataXrefId ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", fldElectionLevelMetaDataXrefId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run ElectionLevelMetaDataXref_Delete. /// </summary> /// <param name="fldElectionLevelMetaDataXrefId">Value for ElectionLevelMetaDataXrefId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(int fldElectionLevelMetaDataXrefId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", fldElectionLevelMetaDataXrefId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(ElectionLevelMetaDataXrefContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", row.ElectionLevelMetaDataXrefId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(ElectionLevelMetaDataXrefContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", row.ElectionLevelMetaDataXrefId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<ElectionLevelMetaDataXrefContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = DeleteAll(rows, x, null); }); return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<ElectionLevelMetaDataXrefContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Delete(row, connection, transaction); return rowCount; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldElectionLevelMetaDataXrefId">Value for ElectionLevelMetaDataXrefId</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldElectionLevelMetaDataXrefId ) { bool result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Exists]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", fldElectionLevelMetaDataXrefId) }); result = (bool)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldElectionLevelMetaDataXrefId">Value for ElectionLevelMetaDataXrefId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldElectionLevelMetaDataXrefId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Exists]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", fldElectionLevelMetaDataXrefId) }); return (bool)cmd.ExecuteScalar(); } } /// <summary> /// Run ElectionLevelMetaDataXref_Search, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool Search(string fldMetaDataId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Search]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataId", fldMetaDataId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run ElectionLevelMetaDataXref_Search, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool Search(string fldMetaDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_Search]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataId", fldMetaDataId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run ElectionLevelMetaDataXref_SelectAll, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectAll() { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectAll]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run ElectionLevelMetaDataXref_SelectAll, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectAll]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run ElectionLevelMetaDataXref_SelectBy_ElectionLevelMetaDataXrefId, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldElectionLevelMetaDataXrefId">Value for ElectionLevelMetaDataXrefId</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectBy_ElectionLevelMetaDataXrefId(int fldElectionLevelMetaDataXrefId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectBy_ElectionLevelMetaDataXrefId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", fldElectionLevelMetaDataXrefId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run ElectionLevelMetaDataXref_SelectBy_ElectionLevelMetaDataXrefId, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldElectionLevelMetaDataXrefId">Value for ElectionLevelMetaDataXrefId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectBy_ElectionLevelMetaDataXrefId(int fldElectionLevelMetaDataXrefId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectBy_ElectionLevelMetaDataXrefId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelMetaDataXrefId", fldElectionLevelMetaDataXrefId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run ElectionLevelMetaDataXref_SelectBy_MetaDataId, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectBy_MetaDataId(string fldMetaDataId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectBy_MetaDataId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataId", fldMetaDataId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run ElectionLevelMetaDataXref_SelectBy_MetaDataId, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectBy_MetaDataId(string fldMetaDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectBy_MetaDataId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataId", fldMetaDataId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run ElectionLevelMetaDataXref_SelectBy_ContentInspectionId, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectBy_ContentInspectionId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run ElectionLevelMetaDataXref_SelectBy_ContentInspectionId, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectBy_ContentInspectionId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run ElectionLevelMetaDataXref_SelectBy_ElectionLevelId, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldElectionLevelId">Value for ElectionLevelId</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectBy_ElectionLevelId(int fldElectionLevelId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectBy_ElectionLevelId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelId", fldElectionLevelId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run ElectionLevelMetaDataXref_SelectBy_ElectionLevelId, and return results as a list of ElectionLevelMetaDataXrefRow. /// </summary> /// <param name="fldElectionLevelId">Value for ElectionLevelId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of ElectionLevelMetaDataXrefRow.</returns> public virtual bool SelectBy_ElectionLevelId(int fldElectionLevelId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[ElectionLevelMetaDataXref_SelectBy_ElectionLevelId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ElectionLevelId", fldElectionLevelId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Read all items into this collection /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadAll(SqlDataReader reader) { var canRead = ReadOne(reader); var result = canRead; while (canRead) canRead = ReadOne(reader); return result; } /// <summary> /// Read one item into Results /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadOne(SqlDataReader reader) { if (reader.Read()) { Results.Add( new ElectionLevelMetaDataXrefContract { ElectionLevelMetaDataXrefId = reader.GetInt32(0), ContentInspectionId = reader.GetInt32(1), ElectionLevelId = reader.GetInt32(2), MetaDataId = reader.IsDBNull(3) ? null : reader.GetString(3), }); return true; } return false; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public virtual int Save(ElectionLevelMetaDataXrefContract row) { if(row == null) return 0; if(row.ElectionLevelMetaDataXrefId != null) return Update(row); return Insert(row); } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Save(ElectionLevelMetaDataXrefContract row, SqlConnection connection, SqlTransaction transaction) { if(row == null) return 0; if(row.ElectionLevelMetaDataXrefId != null) return Update(row, connection, transaction); return Insert(row, connection, transaction); } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<ElectionLevelMetaDataXrefContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { foreach(var row in rows) rowCount += Save(row, x, null); }); return rowCount; } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<ElectionLevelMetaDataXrefContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Save(row, connection, transaction); return rowCount; } } }
namespace Fixtures.Azure.SwaggerBatAzureSpecials { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Newtonsoft.Json; using Microsoft.Azure; using Models; internal partial class ApiVersionDefaultOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionDefaultOperations { /// <summary> /// Initializes a new instance of the ApiVersionDefaultOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ApiVersionDefaultOperations(AutoRestAzureSpecialParametersTestClient client) { this.Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse> GetMethodGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.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("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMethodGlobalValid", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//azurespecials/apiVersion/method/string/none/query/global/2015-07-01-preview"; List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse> GetMethodGlobalNotProvidedValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.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("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMethodGlobalNotProvidedValid", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//azurespecials/apiVersion/method/string/none/query/globalNotProvided/2015-07-01-preview"; List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse> GetPathGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.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("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetPathGlobalValid", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//azurespecials/apiVersion/path/string/none/query/global/2015-07-01-preview"; List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse> GetSwaggerGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.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("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetSwaggerGlobalValid", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//azurespecials/apiVersion/swagger/string/none/query/global/2015-07-01-preview"; List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if WCF_SUPPORTED namespace NLog.LogReceiverService { using System.ServiceModel.Description; using System; using System.ComponentModel; using System.Net; using System.ServiceModel; using System.ServiceModel.Channels; /// <summary> /// Abstract base class for the WcfLogReceiverXXXWay classes. It can only be /// used internally (see internal constructor). It passes off any Channel usage /// to the inheriting class. /// </summary> /// <typeparam name="TService">Type of the WCF service.</typeparam> public abstract class WcfLogReceiverClientBase<TService> : ClientBase<TService>, IWcfLogReceiverClient where TService : class { /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> protected WcfLogReceiverClientBase() : base() { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> protected WcfLogReceiverClientBase(string endpointConfigurationName) : base(endpointConfigurationName) { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> /// <param name="remoteAddress">The remote address.</param> protected WcfLogReceiverClientBase(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> /// <param name="remoteAddress">The remote address.</param> protected WcfLogReceiverClientBase(string endpointConfigurationName, EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="binding">The binding.</param> /// <param name="remoteAddress">The remote address.</param> protected WcfLogReceiverClientBase(Binding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) { } /// <summary> /// Occurs when the log message processing has completed. /// </summary> public event EventHandler<AsyncCompletedEventArgs> ProcessLogMessagesCompleted; /// <summary> /// Occurs when Open operation has completed. /// </summary> public event EventHandler<AsyncCompletedEventArgs> OpenCompleted; /// <summary> /// Occurs when Close operation has completed. /// </summary> public event EventHandler<AsyncCompletedEventArgs> CloseCompleted; #if !NET4_0 && !NET3_5 && !NETSTANDARD /// <summary> /// Gets or sets the cookie container. /// </summary> /// <value>The cookie container.</value> public CookieContainer CookieContainer { get { var httpCookieContainerManager = InnerChannel.GetProperty<IHttpCookieContainerManager>(); return httpCookieContainerManager?.CookieContainer; } set { var httpCookieContainerManager = InnerChannel.GetProperty<IHttpCookieContainerManager>(); if (httpCookieContainerManager != null) { httpCookieContainerManager.CookieContainer = value; } else { throw new InvalidOperationException("Unable to set the CookieContainer. Please make sure the binding contains an HttpCookieContainerBindingElement."); } } } #endif /// <summary> /// Opens the client asynchronously. /// </summary> public void OpenAsync() { OpenAsync(null); } /// <summary> /// Opens the client asynchronously. /// </summary> /// <param name="userState">User-specific state.</param> public void OpenAsync(object userState) { InvokeAsync(OnBeginOpen, null, OnEndOpen, OnOpenCompleted, userState); } /// <summary> /// Closes the client asynchronously. /// </summary> public void CloseAsync() { CloseAsync(null); } /// <summary> /// Closes the client asynchronously. /// </summary> /// <param name="userState">User-specific state.</param> public void CloseAsync(object userState) { InvokeAsync(OnBeginClose, null, OnEndClose, OnCloseCompleted, userState); } /// <summary> /// Processes the log messages asynchronously. /// </summary> /// <param name="events">The events to send.</param> public void ProcessLogMessagesAsync(NLogEvents events) { ProcessLogMessagesAsync(events, null); } /// <summary> /// Processes the log messages asynchronously. /// </summary> /// <param name="events">The events to send.</param> /// <param name="userState">User-specific state.</param> public void ProcessLogMessagesAsync(NLogEvents events, object userState) { InvokeAsync( OnBeginProcessLogMessages, new object[] { events }, OnEndProcessLogMessages, OnProcessLogMessagesCompleted, userState); } /// <summary> /// Begins processing of log messages. /// </summary> /// <param name="events">The events to send.</param> /// <param name="callback">The callback.</param> /// <param name="asyncState">Asynchronous state.</param> /// <returns> /// IAsyncResult value which can be passed to <see cref="ILogReceiverOneWayClient.EndProcessLogMessages"/>. /// </returns> public abstract IAsyncResult BeginProcessLogMessages(NLogEvents events, AsyncCallback callback, object asyncState); /// <summary> /// Ends asynchronous processing of log messages. /// </summary> /// <param name="result">The result.</param> public abstract void EndProcessLogMessages(IAsyncResult result); private IAsyncResult OnBeginProcessLogMessages(object[] inValues, AsyncCallback callback, object asyncState) { var events = (NLogEvents)inValues[0]; return BeginProcessLogMessages(events, callback, asyncState); } private object[] OnEndProcessLogMessages(IAsyncResult result) { EndProcessLogMessages(result); return null; } private void OnProcessLogMessagesCompleted(object state) { if (ProcessLogMessagesCompleted != null) { var e = (InvokeAsyncCompletedEventArgs)state; ProcessLogMessagesCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } private IAsyncResult OnBeginOpen(object[] inValues, AsyncCallback callback, object asyncState) { return ((ICommunicationObject)this).BeginOpen(callback, asyncState); } private object[] OnEndOpen(IAsyncResult result) { ((ICommunicationObject)this).EndOpen(result); return null; } private void OnOpenCompleted(object state) { if (OpenCompleted != null) { var e = (InvokeAsyncCompletedEventArgs)state; OpenCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } private IAsyncResult OnBeginClose(object[] inValues, AsyncCallback callback, object asyncState) { return ((ICommunicationObject)this).BeginClose(callback, asyncState); } private object[] OnEndClose(IAsyncResult result) { ((ICommunicationObject)this).EndClose(result); return null; } private void OnCloseCompleted(object state) { if (CloseCompleted != null) { var e = (InvokeAsyncCompletedEventArgs)state; CloseCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } } } #endif
using System; using System.Globalization; using System.Linq; using Eto.Drawing; using System.Collections.Generic; using System.Runtime.InteropServices; #if XAMMAC2 using AppKit; using Foundation; using CoreGraphics; using ObjCRuntime; using CoreAnimation; using CoreImage; #elif OSX using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.CoreGraphics; using MonoMac.ObjCRuntime; using MonoMac.CoreAnimation; using MonoMac.CoreImage; using MonoMac; #if Mac64 using CGSize = MonoMac.Foundation.NSSize; using CGRect = MonoMac.Foundation.NSRect; using CGPoint = MonoMac.Foundation.NSPoint; using nfloat = System.Double; using nint = System.Int64; using nuint = System.UInt64; #else using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using nfloat = System.Single; using nint = System.Int32; using nuint = System.UInt32; #endif #endif #if OSX using Eto.Mac.Forms; #if XAMMAC2 using GraphicsBase = Eto.Mac.Forms.MacBase<CoreGraphics.CGContext, Eto.Drawing.Graphics, Eto.Drawing.Graphics.ICallback>; #else using GraphicsBase = Eto.Mac.Forms.MacBase<MonoMac.CoreGraphics.CGContext, Eto.Drawing.Graphics, Eto.Drawing.Graphics.ICallback>; #endif namespace Eto.Mac.Drawing #elif IOS using Eto.iOS.Forms; using Eto.Mac; using CoreGraphics; using UIKit; using Foundation; using NSView = UIKit.UIView; using GraphicsBase = Eto.WidgetHandler<CoreGraphics.CGContext, Eto.Drawing.Graphics, Eto.Drawing.Graphics.ICallback>; namespace Eto.iOS.Drawing #endif { #if OSX public static class GraphicsExtensions { [DllImport(Constants.AppKitLibrary, EntryPoint = "NSSetFocusRingStyle")] public extern static void SetFocusRingStyle(NSFocusRingPlacement placement); } #endif /// <summary> /// Handler for the <see cref="Graphics.IHandler"/> /// </summary> /// <copyright>(c) 2012-2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class GraphicsHandler : GraphicsBase, Graphics.IHandler { #if OSX NSGraphicsContext graphicsContext; bool disposeContext; readonly NSView view; #endif float height; bool isOffset; CGRect? clipBounds; IGraphicsPath clipPath; readonly Stack<CGAffineTransform> transforms = new Stack<CGAffineTransform>(); CGAffineTransform currentTransform = CGAffineTransform.MakeIdentity(); static readonly CGColorSpace patternColorSpace = CGColorSpace.CreatePattern(null); public NSView DisplayView { get; private set; } static readonly object PixelOffsetMode_Key = new object(); public PixelOffsetMode PixelOffsetMode { get { return Widget != null ? Widget.Properties.Get<PixelOffsetMode>(PixelOffsetMode_Key) : default(PixelOffsetMode); } set { Widget.Properties.Set(PixelOffsetMode_Key, value); } } void SetOffset(bool fill) { var requiresOffset = !fill && PixelOffsetMode == PixelOffsetMode.None; if (requiresOffset != isOffset) { RewindAll(); isOffset = requiresOffset; ApplyAll(); } } public GraphicsHandler() { } #if OSX public GraphicsHandler(NSView view) { this.view = view; graphicsContext = NSGraphicsContext.FromWindow(view.Window); graphicsContext = graphicsContext.IsFlipped ? graphicsContext : NSGraphicsContext.FromGraphicsPort(graphicsContext.GraphicsPortHandle, true); disposeContext = true; Control = graphicsContext.GraphicsPort; view.PostsFrameChangedNotifications = true; AddObserver(NSView.FrameChangedNotification, FrameDidChange, view); // if control is in a scrollview, we need to trap when it's scrolled as well var parent = view.Superview; while (parent != null) { var scroll = parent as NSScrollView; if (scroll != null) { scroll.ContentView.PostsBoundsChangedNotifications = true; AddObserver(NSView.BoundsChangedNotification, FrameDidChange, scroll.ContentView); } parent = parent.Superview; } SetDefaults(); InitializeContext(view.IsFlipped); } static void FrameDidChange(ObserverActionEventArgs e) { var h = e.Handler as GraphicsHandler; if (h != null && h.Control != null) { h.RewindAll(); h.Control.RestoreState(); h.InitializeContext(h.view.IsFlipped); } } public GraphicsHandler(NSView view, NSGraphicsContext graphicsContext, float height, bool flipped) { DisplayView = view; this.height = height; this.graphicsContext = flipped != graphicsContext.IsFlipped ? graphicsContext : NSGraphicsContext.FromGraphicsPort(graphicsContext.GraphicsPortHandle, true); Control = this.graphicsContext.GraphicsPort; SetDefaults(); InitializeContext(!flipped); } #elif IOS public GraphicsHandler(NSView view, CGContext context, nfloat height) { this.DisplayView = view; this.height = (float)height; this.Control = context; SetDefaults(); InitializeContext(false); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endif protected override bool DisposeControl { get { return false; } } public bool IsRetained { get { return false; } } static readonly object AntiAlias_Key = new object(); public bool AntiAlias { get { return Widget.Properties.Get<bool>(AntiAlias_Key, true); } set { Widget.Properties.Set(AntiAlias_Key, value, () => Control.SetShouldAntialias(value)); } } static readonly object PointsPerPixel_Key = new object(); public float PointsPerPixel { get { return Widget.Properties.Get<float>(PointsPerPixel_Key, 1f); } private set { Widget.Properties.Set(PointsPerPixel_Key, value); } } public ImageInterpolation ImageInterpolation { get { return Control.InterpolationQuality.ToEto(); } set { Control.InterpolationQuality = value.ToCG(); } } public void CreateFromImage(Bitmap image) { var handler = image.Handler as BitmapHandler; #if OSX var rep = handler.Control.Representations().OfType<NSBitmapImageRep>().FirstOrDefault(); graphicsContext = NSGraphicsContext.FromBitmap(rep); graphicsContext = graphicsContext.IsFlipped ? graphicsContext : NSGraphicsContext.FromGraphicsPort(graphicsContext.GraphicsPortHandle, true); disposeContext = true; Control = graphicsContext.GraphicsPort; PointsPerPixel = (float)(rep.PixelsWide / handler.Control.Size.Width); #elif IOS var cgimage = handler.Control.CGImage; Control = new CGBitmapContext(handler.Data.MutableBytes, cgimage.Width, cgimage.Height, cgimage.BitsPerComponent, cgimage.BytesPerRow, cgimage.ColorSpace, cgimage.BitmapInfo); PointsPerPixel = (float)(cgimage.Width / handler.Control.Size.Width); #endif height = image.Size.Height; SetDefaults(); InitializeContext(true); } public void Reset() { // unwind all SaveState's RewindAll(); // initial save state Control.RestoreState(); } public void Flush() { #if OSX graphicsContext.FlushGraphics(); #endif } #if OSX public float ViewHeight { get { return (float)(view != null ? view.Bounds.Height : height); } } #elif IOS public float ViewHeight { get { return height; } } #endif void SetDefaults() { Control.InterpolationQuality = CGInterpolationQuality.Default; Control.SetAllowsSubpixelPositioning(false); } #if OSX CGSize? phase; public void SetPhase() { if (DisplayView == null) return; if (phase == null) { // find parent with layer, or goes up to window if none are found var layerView = DisplayView; while (layerView.Superview != null && layerView.Layer == null) layerView = layerView.Superview; // convert bottom-left point relative to layer or window var pos = DisplayView.ConvertPointToView(CGPoint.Empty, layerView); // phase should be based on position of control within closest layer or window. phase = new CGSize(pos.X, pos.Y); } Control.SetPatternPhase(phase.Value); } #endif void InitializeContext(bool viewFlipped) { Control.SaveState(); #if OSX // os x has different flipped states (depending on layers, etc), so compensate to make 0,0 at the top-left if (view != null) { // we have a view (drawing directly to the screen), so adjust to where it is Control.ClipToRect(view.ConvertRectToView(view.VisibleRect(), null)); var pos = view.ConvertPointToView(CGPoint.Empty, null); if (!viewFlipped) pos.Y += view.Frame.Height; Control.ConcatCTM(new CGAffineTransform(1, 0, 0, -1, (float)pos.X, (float)pos.Y)); } else { // drawing to a bitmap or during a drawRect operation if (viewFlipped) Control.ConcatCTM(new CGAffineTransform(1, 0, 0, -1, 0, ViewHeight)); } phase = null; #elif IOS if (viewFlipped) { // on ios, we flip the context if we're drawing on a bitmap otherwise we don't need to Control.ConcatCTM(new CGAffineTransform(1, 0, 0, -1, 0, ViewHeight)); } #endif ApplyAll(); } void StartDrawing() { #if OSX NSGraphicsContext.GlobalSaveGraphicsState(); NSGraphicsContext.CurrentContext = graphicsContext; #elif IOS UIGraphics.PushContext(Control); #endif Control.SaveState(); } void EndDrawing() { Control.RestoreState(); #if OSX NSGraphicsContext.GlobalRestoreGraphicsState(); #elif IOS UIGraphics.PopContext(); #endif } public void DrawLine(Pen pen, float startx, float starty, float endx, float endy) { SetOffset(false); StartDrawing(); pen.Apply(this); Control.StrokeLineSegments(new [] { new CGPoint(startx, starty), new CGPoint(endx, endy) }); EndDrawing(); } public void DrawRectangle(Pen pen, float x, float y, float width, float height) { SetOffset(false); StartDrawing(); var rect = new CGRect(x, y, width, height); pen.Apply(this); Control.StrokeRect(rect); EndDrawing(); } public void FillRectangle(Brush brush, float x, float y, float width, float height) { SetOffset(true); StartDrawing(); var rect = new CGRect(x, y, width, height); Control.AddRect(rect); Control.Clip(); brush.Draw(this, rect.ToEto()); EndDrawing(); } public void DrawEllipse(Pen pen, float x, float y, float width, float height) { SetOffset(false); StartDrawing(); var rect = new CGRect(x, y, width, height); pen.Apply(this); Control.StrokeEllipseInRect(rect); EndDrawing(); } public void FillEllipse(Brush brush, float x, float y, float width, float height) { SetOffset(true); StartDrawing(); /* if (width == 1 || height == 1) { DrawLine(color, x, y, x+width-1, y+height-1); return; }*/ var rect = new CGRect(x, y, width, height); Control.AddEllipseInRect(rect); Control.Clip(); brush.Draw(this, rect.ToEto()); EndDrawing(); } public void DrawArc(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle) { SetOffset(false); StartDrawing(); var rect = new CGRect(x, y, width, height); pen.Apply(this); var yscale = rect.Height / rect.Width; var centerY = rect.GetMidY(); var centerX = rect.GetMidX(); Control.ConcatCTM(new CGAffineTransform(1.0f, 0, 0, yscale, 0, centerY - centerY * yscale)); Control.AddArc(centerX, centerY, rect.Width / 2, CGConversions.DegreesToRadians(startAngle), CGConversions.DegreesToRadians(startAngle + sweepAngle), sweepAngle < 0); Control.StrokePath(); EndDrawing(); } public void FillPie(Brush brush, float x, float y, float width, float height, float startAngle, float sweepAngle) { SetOffset(true); StartDrawing(); var rect = new CGRect(x, y, width, height); Control.SaveState(); var yscale = rect.Height / rect.Width; var centerY = rect.GetMidY(); var centerX = rect.GetMidX(); Control.ConcatCTM(new CGAffineTransform(1.0f, 0, 0, yscale, 0, centerY - centerY * yscale)); Control.MoveTo(centerX, centerY); Control.AddArc(centerX, centerY, rect.Width / 2, CGConversions.DegreesToRadians(startAngle), CGConversions.DegreesToRadians(startAngle + sweepAngle), sweepAngle < 0); Control.AddLineToPoint(centerX, centerY); Control.ClosePath(); Control.RestoreState(); Control.Clip(); brush.Draw(this, rect.ToEto()); EndDrawing(); } public void FillPath(Brush brush, IGraphicsPath path) { SetOffset(true); StartDrawing(); Control.BeginPath(); Control.AddPath(path.ToCG()); Control.ClosePath(); switch (path.FillMode) { case FillMode.Alternate: Control.EOClip(); break; case FillMode.Winding: Control.Clip(); break; default: throw new NotSupportedException(); } brush.Draw(this, path.Bounds); EndDrawing(); } public void DrawPath(Pen pen, IGraphicsPath path) { SetOffset(false); StartDrawing(); pen.Apply(this); Control.BeginPath(); Control.AddPath(path.ToCG()); Control.StrokePath(); EndDrawing(); } public void DrawImage(Image image, float x, float y) { SetOffset(true); StartDrawing(); var handler = (IImageHandler)image.Handler; handler.DrawImage(this, x, y); EndDrawing(); } public void DrawImage(Image image, float x, float y, float width, float height) { SetOffset(true); StartDrawing(); var handler = (IImageHandler)image.Handler; handler.DrawImage(this, x, y, width, height); EndDrawing(); } public void DrawImage(Image image, RectangleF source, RectangleF destination) { SetOffset(true); StartDrawing(); var handler = (IImageHandler)image.Handler; handler.DrawImage(this, source, destination); EndDrawing(); } public void DrawText(Font font, SolidBrush brush, float x, float y, string text) { SetOffset(true); if (string.IsNullOrEmpty(text)) return; StartDrawing(); FontExtensions.DrawString(text, new PointF(x, y), brush.Color, font); EndDrawing(); } public SizeF MeasureString(Font font, string text) { StartDrawing(); var size = FontExtensions.MeasureString(text, font); EndDrawing(); return size; } #if OSX protected override void Dispose(bool disposing) { if (disposing) { if (disposeContext && graphicsContext != null) graphicsContext.FlushGraphics(); Reset(); if (disposeContext && graphicsContext != null) graphicsContext.Dispose(); } base.Dispose(disposing); } #endif public void TranslateTransform(float offsetX, float offsetY) { Control.TranslateCTM(offsetX, offsetY); currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeTranslation(offsetX, offsetY), currentTransform); } public void RotateTransform(float angle) { angle = (float)CGConversions.DegreesToRadians(angle); Control.RotateCTM(angle); currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeRotation(angle), currentTransform); } public void ScaleTransform(float scaleX, float scaleY) { Control.ScaleCTM(scaleX, scaleY); currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeScale(scaleX, scaleY), currentTransform); } public void MultiplyTransform(IMatrix matrix) { var m = matrix.ToCG(); Control.ConcatCTM(m); currentTransform = CGAffineTransform.Multiply(m, currentTransform); } public void SaveTransform() { transforms.Push(currentTransform); } public void RestoreTransform() { if (transforms.Count <= 0) throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "No saved transform")); RewindTransform(); currentTransform = transforms.Pop(); ApplyTransform(); } public IMatrix CurrentTransform { get { return currentTransform.ToEto(); } } public RectangleF ClipBounds { get { return Control.GetClipBoundingBox().ToEto(); } } public void SetClip(RectangleF rectangle) { RewindTransform(); ResetClip(); clipBounds = currentTransform.TransformRect(rectangle.ToNS()); ApplyClip(); ApplyTransform(); } public void SetClip(IGraphicsPath path) { RewindTransform(); ResetClip(); clipPath = path.Clone(); clipPath.Transform(currentTransform.ToEto()); ApplyClip(); ApplyTransform(); } void ApplyClip() { if (clipPath != null) { Control.SaveState(); Control.AddPath(clipPath.ToCG()); switch (clipPath.FillMode) { case FillMode.Alternate: Control.EOClip(); break; case FillMode.Winding: Control.Clip(); break; default: throw new NotSupportedException(); } } else if (clipBounds != null) { Control.SaveState(); Control.ClipToRect(clipBounds.Value); } } void RewindClip() { if (clipBounds != null || clipPath != null) { Control.RestoreState(); } } void RewindTransform() { Control.RestoreState(); } void ApplyTransform() { Control.SaveState(); Control.ConcatCTM(currentTransform); } void RewindAll() { RewindTransform(); RewindClip(); if (isOffset) { Control.RestoreState(); } } void ApplyAll() { if (isOffset) { Control.SaveState(); Control.TranslateCTM(0.5f, 0.5f); } ApplyClip(); ApplyTransform(); } public void ResetClip() { RewindClip(); clipBounds = null; clipPath = null; } public void Clear(SolidBrush brush) { var rect = Control.GetClipBoundingBox(); Control.ClearRect(rect); if (brush != null) FillRectangle(brush, (float)rect.X, (float)rect.Y, (float)rect.Width, (float)rect.Height); } public void SetFillColorSpace() { Control.SetFillColorSpace(patternColorSpace); } } }
/* ' Copyright (c) 2010 DotNetNuke Corporation ' All rights reserved. ' ' 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.Data; using System; using DotNetNuke.Common.Utilities; using DotNetNuke.Framework.Providers; using Microsoft.ApplicationBlocks.Data; using DotNetNuke.Modules.uDebate.Components; namespace DotNetNuke.Modules.uDebate.Data { /// ----------------------------------------------------------------------------- /// <summary> /// An abstract class for the data access layer /// </summary> /// ----------------------------------------------------------------------------- public class DataProvider { #region "Private Members" private const string ProviderType = "data"; private Framework.Providers.ProviderConfiguration _providerConfiguration = Framework.Providers.ProviderConfiguration.GetProviderConfiguration(ProviderType); private string _connectionString; private string _providerPath; private string _objectQualifier; private string _databaseOwner; private string _moduleDataPrefix = "Forum_"; private string _fullModuleQualifier; #endregion public DataProvider() { // Read the configuration specific information for this provider Framework.Providers.Provider objProvider = (Framework.Providers.Provider)_providerConfiguration.Providers[_providerConfiguration.DefaultProvider]; // This code handles getting the connection string from either the connectionString / appsetting section and uses the connectionstring section by default if it exists. // Get Connection string from web.config _connectionString = DotNetNuke.Common.Utilities.Config.GetConnectionString(); // If above funtion does not return anything then connectionString must be set in the dataprovider section. if (_connectionString == string.Empty) { // Use connection string specified in provider _connectionString = objProvider.Attributes["connectionString"]; } _providerPath = objProvider.Attributes["providerPath"]; _objectQualifier = objProvider.Attributes["objectQualifier"]; if (_objectQualifier != string.Empty & _objectQualifier.EndsWith("_") == false) { _objectQualifier += "_"; } _databaseOwner = objProvider.Attributes["databaseOwner"]; if (_databaseOwner != string.Empty & _databaseOwner.EndsWith(".") == false) { _databaseOwner += "."; } _fullModuleQualifier = _databaseOwner + _objectQualifier + _moduleDataPrefix; } #region "Properties" /// <summary> /// The connection string used by our data provider. /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> public string ConnectionString { get { return _connectionString; } } /// <summary> /// The path of our data provider. /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> public string ProviderPath { get { return _providerPath; } } /// <summary> /// The object qualifier used for the provider (ie. dnn_). /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> public string ObjectQualifier { get { return _objectQualifier; } } /// <summary> /// The database owner used for the provider (ie. dbo). /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> public string DatabaseOwner { get { return _databaseOwner; } } #endregion #region Shared/Static Methods private static DataProvider provider; // return the provider //public static DataProvider Instance() //{ // if (provider == null) // { // const string assembly = "DotNetNuke.Modules.uDebate.Data.SqlDataprovider,uDebate"; // Type objectType = Type.GetType(assembly, true, true); // provider = (DataProvider)Activator.CreateInstance(objectType); // DataCache.SetCache(objectType.FullName, provider); // } // Provider objProvider = ((Provider)_providerConfiguration.Providers[_providerConfiguration.DefaultProvider]); // string _connectionString; // if (!String.IsNullOrEmpty(objProvider.Attributes["connectionStringName"]) && !String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings[objProvider.Attributes["connectionStringName"]])) // { // _connectionString = System.Configuration.ConfigurationManager.AppSettings[objProvider.Attributes["connectionStringName"]]; // } // else // { // _connectionString = objProvider.Attributes["connectionString"]; // } // _providerPath = objProvider.Attributes["providerPath"]; // _objectQualifier = objProvider.Attributes["objectQualifier"]; // if (_objectQualifier != string.Empty & _objectQualifier.EndsWith("_") == false) // { // _objectQualifier += "_"; // } // _databaseOwner = objProvider.Attributes["databaseOwner"]; // if (_databaseOwner != string.Empty & _databaseOwner.EndsWith(".") == false) // { // _databaseOwner += "."; // } // _fullModuleQualifier = _databaseOwner + _objectQualifier + _moduleDataPrefix; // return provider; //} [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Not returning class state information")] public static IDbConnection GetConnection() { const string providerType = "data"; ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration(providerType); Provider objProvider = ((Provider)_providerConfiguration.Providers[_providerConfiguration.DefaultProvider]); string _connectionString; if (!String.IsNullOrEmpty(objProvider.Attributes["connectionStringName"]) && !String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings[objProvider.Attributes["connectionStringName"]])) { _connectionString = System.Configuration.ConfigurationManager.AppSettings[objProvider.Attributes["connectionStringName"]]; } else { _connectionString = objProvider.Attributes["connectionString"]; } IDbConnection newConnection = new System.Data.SqlClient.SqlConnection(); newConnection.ConnectionString = _connectionString.ToString(); newConnection.Open(); return newConnection; } #endregion #region Abstract methods //public abstract IDataReader GetItems(int userId, int portalId); //public abstract IDataReader GetItem(int itemId); #endregion #region "Attachments" public IDataReader Attachment_GetAllByPostID(int PostID) { return (IDataReader)SqlHelper.ExecuteReader(_connectionString, "uDebate_Attachment_GetAllByPostID", PostID); } public IDataReader Attachment_GetAllByUserID(int UserID) { return (IDataReader)SqlHelper.ExecuteReader(_connectionString, "uDebate_Attachment_GetAllByUserID", UserID); } public void Attachment_Update(AttachmentInfo objAttachment) { SqlHelper.ExecuteNonQuery(_connectionString, "uDebate_Attachment_Update", objAttachment.AttachmentID, objAttachment.FileID, objAttachment.PostID, objAttachment.UserID, objAttachment.LocalFileName, objAttachment.Inline); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using InsideInning.Web.API.Areas.HelpPage.Models; namespace InsideInning.Web.API.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 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 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) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using J2N.Text; using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using WritableArrayAttribute = Lucene.Net.Support.WritableArrayAttribute; namespace Lucene.Net.Util { /* * 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. */ /// <summary> /// Represents <see cref="T:char[]"/>, as a slice (offset + Length) into an existing <see cref="T:char[]"/>. /// The <see cref="Chars"/> property should never be <c>null</c>; use /// <see cref="EMPTY_CHARS"/> if necessary. /// <para/> /// @lucene.internal /// </summary> #if FEATURE_SERIALIZABLE [Serializable] #endif public sealed class CharsRef : IComparable<CharsRef>, ICharSequence, IEquatable<CharsRef> // LUCENENET specific - implemented IEquatable<CharsRef> #if FEATURE_CLONEABLE , System.ICloneable #endif { /// <summary> /// An empty character array for convenience </summary> public static readonly char[] EMPTY_CHARS = Arrays.Empty<char>(); bool ICharSequence.HasValue => true; /// <summary> /// The contents of the <see cref="CharsRef"/>. Should never be <c>null</c>. /// </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public char[] Chars { get => chars; set => chars = value ?? throw new ArgumentNullException(nameof(value), "Chars cannot be null"); } private char[] chars; /// <summary> /// Offset of first valid character. </summary> public int Offset { get; internal set; } /// <summary> /// Length of used characters. </summary> public int Length { get; set; } /// <summary> /// Creates a new <see cref="CharsRef"/> initialized an empty array zero-Length /// </summary> public CharsRef() : this(EMPTY_CHARS, 0, 0) { } /// <summary> /// Creates a new <see cref="CharsRef"/> initialized with an array of the given /// <paramref name="capacity"/>. /// </summary> public CharsRef(int capacity) { chars = new char[capacity]; } /// <summary> /// Creates a new <see cref="CharsRef"/> initialized with the given <paramref name="chars"/>, /// <paramref name="offset"/> and <paramref name="length"/>. /// </summary> public CharsRef(char[] chars, int offset, int length) { this.chars = chars; this.Offset = offset; this.Length = length; if (Debugging.AssertsEnabled) Debugging.Assert(IsValid()); } /// <summary> /// Creates a new <see cref="CharsRef"/> initialized with the given <see cref="string"/> character /// array. /// </summary> public CharsRef(string @string) { this.chars = @string.ToCharArray(); this.Offset = 0; this.Length = chars.Length; } /// <summary> /// Returns a shallow clone of this instance (the underlying characters are /// <b>not</b> copied and will be shared by both the returned object and this /// object. /// </summary> /// <seealso cref="DeepCopyOf(CharsRef)"/> public object Clone() { return new CharsRef(chars, Offset, Length); } public override int GetHashCode() { const int prime = 31; int result = 0; int end = Offset + Length; for (int i = Offset; i < end; i++) { result = prime * result + chars[i]; } return result; } public override bool Equals(object other) { if (other == null) { return false; } if (other is CharsRef) { return this.CharsEquals(((CharsRef)other)); } return false; } bool IEquatable<CharsRef>.Equals(CharsRef other) // LUCENENET specific - implemented IEquatable<CharsRef> => CharsEquals(other); public bool CharsEquals(CharsRef other) { if (Length == other.Length) { int otherUpto = other.Offset; char[] otherChars = other.chars; int end = Offset + Length; for (int upto = Offset; upto < end; upto++, otherUpto++) { if (chars[upto] != otherChars[otherUpto]) { return false; } } return true; } else { return false; } } /// <summary> /// Signed <see cref="int"/> order comparison </summary> public int CompareTo(CharsRef other) { if (this == other) { return 0; } char[] aChars = this.chars; int aUpto = this.Offset; char[] bChars = other.chars; int bUpto = other.Offset; int aStop = aUpto + Math.Min(this.Length, other.Length); while (aUpto < aStop) { int aInt = aChars[aUpto++]; int bInt = bChars[bUpto++]; if (aInt > bInt) { return 1; } else if (aInt < bInt) { return -1; } } // One is a prefix of the other, or, they are equal: return this.Length - other.Length; } /// <summary> /// Copies the given <see cref="CharsRef"/> referenced content into this instance. /// </summary> /// <param name="other"> /// The <see cref="CharsRef"/> to copy. </param> public void CopyChars(CharsRef other) { CopyChars(other.chars, other.Offset, other.Length); } /// <summary> /// Used to grow the reference array. /// <para/> /// In general this should not be used as it does not take the offset into account. /// <para/> /// @lucene.internal /// </summary> public void Grow(int newLength) { if (Debugging.AssertsEnabled) Debugging.Assert(Offset == 0); if (chars.Length < newLength) { chars = ArrayUtil.Grow(chars, newLength); } } /// <summary> /// Copies the given array into this <see cref="CharsRef"/>. /// </summary> public void CopyChars(char[] otherChars, int otherOffset, int otherLength) { if (Chars.Length - Offset < otherLength) { chars = new char[otherLength]; Offset = 0; } Array.Copy(otherChars, otherOffset, chars, Offset, otherLength); Length = otherLength; } /// <summary> /// Appends the given array to this <see cref="CharsRef"/>. /// </summary> public void Append(char[] otherChars, int otherOffset, int otherLength) { int newLen = Length + otherLength; if (chars.Length - Offset < newLen) { var newChars = new char[newLen]; Array.Copy(chars, Offset, newChars, 0, Length); Offset = 0; chars = newChars; } Array.Copy(otherChars, otherOffset, chars, Length + Offset, otherLength); Length = newLen; } public override string ToString() { return new string(chars, Offset, Length); } // LUCENENET NOTE: Length field made into property already //public char CharAt(int index) //{ // // NOTE: must do a real check here to meet the specs of CharSequence // if (index < 0 || index >= Length) // { // throw new IndexOutOfRangeException(); // } // return Chars[Offset + index]; //} // LUCENENET specific - added to .NETify public char this[int index] { get { // NOTE: must do a real check here to meet the specs of CharSequence if (index < 0 || index >= Length) { throw new ArgumentOutOfRangeException(nameof(index)); // LUCENENET: Changed exception type to ArgumentOutOfRangeException } return chars[Offset + index]; } } public ICharSequence Subsequence(int startIndex, int length) { // NOTE: must do a real check here to meet the specs of CharSequence //if (start < 0 || end > Length || start > end) //{ // throw new IndexOutOfRangeException(); //} // LUCENENET specific - changed semantics from start/end to startIndex/length to match .NET // From Apache Harmony String class if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); if (startIndex + length > Length) throw new ArgumentOutOfRangeException("", $"{nameof(startIndex)} + {nameof(length)} > {nameof(Length)}"); return new CharsRef(chars, Offset + startIndex, length); } /// @deprecated this comparer is only a transition mechanism [Obsolete("this comparer is only a transition mechanism")] private static readonly IComparer<CharsRef> utf16SortedAsUTF8SortOrder = new Utf16SortedAsUTF8Comparer(); /// @deprecated this comparer is only a transition mechanism [Obsolete("this comparer is only a transition mechanism")] public static IComparer<CharsRef> UTF16SortedAsUTF8Comparer => utf16SortedAsUTF8SortOrder; /// @deprecated this comparer is only a transition mechanism [Obsolete("this comparer is only a transition mechanism")] private class Utf16SortedAsUTF8Comparer : IComparer<CharsRef> { // Only singleton internal Utf16SortedAsUTF8Comparer() { } public virtual int Compare(CharsRef a, CharsRef b) { if (a == b) { return 0; } char[] aChars = a.Chars; int aUpto = a.Offset; char[] bChars = b.Chars; int bUpto = b.Offset; int aStop = aUpto + Math.Min(a.Length, b.Length); while (aUpto < aStop) { char aChar = aChars[aUpto++]; char bChar = bChars[bUpto++]; if (aChar != bChar) { // http://icu-project.org/docs/papers/utf16_code_point_order.html /* aChar != bChar, fix up each one if they're both in or above the surrogate range, then compare them */ if (aChar >= 0xd800 && bChar >= 0xd800) {//LUCENE TO-DO possible truncation or is char 16bit? if (aChar >= 0xe000) { aChar -= (char)0x800; } else { aChar += (char)0x2000; } if (bChar >= 0xe000) { bChar -= (char)0x800; } else { bChar += (char)0x2000; } } /* now aChar and bChar are in code point order */ return (int)aChar - (int)bChar; // int must be 32 bits wide } } // One is a prefix of the other, or, they are equal: return a.Length - b.Length; } } /// <summary> /// Creates a new <see cref="CharsRef"/> that points to a copy of the chars from /// <paramref name="other"/>. /// <para/> /// The returned <see cref="CharsRef"/> will have a Length of <c>other.Length</c> /// and an offset of zero. /// </summary> public static CharsRef DeepCopyOf(CharsRef other) { CharsRef clone = new CharsRef(); clone.CopyChars(other); return clone; } /// <summary> /// Performs internal consistency checks. /// Always returns true (or throws <see cref="InvalidOperationException"/>) /// </summary> public bool IsValid() { if (Chars == null) { throw new InvalidOperationException("chars is null"); } if (Length < 0) { throw new InvalidOperationException("Length is negative: " + Length); } if (Length > Chars.Length) { throw new InvalidOperationException("Length is out of bounds: " + Length + ",chars.Length=" + Chars.Length); } if (Offset < 0) { throw new InvalidOperationException("offset is negative: " + Offset); } if (Offset > Chars.Length) { throw new InvalidOperationException("offset out of bounds: " + Offset + ",chars.Length=" + Chars.Length); } if (Offset + Length < 0) { throw new InvalidOperationException("offset+Length is negative: offset=" + Offset + ",Length=" + Length); } if (Offset + Length > Chars.Length) { throw new InvalidOperationException("offset+Length out of bounds: offset=" + Offset + ",Length=" + Length + ",chars.Length=" + Chars.Length); } return 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.Security; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Globalization { public partial class CompareInfo { private unsafe void InitSort(CultureInfo culture) { _sortName = culture.SortName; m_name = culture._name; _sortName = culture.SortName; if (_invariantMode) { _sortHandle = IntPtr.Zero; } else { const uint LCMAP_SORTHANDLE = 0x20000000; IntPtr handle; int ret = Interop.Kernel32.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero); _sortHandle = ret > 0 ? handle : IntPtr.Zero; } } private static unsafe int FindStringOrdinal( uint dwFindStringOrdinalFlags, string stringSource, int offset, int cchSource, string value, int cchValue, bool bIgnoreCase) { Debug.Assert(!GlobalizationMode.Invariant); fixed (char* pSource = stringSource) fixed (char* pValue = value) { int ret = Interop.Kernel32.FindStringOrdinal( dwFindStringOrdinalFlags, pSource + offset, cchSource, pValue, cchValue, bIgnoreCase ? 1 : 0); return ret < 0 ? ret : ret + offset; } } internal static int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase); } internal static int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase); } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(source != null); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (source.Length == 0) { return 0; } int flags = GetNativeCompareFlags(options); int tmpHash = 0; #if CORECLR tmpHash = InternalGetGlobalizedHashCode(_sortHandle, _sortName, source, source.Length, flags); #else fixed (char* pSource = source) { if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_HASH | (uint)flags, pSource, source.Length, &tmpHash, sizeof(int), null, null, _sortHandle) == 0) { Environment.FailFast("LCMapStringEx failed!"); } } #endif return tmpHash; } private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { Debug.Assert(!GlobalizationMode.Invariant); // Use the OS to compare and then convert the result to expected value by subtracting 2 return Interop.Kernel32.CompareStringOrdinal(string1, count1, string2, count2, true) - 2; } private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(string1 != null); Debug.Assert(string2 != null); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pString1 = string1) fixed (char* pString2 = string2) { int result = Interop.Kernel32.CompareStringEx( pLocaleName, (uint)GetNativeCompareFlags(options), pString1 + offset1, length1, pString2 + offset2, length2, null, null, _sortHandle); if (result == 0) { Environment.FailFast("CompareStringEx failed"); } // Map CompareStringEx return value to -1, 0, 1. return result - 2; } } private unsafe int FindString( uint dwFindNLSStringFlags, string lpStringSource, int startSource, int cchSource, string lpStringValue, int startValue, int cchValue, int *pcchFound) { Debug.Assert(!_invariantMode); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pSource = lpStringSource) fixed (char* pValue = lpStringValue) { char* pS = pSource + startSource; char* pV = pValue + startValue; return Interop.Kernel32.FindNLSStringEx( pLocaleName, dwFindNLSStringFlags, pS, cchSource, pV, cchValue, pcchFound, null, null, _sortHandle); } } internal unsafe int IndexOfCore(String source, String target, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { Debug.Assert(!_invariantMode); Debug.Assert(source != null); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { if (matchLengthPtr != null) *matchLengthPtr = 0; return startIndex; } if (source.Length == 0) { return -1; } if ((options & CompareOptions.Ordinal) != 0) { int retValue = FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false); if (retValue >= 0) { if (matchLengthPtr != null) *matchLengthPtr = target.Length; } return retValue; } else { int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count, target, 0, target.Length, matchLengthPtr); if (retValue >= 0) { return retValue + startIndex; } } return -1; } private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for // and add a precondition that target is not empty. if (target.Length == 0) return startIndex; // keep Whidbey compatibility if ((options & CompareOptions.Ordinal) != 0) { return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true); } else { int retValue = FindString(FIND_FROMEND | (uint) GetNativeCompareFlags(options), source, startIndex - count + 1, count, target, 0, target.Length, null); if (retValue >= 0) { return retValue + startIndex - (count - 1); } } return -1; } private unsafe bool StartsWith(string source, string prefix, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(prefix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, prefix, 0, prefix.Length, null) >= 0; } private unsafe bool EndsWith(string source, string suffix, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(suffix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, suffix, 0, suffix.Length, null) >= 0; } // PAL ends here [NonSerialized] private IntPtr _sortHandle; private const uint LCMAP_SORTKEY = 0x00000400; private const uint LCMAP_HASH = 0x00040000; private const int FIND_STARTSWITH = 0x00100000; private const int FIND_ENDSWITH = 0x00200000; private const int FIND_FROMSTART = 0x00400000; private const int FIND_FROMEND = 0x00800000; // TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false? private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex) { int retValue = -1; int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex; fixed (char* pSource = source, spTarget = target) { char* spSubSource = pSource + sourceStartIndex; if (findLastIndex) { int startPattern = (sourceCount - 1) - targetCount + 1; if (startPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex - sourceCount + 1; } } else { int endPattern = (sourceCount - 1) - targetCount + 1; if (endPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex; } } } return retValue; } private unsafe SortKey CreateSortKey(String source, CompareOptions options) { Debug.Assert(!_invariantMode); if (source == null) { throw new ArgumentNullException(nameof(source)); } Contract.EndContractBlock(); if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } byte [] keyData = null; if (source.Length == 0) { keyData = Array.Empty<byte>(); } else { fixed (char *pSource = source) { int result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options), pSource, source.Length, null, 0, null, null, _sortHandle); if (result == 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "source"); } keyData = new byte[result]; fixed (byte* pBytes = keyData) { result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options), pSource, source.Length, pBytes, keyData.Length, null, null, _sortHandle); } } } return new SortKey(Name, source, options, keyData); } private static unsafe bool IsSortable(char* text, int length) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.Kernel32.IsNLSDefinedString(Interop.Kernel32.COMPARE_STRING, 0, IntPtr.Zero, text, length); } private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead) private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal. private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead) private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols. private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character. private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols. private static int GetNativeCompareFlags(CompareOptions options) { // Use "linguistic casing" by default (load the culture's casing exception tables) int nativeCompareFlags = NORM_LINGUISTIC_CASING; if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; } if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; } if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; } if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; } if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; } if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; } // TODO: Can we try for GetNativeCompareFlags to never // take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special // in some places. // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; } Debug.Assert(((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreWidth | CompareOptions.StringSort)) == 0) || (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled"); return nativeCompareFlags; } private unsafe SortVersion GetSortVersion() { Debug.Assert(!_invariantMode); Interop.Kernel32.NlsVersionInfoEx nlsVersion = new Interop.Kernel32.NlsVersionInfoEx(); nlsVersion.dwNLSVersionInfoSize = Marshal.SizeOf(typeof(Interop.Kernel32.NlsVersionInfoEx)); Interop.Kernel32.GetNLSVersionEx(Interop.Kernel32.COMPARE_STRING, _sortName, &nlsVersion); return new SortVersion( nlsVersion.dwNLSVersion, nlsVersion.dwEffectiveId == 0 ? LCID : nlsVersion.dwEffectiveId, nlsVersion.guidCustomVersion); } #if CORECLR // Get a locale sensitive sort hash code from native code -- COMNlsInfo::InternalGetGlobalizedHashCode [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern int InternalGetGlobalizedHashCode(IntPtr handle, string localeName, string source, int length, int dwFlags); #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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SubtractInt16() { var test = new SimpleBinaryOpTest__SubtractInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractInt16 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Int16); private static Int16[] _data1 = new Int16[ElementCount]; private static Int16[] _data2 = new Int16[ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private SimpleBinaryOpTest__DataTable<Int16> _dataTable; static SimpleBinaryOpTest__SubtractInt16() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__SubtractInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int16>(_data1, _data2, new Int16[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Subtract( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Subtract( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractInt16(); var result = Avx2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[ElementCount]; Int16[] inArray2 = new Int16[ElementCount]; Int16[] outArray = new Int16[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[ElementCount]; Int16[] inArray2 = new Int16[ElementCount]; Int16[] outArray = new Int16[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { if ((short)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((short)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<Int16>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.Reflection; using Nini.Config; using log4net; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Data; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; namespace OpenSim.Services.GridService { public class GridService : GridServiceBase, IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string LogHeader = "[GRID SERVICE]"; private bool m_DeleteOnUnregister = true; private static GridService m_RootInstance = null; protected IConfigSource m_config; protected static HypergridLinker m_HypergridLinker; protected IAuthenticationService m_AuthenticationService = null; protected bool m_AllowDuplicateNames = false; protected bool m_AllowHypergridMapSearch = false; protected bool m_SuppressVarregionOverlapCheckOnRegistration = false; private static Dictionary<string,object> m_ExtraFeatures = new Dictionary<string, object>(); public GridService(IConfigSource config) : base(config) { m_log.DebugFormat("[GRID SERVICE]: Starting..."); m_config = config; IConfig gridConfig = config.Configs["GridService"]; bool suppressConsoleCommands = false; if (gridConfig != null) { m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true); string authService = gridConfig.GetString("AuthenticationService", String.Empty); if (authService != String.Empty) { Object[] args = new Object[] { config }; m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args); } m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames); m_AllowHypergridMapSearch = gridConfig.GetBoolean("AllowHypergridMapSearch", m_AllowHypergridMapSearch); m_SuppressVarregionOverlapCheckOnRegistration = gridConfig.GetBoolean("SuppressVarregionOverlapCheckOnRegistration", m_SuppressVarregionOverlapCheckOnRegistration); // This service is also used locally by a simulator running in grid mode. This switches prevents // inappropriate console commands from being registered suppressConsoleCommands = gridConfig.GetBoolean("SuppressConsoleCommands", suppressConsoleCommands); } if (m_RootInstance == null) { m_RootInstance = this; if (!suppressConsoleCommands && MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand("Regions", true, "deregister region id", "deregister region id <region-id>+", "Deregister a region manually.", String.Empty, HandleDeregisterRegion); MainConsole.Instance.Commands.AddCommand("Regions", true, "show regions", "show regions", "Show details on all regions", String.Empty, HandleShowRegions); MainConsole.Instance.Commands.AddCommand("Regions", true, "show region name", "show region name <Region name>", "Show details on a region", String.Empty, HandleShowRegion); MainConsole.Instance.Commands.AddCommand("Regions", true, "show region at", "show region at <x-coord> <y-coord>", "Show details on a region at the given co-ordinate.", "For example, show region at 1000 1000", HandleShowRegionAt); MainConsole.Instance.Commands.AddCommand("General", true, "show grid size", "show grid size", "Show the current grid size (excluding hyperlink references)", String.Empty, HandleShowGridSize); MainConsole.Instance.Commands.AddCommand("Regions", true, "set region flags", "set region flags <Region name> <flags>", "Set database flags for region", String.Empty, HandleSetFlags); } if (!suppressConsoleCommands) SetExtraServiceURLs(config); m_HypergridLinker = new HypergridLinker(m_config, this, m_Database); } } private void SetExtraServiceURLs(IConfigSource config) { IConfig loginConfig = config.Configs["LoginService"]; IConfig gridConfig = config.Configs["GridService"]; if (loginConfig == null || gridConfig == null) return; string configVal; configVal = loginConfig.GetString("SearchURL", string.Empty); if (!string.IsNullOrEmpty(configVal)) m_ExtraFeatures["search-server-url"] = configVal; configVal = loginConfig.GetString("MapTileURL", string.Empty); if (!string.IsNullOrEmpty(configVal)) { // This URL must end with '/', the viewer doesn't check configVal = configVal.Trim(); if (!configVal.EndsWith("/")) configVal = configVal + "/"; m_ExtraFeatures["map-server-url"] = configVal; } configVal = loginConfig.GetString("DestinationGuide", string.Empty); if (!string.IsNullOrEmpty(configVal)) m_ExtraFeatures["destination-guide-url"] = configVal; configVal = Util.GetConfigVarFromSections<string>( config, "GatekeeperURI", new string[] { "Startup", "Hypergrid" }, String.Empty); if (!string.IsNullOrEmpty(configVal)) m_ExtraFeatures["GridURL"] = configVal; configVal = Util.GetConfigVarFromSections<string>( config, "GridName", new string[] { "Const", "Hypergrid" }, String.Empty); if (string.IsNullOrEmpty(configVal)) configVal = Util.GetConfigVarFromSections<string>( config, "gridname", new string[] { "GridInfo" }, String.Empty); if (!string.IsNullOrEmpty(configVal)) m_ExtraFeatures["GridName"] = configVal; m_ExtraFeatures["ExportSupported"] = gridConfig.GetString("ExportSupported", "true"); } #region IGridService public string RegisterRegion(UUID scopeID, GridRegion regionInfos) { IConfig gridConfig = m_config.Configs["GridService"]; if (regionInfos.RegionID == UUID.Zero) return "Invalid RegionID - cannot be zero UUID"; String reason = "Region overlaps another region"; // we should not need to check for overlaps RegionData region = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID); if ((region != null) && (region.RegionID != regionInfos.RegionID)) { // If not same ID and same coordinates, this new region has conflicts and can't be registered. m_log.WarnFormat("{0} Register region conflict in scope {1}. {2}", LogHeader, scopeID, reason); return reason; } if (region != null) { // There is a preexisting record // // Get it's flags // OpenSim.Framework.RegionFlags rflags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(region.Data["flags"]); // Is this a reservation? // if ((rflags & OpenSim.Framework.RegionFlags.Reservation) != 0) { // Regions reserved for the null key cannot be taken. if ((string)region.Data["PrincipalID"] == UUID.Zero.ToString()) return "Region location is reserved"; // Treat it as an auth request // // NOTE: Fudging the flags value here, so these flags // should not be used elsewhere. Don't optimize // this with the later retrieval of the same flags! rflags |= OpenSim.Framework.RegionFlags.Authenticate; } if ((rflags & OpenSim.Framework.RegionFlags.Authenticate) != 0) { // Can we authenticate at all? // if (m_AuthenticationService == null) return "No authentication possible"; if (!m_AuthenticationService.Verify(new UUID(region.Data["PrincipalID"].ToString()), regionInfos.Token, 30)) return "Bad authentication"; } } // If we get here, the destination is clear. Now for the real check. if (!m_AllowDuplicateNames) { List<RegionData> dupe = m_Database.Get(Util.EscapeForLike(regionInfos.RegionName), scopeID); if (dupe != null && dupe.Count > 0) { foreach (RegionData d in dupe) { if (d.RegionID != regionInfos.RegionID) { m_log.WarnFormat("[GRID SERVICE]: Region tried to register using a duplicate name. New region: {0} ({1}), existing region: {2} ({3}).", regionInfos.RegionName, regionInfos.RegionID, d.RegionName, d.RegionID); return "Duplicate region name"; } } } } // If there is an old record for us, delete it if it is elsewhere. region = m_Database.Get(regionInfos.RegionID, scopeID); if ((region != null) && (region.RegionID == regionInfos.RegionID) && ((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY))) { if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.NoMove) != 0) return "Can't move this region"; if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.LockedOut) != 0) return "Region locked out"; // Region reregistering in other coordinates. Delete the old entry m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.", regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY); try { m_Database.Delete(regionInfos.RegionID); } catch (Exception e) { m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e); } } // Everything is ok, let's register RegionData rdata = RegionInfo2RegionData(regionInfos); rdata.ScopeID = scopeID; if (region != null) { int oldFlags = Convert.ToInt32(region.Data["flags"]); oldFlags &= ~(int)OpenSim.Framework.RegionFlags.Reservation; rdata.Data["flags"] = oldFlags.ToString(); // Preserve flags } else { rdata.Data["flags"] = "0"; if ((gridConfig != null) && rdata.RegionName != string.Empty) { int newFlags = 0; string regionName = rdata.RegionName.Trim().Replace(' ', '_'); newFlags = ParseFlags(newFlags, gridConfig.GetString("DefaultRegionFlags", String.Empty)); newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty)); newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + rdata.RegionID.ToString(), String.Empty)); rdata.Data["flags"] = newFlags.ToString(); } } int flags = Convert.ToInt32(rdata.Data["flags"]); flags |= (int)OpenSim.Framework.RegionFlags.RegionOnline; rdata.Data["flags"] = flags.ToString(); try { rdata.Data["last_seen"] = Util.UnixTimeSinceEpoch(); m_Database.Store(rdata); } catch (Exception e) { m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e); } m_log.DebugFormat ("[GRID SERVICE]: Region {0} ({1}, {2}x{3}) registered at {4},{5} with flags {6}", regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionSizeX, regionInfos.RegionSizeY, regionInfos.RegionCoordX, regionInfos.RegionCoordY, (OpenSim.Framework.RegionFlags)flags); return String.Empty; } /// <summary> /// Search the region map for regions conflicting with this region. /// The region to be added is passed and we look for any existing regions that are /// in the requested location, that are large varregions that overlap this region, or /// are previously defined regions that would lie under this new region. /// </summary> /// <param name="regionInfos">Information on region requested to be added to the world map</param> /// <param name="scopeID">Grid id for region</param> /// <param name="reason">The reason the returned region conflicts with passed region</param> /// <returns></returns> private RegionData FindAnyConflictingRegion(GridRegion regionInfos, UUID scopeID, out string reason) { reason = "Reregistration"; // First see if there is an existing region right where this region is trying to go // (We keep this result so it can be returned if suppressing errors) RegionData noErrorRegion = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID); RegionData region = noErrorRegion; if (region != null && region.RegionID == regionInfos.RegionID && region.sizeX == regionInfos.RegionSizeX && region.sizeY == regionInfos.RegionSizeY) { // If this seems to be exactly the same region, return this as it could be // a re-registration (permissions checked by calling routine). m_log.DebugFormat("{0} FindAnyConflictingRegion: re-register of {1}", LogHeader, RegionString(regionInfos)); return region; } // No region exactly there or we're resizing an existing region. // Fetch regions that could be varregions overlapping requested location. int xmin = regionInfos.RegionLocX - (int)Constants.MaximumRegionSize + 10; int xmax = regionInfos.RegionLocX; int ymin = regionInfos.RegionLocY - (int)Constants.MaximumRegionSize + 10; int ymax = regionInfos.RegionLocY; List<RegionData> rdatas = m_Database.Get(xmin, ymin, xmax, ymax, scopeID); foreach (RegionData rdata in rdatas) { // m_log.DebugFormat("{0} FindAnyConflictingRegion: find existing. Checking {1}", LogHeader, RegionString(rdata) ); if ( (rdata.posX + rdata.sizeX > regionInfos.RegionLocX) && (rdata.posY + rdata.sizeY > regionInfos.RegionLocY) ) { region = rdata; m_log.WarnFormat("{0} FindAnyConflictingRegion: conflict of {1} by existing varregion {2}", LogHeader, RegionString(regionInfos), RegionString(region)); reason = String.Format("Region location is overlapped by existing varregion {0}", RegionString(region)); if (m_SuppressVarregionOverlapCheckOnRegistration) region = noErrorRegion; return region; } } // There isn't a region that overlaps this potential region. // See if this potential region overlaps an existing region. // First, a shortcut of not looking for overlap if new region is legacy region sized // and connot overlap anything. if (regionInfos.RegionSizeX != Constants.RegionSize || regionInfos.RegionSizeY != Constants.RegionSize) { // trim range looked for so we don't pick up neighbor regions just off the edges xmin = regionInfos.RegionLocX; xmax = regionInfos.RegionLocX + regionInfos.RegionSizeX - 10; ymin = regionInfos.RegionLocY; ymax = regionInfos.RegionLocY + regionInfos.RegionSizeY - 10; rdatas = m_Database.Get(xmin, ymin, xmax, ymax, scopeID); // If the region is being resized, the found region could be ourself. foreach (RegionData rdata in rdatas) { // m_log.DebugFormat("{0} FindAnyConflictingRegion: see if overlap. Checking {1}", LogHeader, RegionString(rdata) ); if (region == null || region.RegionID != regionInfos.RegionID) { region = rdata; m_log.WarnFormat("{0} FindAnyConflictingRegion: conflict of varregion {1} overlaps existing region {2}", LogHeader, RegionString(regionInfos), RegionString(region)); reason = String.Format("Region {0} would overlap existing region {1}", RegionString(regionInfos), RegionString(region)); if (m_SuppressVarregionOverlapCheckOnRegistration) region = noErrorRegion; return region; } } } // If we get here, region is either null (nothing found here) or // is the non-conflicting region found at the location being requested. return region; } // String describing name and region location of passed region private String RegionString(RegionData reg) { return String.Format("{0}/{1} at <{2},{3}>", reg.RegionName, reg.RegionID, reg.coordX, reg.coordY); } // String describing name and region location of passed region private String RegionString(GridRegion reg) { return String.Format("{0}/{1} at <{2},{3}>", reg.RegionName, reg.RegionID, reg.RegionCoordX, reg.RegionCoordY); } public bool DeregisterRegion(UUID regionID) { RegionData region = m_Database.Get(regionID, UUID.Zero); if (region == null) return false; m_log.DebugFormat( "[GRID SERVICE]: Deregistering region {0} ({1}) at {2}-{3}", region.RegionName, region.RegionID, region.coordX, region.coordY); int flags = Convert.ToInt32(region.Data["flags"]); if ((!m_DeleteOnUnregister) || ((flags & (int)OpenSim.Framework.RegionFlags.Persistent) != 0)) { flags &= ~(int)OpenSim.Framework.RegionFlags.RegionOnline; region.Data["flags"] = flags.ToString(); region.Data["last_seen"] = Util.UnixTimeSinceEpoch(); try { m_Database.Store(region); } catch (Exception e) { m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e); } return true; } return m_Database.Delete(regionID); } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { List<GridRegion> rinfos = new List<GridRegion>(); RegionData region = m_Database.Get(regionID, scopeID); if (region != null) { List<RegionData> rdatas = m_Database.Get( region.posX - 1, region.posY - 1, region.posX + region.sizeX + 1, region.posY + region.sizeY + 1, scopeID); foreach (RegionData rdata in rdatas) { if (rdata.RegionID != regionID) { int flags = Convert.ToInt32(rdata.Data["flags"]); if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0) // no hyperlinks as neighbours rinfos.Add(RegionData2RegionInfo(rdata)); } } // string rNames = ""; // foreach (GridRegion gr in rinfos) // rNames += gr.RegionName + ","; // m_log.DebugFormat("{0} region {1} has {2} neighbours ({3})", // LogHeader, region.RegionName, rinfos.Count, rNames); } else { m_log.WarnFormat( "[GRID SERVICE]: GetNeighbours() called for scope {0}, region {1} but no such region found", scopeID, regionID); } return rinfos; } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { RegionData rdata = m_Database.Get(regionID, scopeID); if (rdata != null) return RegionData2RegionInfo(rdata); return null; } // Get a region given its base coordinates. // NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST // be the base coordinate of the region. // The snapping is technically unnecessary but is harmless because regions are always // multiples of the legacy region size (256). public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { uint regionX = Util.WorldToRegionLoc((uint)x); uint regionY = Util.WorldToRegionLoc((uint)y); int snapX = (int)Util.RegionToWorldLoc(regionX); int snapY = (int)Util.RegionToWorldLoc(regionY); RegionData rdata = m_Database.Get(snapX, snapY, scopeID); if (rdata != null) { m_log.DebugFormat("{0} GetRegionByPosition. Found region {1} in database. Pos=<{2},{3}>", LogHeader, rdata.RegionName, regionX, regionY); return RegionData2RegionInfo(rdata); } else { m_log.DebugFormat("{0} GetRegionByPosition. Did not find region in database. Pos=<{1},{2}>", LogHeader, regionX, regionY); return null; } } public GridRegion GetRegionByName(UUID scopeID, string name) { List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name), scopeID); if ((rdatas != null) && (rdatas.Count > 0)) return RegionData2RegionInfo(rdatas[0]); // get the first if (m_AllowHypergridMapSearch) { GridRegion r = GetHypergridRegionByName(scopeID, name); if (r != null) return r; } return null; } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { // m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name); List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name) + "%", scopeID); int count = 0; List<GridRegion> rinfos = new List<GridRegion>(); if (rdatas != null) { // m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count); foreach (RegionData rdata in rdatas) { if (count++ < maxNumber) rinfos.Add(RegionData2RegionInfo(rdata)); } } if (m_AllowHypergridMapSearch && (rdatas == null || (rdatas != null && rdatas.Count == 0))) { GridRegion r = GetHypergridRegionByName(scopeID, name); if (r != null) rinfos.Add(r); } return rinfos; } /// <summary> /// Get a hypergrid region. /// </summary> /// <param name="scopeID"></param> /// <param name="name"></param> /// <returns>null if no hypergrid region could be found.</returns> protected GridRegion GetHypergridRegionByName(UUID scopeID, string name) { if (name.Contains(".")) return m_HypergridLinker.LinkRegion(scopeID, name); else return null; } public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize; int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize; int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize; int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize; List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID); List<GridRegion> rinfos = new List<GridRegion>(); foreach (RegionData rdata in rdatas) rinfos.Add(RegionData2RegionInfo(rdata)); return rinfos; } #endregion #region Data structure conversions public RegionData RegionInfo2RegionData(GridRegion rinfo) { RegionData rdata = new RegionData(); rdata.posX = (int)rinfo.RegionLocX; rdata.posY = (int)rinfo.RegionLocY; rdata.sizeX = rinfo.RegionSizeX; rdata.sizeY = rinfo.RegionSizeY; rdata.RegionID = rinfo.RegionID; rdata.RegionName = rinfo.RegionName; rdata.Data = rinfo.ToKeyValuePairs(); rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY); rdata.Data["owner_uuid"] = rinfo.EstateOwner.ToString(); return rdata; } public GridRegion RegionData2RegionInfo(RegionData rdata) { GridRegion rinfo = new GridRegion(rdata.Data); rinfo.RegionLocX = rdata.posX; rinfo.RegionLocY = rdata.posY; rinfo.RegionSizeX = rdata.sizeX; rinfo.RegionSizeY = rdata.sizeY; rinfo.RegionID = rdata.RegionID; rinfo.RegionName = rdata.RegionName; rinfo.ScopeID = rdata.ScopeID; return rinfo; } #endregion public List<GridRegion> GetDefaultRegions(UUID scopeID) { List<GridRegion> ret = new List<GridRegion>(); List<RegionData> regions = m_Database.GetDefaultRegions(scopeID); foreach (RegionData r in regions) { if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0) ret.Add(RegionData2RegionInfo(r)); } m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count); return ret; } public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID) { List<GridRegion> ret = new List<GridRegion>(); List<RegionData> regions = m_Database.GetDefaultHypergridRegions(scopeID); foreach (RegionData r in regions) { if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0) ret.Add(RegionData2RegionInfo(r)); } int hgDefaultRegionsFoundOnline = regions.Count; // For now, hypergrid default regions will always be given precedence but we will also return simple default // regions in case no specific hypergrid regions are specified. ret.AddRange(GetDefaultRegions(scopeID)); int normalDefaultRegionsFoundOnline = ret.Count - hgDefaultRegionsFoundOnline; m_log.DebugFormat( "[GRID SERVICE]: GetDefaultHypergridRegions returning {0} hypergrid default and {1} normal default regions", hgDefaultRegionsFoundOnline, normalDefaultRegionsFoundOnline); return ret; } public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y) { List<GridRegion> ret = new List<GridRegion>(); List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y); foreach (RegionData r in regions) { if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0) ret.Add(RegionData2RegionInfo(r)); } m_log.DebugFormat("[GRID SERVICE]: Fallback returned {0} regions", ret.Count); return ret; } public List<GridRegion> GetHyperlinks(UUID scopeID) { List<GridRegion> ret = new List<GridRegion>(); List<RegionData> regions = m_Database.GetHyperlinks(scopeID); foreach (RegionData r in regions) { if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0) ret.Add(RegionData2RegionInfo(r)); } m_log.DebugFormat("[GRID SERVICE]: Hyperlinks returned {0} regions", ret.Count); return ret; } public int GetRegionFlags(UUID scopeID, UUID regionID) { RegionData region = m_Database.Get(regionID, scopeID); if (region != null) { int flags = Convert.ToInt32(region.Data["flags"]); //m_log.DebugFormat("[GRID SERVICE]: Request for flags of {0}: {1}", regionID, flags); return flags; } else return -1; } private void HandleDeregisterRegion(string module, string[] cmd) { if (cmd.Length < 4) { MainConsole.Instance.Output("Usage: degregister region id <region-id>+"); return; } for (int i = 3; i < cmd.Length; i++) { string rawRegionUuid = cmd[i]; UUID regionUuid; if (!UUID.TryParse(rawRegionUuid, out regionUuid)) { MainConsole.Instance.OutputFormat("{0} is not a valid region uuid", rawRegionUuid); return; } GridRegion region = GetRegionByUUID(UUID.Zero, regionUuid); if (region == null) { MainConsole.Instance.OutputFormat("No region with UUID {0}", regionUuid); return; } if (DeregisterRegion(regionUuid)) { MainConsole.Instance.OutputFormat("Deregistered {0} {1}", region.RegionName, regionUuid); } else { // I don't think this can ever occur if we know that the region exists. MainConsole.Instance.OutputFormat("Error deregistering {0} {1}", region.RegionName, regionUuid); } } } private void HandleShowRegions(string module, string[] cmd) { if (cmd.Length != 2) { MainConsole.Instance.Output("Syntax: show regions"); return; } List<RegionData> regions = m_Database.Get(int.MinValue, int.MinValue, int.MaxValue, int.MaxValue, UUID.Zero); OutputRegionsToConsoleSummary(regions); } private void HandleShowGridSize(string module, string[] cmd) { List<RegionData> regions = m_Database.Get(int.MinValue, int.MinValue, int.MaxValue, int.MaxValue, UUID.Zero); double size = 0; foreach (RegionData region in regions) { int flags = Convert.ToInt32(region.Data["flags"]); if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0) size += region.sizeX * region.sizeY; } MainConsole.Instance.Output("This is a very rough approximation."); MainConsole.Instance.Output("Although it will not count regions that are actually links to others over the Hypergrid, "); MainConsole.Instance.Output("it will count regions that are inactive but were not deregistered from the grid service"); MainConsole.Instance.Output("(e.g. simulator crashed rather than shutting down cleanly).\n"); MainConsole.Instance.OutputFormat("Grid size: {0} km squared.", size / 1000000); } private void HandleShowRegion(string module, string[] cmd) { if (cmd.Length != 4) { MainConsole.Instance.Output("Syntax: show region name <region name>"); return; } string regionName = cmd[3]; List<RegionData> regions = m_Database.Get(Util.EscapeForLike(regionName), UUID.Zero); if (regions == null || regions.Count < 1) { MainConsole.Instance.Output("No region with name {0} found", regionName); return; } OutputRegionsToConsole(regions); } private void HandleShowRegionAt(string module, string[] cmd) { if (cmd.Length != 5) { MainConsole.Instance.Output("Syntax: show region at <x-coord> <y-coord>"); return; } uint x, y; if (!uint.TryParse(cmd[3], out x)) { MainConsole.Instance.Output("x-coord must be an integer"); return; } if (!uint.TryParse(cmd[4], out y)) { MainConsole.Instance.Output("y-coord must be an integer"); return; } RegionData region = m_Database.Get((int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y), UUID.Zero); if (region == null) { MainConsole.Instance.OutputFormat("No region found at {0},{1}", x, y); return; } OutputRegionToConsole(region); } private void OutputRegionToConsole(RegionData r) { OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]); ConsoleDisplayList dispList = new ConsoleDisplayList(); dispList.AddRow("Region Name", r.RegionName); dispList.AddRow("Region ID", r.RegionID); dispList.AddRow("Location", string.Format("{0},{1}", r.coordX, r.coordY)); dispList.AddRow("Size", string.Format("{0}x{1}", r.sizeX, r.sizeY)); dispList.AddRow("URI", r.Data["serverURI"]); dispList.AddRow("Owner ID", r.Data["owner_uuid"]); dispList.AddRow("Flags", flags); MainConsole.Instance.Output(dispList.ToString()); } private void OutputRegionsToConsole(List<RegionData> regions) { foreach (RegionData r in regions) OutputRegionToConsole(r); } private void OutputRegionsToConsoleSummary(List<RegionData> regions) { ConsoleDisplayTable dispTable = new ConsoleDisplayTable(); dispTable.AddColumn("Name", 44); dispTable.AddColumn("ID", 36); dispTable.AddColumn("Position", 11); dispTable.AddColumn("Size", 11); dispTable.AddColumn("Flags", 60); foreach (RegionData r in regions) { OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]); dispTable.AddRow( r.RegionName, r.RegionID.ToString(), string.Format("{0},{1}", r.coordX, r.coordY), string.Format("{0}x{1}", r.sizeX, r.sizeY), flags.ToString()); } MainConsole.Instance.Output(dispTable.ToString()); } private int ParseFlags(int prev, string flags) { OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)prev; string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries); foreach (string p in parts) { int val; try { if (p.StartsWith("+")) { val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1)); f |= (OpenSim.Framework.RegionFlags)val; } else if (p.StartsWith("-")) { val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1)); f &= ~(OpenSim.Framework.RegionFlags)val; } else { val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p); f |= (OpenSim.Framework.RegionFlags)val; } } catch (Exception) { MainConsole.Instance.Output("Error in flag specification: " + p); } } return (int)f; } private void HandleSetFlags(string module, string[] cmd) { if (cmd.Length < 5) { MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>"); return; } List<RegionData> regions = m_Database.Get(Util.EscapeForLike(cmd[3]), UUID.Zero); if (regions == null || regions.Count < 1) { MainConsole.Instance.Output("Region not found"); return; } foreach (RegionData r in regions) { int flags = Convert.ToInt32(r.Data["flags"]); flags = ParseFlags(flags, cmd[4]); r.Data["flags"] = flags.ToString(); OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)flags; MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f)); m_Database.Store(r); } } /// <summary> /// Gets the grid extra service URls we wish for the region to send in OpenSimExtras to dynamically refresh /// parameters in the viewer used to access services like map, search and destination guides. /// <para>see "SimulatorFeaturesModule" </para> /// </summary> /// <returns> /// The grid extra service URls. /// </returns> public Dictionary<string,object> GetExtraFeatures() { return m_ExtraFeatures; } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using UnityEditor; using UnityEngine; namespace PlayFab.PfEditor { public class PlayFabEditorSDKTools : UnityEditor.Editor { private const int buttonWidth = 150; public static bool IsInstalled { get { return GetPlayFabSettings() != null; } } private static Type playFabSettingsType = null; private static string installedSdkVersion = string.Empty; private static string latestSdkVersion = string.Empty; private static UnityEngine.Object sdkFolder; private static UnityEngine.Object _previousSdkFolderPath; private static bool isObjectFieldActive; private static bool isInitialized; //used to check once, gets reset after each compile; public static bool isSdkSupported = true; public static void DrawSdkPanel() { if (!isInitialized) { //SDK is installed. CheckSdkVersion(); isInitialized = true; GetLatestSdkVersion(); sdkFolder = FindSdkAsset(); if (sdkFolder != null) { PlayFabEditorPrefsSO.Instance.SdkPath = AssetDatabase.GetAssetPath(sdkFolder); PlayFabEditorDataService.SaveEnvDetails(); } } if (IsInstalled) ShowSdkInstalledMenu(); else ShowSdkNotInstalledMenu(); } private static void ShowSdkInstalledMenu() { isObjectFieldActive = sdkFolder == null; if (_previousSdkFolderPath != sdkFolder) { // something changed, better save the result. _previousSdkFolderPath = sdkFolder; PlayFabEditorPrefsSO.Instance.SdkPath = (AssetDatabase.GetAssetPath(sdkFolder)); PlayFabEditorDataService.SaveEnvDetails(); isObjectFieldActive = false; } var labelStyle = new GUIStyle(PlayFabEditorHelper.uiStyle.GetStyle("titleLabel")); using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"))) { EditorGUILayout.LabelField(string.Format("SDK {0} is installed", string.IsNullOrEmpty(installedSdkVersion) ? "Unknown" : installedSdkVersion), labelStyle, GUILayout.MinWidth(EditorGUIUtility.currentViewWidth)); if (!isObjectFieldActive) { GUI.enabled = false; } else { EditorGUILayout.LabelField( "An SDK was detected, but we were unable to find the directory. Drag-and-drop the top-level PlayFab SDK folder below.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt")); } using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { GUILayout.FlexibleSpace(); sdkFolder = EditorGUILayout.ObjectField(sdkFolder, typeof(UnityEngine.Object), false, GUILayout.MaxWidth(200)); GUILayout.FlexibleSpace(); } if (!isObjectFieldActive) { // this is a hack to prevent our "block while loading technique" from breaking up at this point. GUI.enabled = !EditorApplication.isCompiling && PlayFabEditor.blockingRequests.Count == 0; } if (isSdkSupported && sdkFolder != null) { using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { GUILayout.FlexibleSpace(); if (GUILayout.Button("REMOVE SDK", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200))) { RemoveSdk(); } GUILayout.FlexibleSpace(); } } } if (sdkFolder != null) { using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"))) { isSdkSupported = false; string[] versionNumber = !string.IsNullOrEmpty(installedSdkVersion) ? installedSdkVersion.Split('.') : new string[0]; var numerical = 0; if (string.IsNullOrEmpty(installedSdkVersion) || versionNumber == null || versionNumber.Length == 0 || (versionNumber.Length > 0 && int.TryParse(versionNumber[0], out numerical) && numerical < 2)) { //older version of the SDK using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { EditorGUILayout.LabelField("Most of the Editor Extensions depend on SDK versions >2.0. Consider upgrading to the get most features.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt")); } using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { GUILayout.FlexibleSpace(); if (GUILayout.Button("READ THE UPGRADE GUIDE", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32))) { Application.OpenURL("https://github.com/PlayFab/UnitySDK/blob/master/UPGRADE.md"); } GUILayout.FlexibleSpace(); } } else if (numerical >= 2) { isSdkSupported = true; } using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { if (ShowSDKUpgrade() && isSdkSupported) { GUILayout.FlexibleSpace(); if (GUILayout.Button("Upgrade to " + latestSdkVersion, PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MinHeight(32))) { UpgradeSdk(); } GUILayout.FlexibleSpace(); } else if (isSdkSupported) { GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("You have the latest SDK!", labelStyle, GUILayout.MinHeight(32)); GUILayout.FlexibleSpace(); } } } } if (isSdkSupported && string.IsNullOrEmpty(PlayFabEditorDataService.SharedSettings.TitleId)) { using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"))) { EditorGUILayout.LabelField("Before making PlayFab API calls, the SDK must be configured to your PlayFab Title.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt")); using (new UnityHorizontal()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("SET MY TITLE", PlayFabEditorHelper.uiStyle.GetStyle("textButton"))) { PlayFabEditorMenu.OnSettingsClicked(); } GUILayout.FlexibleSpace(); } } } using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"))) { GUILayout.FlexibleSpace(); if (GUILayout.Button("VIEW RELEASE NOTES", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200))) { Application.OpenURL("https://api.playfab.com/releaseNotes/"); } GUILayout.FlexibleSpace(); } } private static void ShowSdkNotInstalledMenu() { using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"))) { var labelStyle = new GUIStyle(PlayFabEditorHelper.uiStyle.GetStyle("titleLabel")); EditorGUILayout.LabelField("No SDK is installed.", labelStyle, GUILayout.MinWidth(EditorGUIUtility.currentViewWidth)); GUILayout.Space(20); using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"))) { GUILayout.FlexibleSpace(); if (GUILayout.Button("Refresh", PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth), GUILayout.MinHeight(32))) playFabSettingsType = null; GUILayout.FlexibleSpace(); if (GUILayout.Button("Install PlayFab SDK", PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth), GUILayout.MinHeight(32))) ImportLatestSDK(); GUILayout.FlexibleSpace(); } } } public static void ImportLatestSDK() { PlayFabEditorHttp.MakeDownloadCall("https://api.playfab.com/sdks/download/unity-via-edex", (fileName) => { Debug.Log("PlayFab SDK Install: Complete"); AssetDatabase.ImportPackage(fileName, false); PlayFabEditorPrefsSO.Instance.SdkPath = PlayFabEditorHelper.DEFAULT_SDK_LOCATION; PlayFabEditorDataService.SaveEnvDetails(); }); } public static Type GetPlayFabSettings() { if (playFabSettingsType == typeof(object)) return null; // Sentinel value to indicate that PlayFabSettings doesn't exist if (playFabSettingsType != null) return playFabSettingsType; playFabSettingsType = typeof(object); // Sentinel value to indicate that PlayFabSettings doesn't exist var allAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in allAssemblies) foreach (var eachType in assembly.GetTypes()) if (eachType.Name == PlayFabEditorHelper.PLAYFAB_SETTINGS_TYPENAME) playFabSettingsType = eachType; //if (playFabSettingsType == typeof(object)) // Debug.LogWarning("Should not have gotten here: " + allAssemblies.Length); //else // Debug.Log("Found Settings: " + allAssemblies.Length + ", " + playFabSettingsType.Assembly.FullName); return playFabSettingsType == typeof(object) ? null : playFabSettingsType; } private static void CheckSdkVersion() { if (!string.IsNullOrEmpty(installedSdkVersion)) return; var types = new List<Type>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { try { foreach (var type in assembly.GetTypes()) if (type.Name == "PlayFabVersion" || type.Name == PlayFabEditorHelper.PLAYFAB_SETTINGS_TYPENAME) types.Add(type); } catch (ReflectionTypeLoadException) { // For this failure, silently skip this assembly unless we have some expectation that it contains PlayFab if (assembly.FullName.StartsWith("Assembly-CSharp")) // The standard "source-code in unity proj" assembly name Debug.LogWarning("PlayFab EdEx Error, failed to access the main CSharp assembly that probably contains PlayFab. Please report this on the PlayFab Forums"); continue; } } foreach (var type in types) { foreach (var property in type.GetProperties()) if (property.Name == "SdkVersion" || property.Name == "SdkRevision") installedSdkVersion += property.GetValue(property, null).ToString(); foreach (var field in type.GetFields()) if (field.Name == "SdkVersion" || field.Name == "SdkRevision") installedSdkVersion += field.GetValue(field).ToString(); } } private static UnityEngine.Object FindSdkAsset() { UnityEngine.Object sdkAsset = null; // look in editor prefs if (PlayFabEditorPrefsSO.Instance.SdkPath != null) { sdkAsset = AssetDatabase.LoadAssetAtPath(PlayFabEditorPrefsSO.Instance.SdkPath, typeof(UnityEngine.Object)); } if (sdkAsset != null) return sdkAsset; sdkAsset = AssetDatabase.LoadAssetAtPath(PlayFabEditorHelper.DEFAULT_SDK_LOCATION, typeof(UnityEngine.Object)); if (sdkAsset != null) return sdkAsset; var fileList = Directory.GetDirectories(Application.dataPath, "*PlayFabSdk", SearchOption.AllDirectories); if (fileList.Length == 0) return null; var relPath = fileList[0].Substring(fileList[0].LastIndexOf("Assets/")); return AssetDatabase.LoadAssetAtPath(relPath, typeof(UnityEngine.Object)); } private static bool ShowSDKUpgrade() { if (string.IsNullOrEmpty(latestSdkVersion) || latestSdkVersion == "Unknown") { return false; } if (string.IsNullOrEmpty(installedSdkVersion) || installedSdkVersion == "Unknown") { return true; } string[] currrent = installedSdkVersion.Split('.'); string[] latest = latestSdkVersion.Split('.'); if (int.Parse(currrent[0]) < 2) { return false; } return int.Parse(latest[0]) > int.Parse(currrent[0]) || int.Parse(latest[1]) > int.Parse(currrent[1]) || int.Parse(latest[2]) > int.Parse(currrent[2]); } private static void UpgradeSdk() { if (EditorUtility.DisplayDialog("Confirm SDK Upgrade", "This action will remove the current PlayFab SDK and install the lastet version. Related plug-ins will need to be manually upgraded.", "Confirm", "Cancel")) { RemoveSdk(false); ImportLatestSDK(); } } private static void RemoveSdk(bool prompt = true) { if (prompt && !EditorUtility.DisplayDialog("Confirm SDK Removal", "This action will remove the current PlayFab SDK. Related plug-ins will need to be manually removed.", "Confirm", "Cancel")) return; //try to clean-up the plugin dirs if (Directory.Exists(Application.dataPath + "/Plugins")) { var folders = Directory.GetDirectories(Application.dataPath + "/Plugins", "PlayFabShared", SearchOption.AllDirectories); foreach (var folder in folders) FileUtil.DeleteFileOrDirectory(folder); //try to clean-up the plugin files (if anything is left) var files = Directory.GetFiles(Application.dataPath + "/Plugins", "PlayFabErrors.cs", SearchOption.AllDirectories); foreach (var file in files) FileUtil.DeleteFileOrDirectory(file); } if (FileUtil.DeleteFileOrDirectory(PlayFabEditorPrefsSO.Instance.SdkPath)) { PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnSuccess, "PlayFab SDK Removed!"); // HACK for 5.4, AssetDatabase.Refresh(); seems to cause the install to fail. if (prompt) { AssetDatabase.Refresh(); } } else { PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, "An unknown error occured and the PlayFab SDK could not be removed."); } } private static void GetLatestSdkVersion() { var threshold = PlayFabEditorPrefsSO.Instance.EdSet_lastSdkVersionCheck != DateTime.MinValue ? PlayFabEditorPrefsSO.Instance.EdSet_lastSdkVersionCheck.AddHours(1) : DateTime.MinValue; if (DateTime.Today > threshold) { PlayFabEditorHttp.MakeGitHubApiCall("https://api.github.com/repos/PlayFab/UnitySDK/git/refs/tags", (version) => { latestSdkVersion = version ?? "Unknown"; PlayFabEditorPrefsSO.Instance.EdSet_latestSdkVersion = latestSdkVersion; }); } else { latestSdkVersion = PlayFabEditorPrefsSO.Instance.EdSet_latestSdkVersion; } } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Globalization; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// This object is in charge of reloading nodes that have file monikers that can be listened to changes /// </summary> internal class FileChangeManager : IVsFileChangeEvents { #region nested objects /// <summary> /// Defines a data structure that can link a item moniker to the item and its file change cookie. /// </summary> private struct ObservedItemInfo { /// <summary> /// Defines the id of the item that is to be reloaded. /// </summary> private uint itemID; /// <summary> /// Defines the file change cookie that is returned when listening on file changes on the nested project item. /// </summary> private uint fileChangeCookie; /// <summary> /// Defines the nested project item that is to be reloaded. /// </summary> internal uint ItemID { get { return this.itemID; } set { this.itemID = value; } } /// <summary> /// Defines the file change cookie that is returned when listenning on file changes on the nested project item. /// </summary> internal uint FileChangeCookie { get { return this.fileChangeCookie; } set { this.fileChangeCookie = value; } } } #endregion #region Fields /// <summary> /// Event that is raised when one of the observed file names have changed on disk. /// </summary> internal event EventHandler<FileChangedOnDiskEventArgs> FileChangedOnDisk; /// <summary> /// Reference to the FileChange service. /// </summary> private IVsFileChangeEx fileChangeService; /// <summary> /// Maps between the observed item identified by its filename (in canonicalized form) and the cookie used for subscribing /// to the events. /// </summary> private Dictionary<string, ObservedItemInfo> observedItems = new Dictionary<string, ObservedItemInfo>(); /// <summary> /// Has Disposed already been called? /// </summary> private bool disposed; #endregion #region Constructor /// <summary> /// Overloaded ctor. /// </summary> /// <param name="nodeParam">An instance of a project item.</param> internal FileChangeManager(IServiceProvider serviceProvider) { #region input validation if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } #endregion this.fileChangeService = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx)); if (this.fileChangeService == null) { // VS is in bad state, since the SVsFileChangeEx could not be proffered. throw new InvalidOperationException(); } } #endregion #region IDisposable Members /// <summary> /// Disposes resources. /// </summary> public void Dispose() { // Don't dispose more than once if (this.disposed) { return; } this.disposed = true; // Unsubscribe from the observed source files. foreach (ObservedItemInfo info in this.observedItems.Values) { ErrorHandler.ThrowOnFailure(this.fileChangeService.UnadviseFileChange(info.FileChangeCookie)); } // Clean the observerItems list this.observedItems.Clear(); } #endregion #region IVsFileChangeEvents Members /// <summary> /// Called when one of the file have changed on disk. /// </summary> /// <param name="numberOfFilesChanged">Number of files changed.</param> /// <param name="filesChanged">Array of file names.</param> /// <param name="flags">Array of flags indicating the type of changes. See _VSFILECHANGEFLAGS.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> int IVsFileChangeEvents.FilesChanged(uint numberOfFilesChanged, string[] filesChanged, uint[] flags) { if (filesChanged == null) { throw new ArgumentNullException("filesChanged"); } if (flags == null) { throw new ArgumentNullException("flags"); } if (this.FileChangedOnDisk != null) { for (int i = 0; i < numberOfFilesChanged; i++) { string fullFileName = Utilities.CanonicalizeFileName(filesChanged[i]); if (this.observedItems.ContainsKey(fullFileName)) { ObservedItemInfo info = this.observedItems[fullFileName]; this.FileChangedOnDisk(this, new FileChangedOnDiskEventArgs(fullFileName, info.ItemID, (_VSFILECHANGEFLAGS)flags[i])); } } } return VSConstants.S_OK; } /// <summary> /// Notifies clients of changes made to a directory. /// </summary> /// <param name="directory">Name of the directory that had a change.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> int IVsFileChangeEvents.DirectoryChanged(string directory) { return VSConstants.S_OK; } #endregion #region helpers /// <summary> /// Observe when the given file is updated on disk. In this case we do not care about the item id that represents the file in the hierarchy. /// </summary> /// <param name="fileName">File to observe.</param> internal void ObserveItem(string fileName) { this.ObserveItem(fileName, VSConstants.VSITEMID_NIL); } /// <summary> /// Observe when the given file is updated on disk. /// </summary> /// <param name="fileName">File to observe.</param> /// <param name="id">The item id of the item to observe.</param> internal void ObserveItem(string fileName, uint id) { #region Input validation if (String.IsNullOrEmpty(fileName)) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), "fileName"); } #endregion string fullFileName = Utilities.CanonicalizeFileName(fileName); if (!this.observedItems.ContainsKey(fullFileName)) { // Observe changes to the file uint fileChangeCookie; ErrorHandler.ThrowOnFailure(this.fileChangeService.AdviseFileChange(fullFileName, (uint)(_VSFILECHANGEFLAGS.VSFILECHG_Time | _VSFILECHANGEFLAGS.VSFILECHG_Del), this, out fileChangeCookie)); ObservedItemInfo itemInfo = new ObservedItemInfo(); itemInfo.ItemID = id; itemInfo.FileChangeCookie = fileChangeCookie; // Remember that we're observing this file (used in FilesChanged event handler) this.observedItems.Add(fullFileName, itemInfo); } } /// <summary> /// Ignore item file changes for the specified item. /// </summary> /// <param name="fileName">File to ignore observing.</param> /// <param name="ignore">Flag indicating whether or not to ignore changes (1 to ignore, 0 to stop ignoring).</param> internal void IgnoreItemChanges(string fileName, bool ignore) { #region Input validation if (String.IsNullOrEmpty(fileName)) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), "fileName"); } #endregion string fullFileName = Utilities.CanonicalizeFileName(fileName); if (this.observedItems.ContainsKey(fullFileName)) { // Call ignore file with the flags specified. ErrorHandler.ThrowOnFailure(this.fileChangeService.IgnoreFile(0, fileName, ignore ? 1 : 0)); } } /// <summary> /// Stop observing when the file is updated on disk. /// </summary> /// <param name="fileName">File to stop observing.</param> internal void StopObservingItem(string fileName) { #region Input validation if (String.IsNullOrEmpty(fileName)) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), "fileName"); } #endregion string fullFileName = Utilities.CanonicalizeFileName(fileName); if (this.observedItems.ContainsKey(fullFileName)) { // Get the cookie that was used for this.observedItems to this file. ObservedItemInfo itemInfo = this.observedItems[fullFileName]; // Remove the file from our observed list. It's important that this is done before the call to // UnadviseFileChange, because for some reason, the call to UnadviseFileChange can trigger a // FilesChanged event, and we want to be able to filter that event away. this.observedItems.Remove(fullFileName); // Stop observing the file ErrorHandler.ThrowOnFailure(this.fileChangeService.UnadviseFileChange(itemInfo.FileChangeCookie)); } } #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. /* Note on transaction support: Eventually we will want to add support for NT's transactions to our RegistryKey API's (possibly Whidbey M3?). When we do this, here's the list of API's we need to make transaction-aware: RegCreateKeyEx RegDeleteKey RegDeleteValue RegEnumKeyEx RegEnumValue RegOpenKeyEx RegQueryInfoKey RegQueryValueEx RegSetValueEx We can ignore RegConnectRegistry (remote registry access doesn't yet have transaction support) and RegFlushKey. RegCloseKey doesn't require any additional work. . */ /* Note on ACL support: The key thing to note about ACL's is you set them on a kernel object like a registry key, then the ACL only gets checked when you construct handles to them. So if you set an ACL to deny read access to yourself, you'll still be able to read with that handle, but not with new handles. Another peculiarity is a Terminal Server app compatibility workaround. The OS will second guess your attempt to open a handle sometimes. If a certain combination of Terminal Server app compat registry keys are set, then the OS will try to reopen your handle with lesser permissions if you couldn't open it in the specified mode. So on some machines, we will see handles that may not be able to read or write to a registry key. It's very strange. But the real test of these handles is attempting to read or set a value in an affected registry key. For reference, at least two registry keys must be set to particular values for this behavior: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1. HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1 There might possibly be an interaction with yet a third registry key as well. */ using Microsoft.Win32.SafeHandles; using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; namespace Microsoft.Win32 { /** * Registry encapsulation. To get an instance of a RegistryKey use the * Registry class's static members then call OpenSubKey. * * @see Registry * @security(checkDllCalls=off) * @security(checkClassLinking=on) */ internal sealed class RegistryKey : MarshalByRefObject, IDisposable { // We could use const here, if C# supported ELEMENT_TYPE_I fully. internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); internal static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004)); internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); // Dirty indicates that we have munged data that should be potentially // written to disk. // private const int STATE_DIRTY = 0x0001; // SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened" // or "closed". // private const int STATE_SYSTEMKEY = 0x0002; // Access // private const int STATE_WRITEACCESS = 0x0004; // Indicates if this key is for HKEY_PERFORMANCE_DATA private const int STATE_PERF_DATA = 0x0008; // Names of keys. This array must be in the same order as the HKEY values listed above. // private static readonly String[] hkeyNames = new String[] { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_PERFORMANCE_DATA", "HKEY_CURRENT_CONFIG", }; // MSDN defines the following limits for registry key names & values: // Key Name: 255 characters // Value name: 16,383 Unicode characters // Value: either 1 MB or current available memory, depending on registry format. private const int MaxKeyLength = 255; private const int MaxValueLength = 16383; private volatile SafeRegistryHandle hkey = null; private volatile int state = 0; private volatile String keyName; private volatile bool remoteKey = false; private volatile RegistryKeyPermissionCheck checkMode; private volatile RegistryView regView = RegistryView.Default; /** * Creates a RegistryKey. * * This key is bound to hkey, if writable is <b>false</b> then no write operations * will be allowed. If systemkey is set then the hkey won't be released * when the object is GC'ed. * The remoteKey flag when set to true indicates that we are dealing with registry entries * on a remote machine and requires the program making these calls to have full trust. */ private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) { this.hkey = hkey; keyName = ""; this.remoteKey = remoteKey; regView = view; if (systemkey) { state |= STATE_SYSTEMKEY; } if (writable) { state |= STATE_WRITEACCESS; } if (isPerfData) state |= STATE_PERF_DATA; ValidateKeyView(view); } /** * Closes this key, flushes it to disk if the contents have been modified. */ public void Close() { Dispose(true); } private void Dispose(bool disposing) { if (hkey != null) { if (!IsSystemKey()) { try { hkey.Dispose(); } catch (IOException) { // we don't really care if the handle is invalid at this point } finally { hkey = null; } } else if (disposing && IsPerfDataKey()) { // System keys should never be closed. However, we want to call RegCloseKey // on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources // (i.e. when disposing is true) so that we release the PERFLIB cache and cause it // to be refreshed (by re-reading the registry) when accessed subsequently. // This is the only way we can see the just installed perf counter. // NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race condition in closing // the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources // in this situation the down level OSes are not. We have a small window between // the dispose below and usage elsewhere (other threads). This is By Design. // This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey // (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary. SafeRegistryHandle.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA); } } } void IDisposable.Dispose() { Dispose(true); } public void DeleteValue(String name, bool throwOnMissingValue) { EnsureWriteable(); int errorCode = Win32Native.RegDeleteValue(hkey, name); // // From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE // This still means the name doesn't exist. We need to be consistent with previous OS. // if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND || errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE) { if (throwOnMissingValue) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyValueAbsent); } // Otherwise, just return giving no indication to the user. // (For compatibility) } // We really should throw an exception here if errorCode was bad, // but we can't for compatibility reasons. BCLDebug.Correctness(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode); } /** * Retrieves a new RegistryKey that represents the requested key. Valid * values are: * * HKEY_CLASSES_ROOT, * HKEY_CURRENT_USER, * HKEY_LOCAL_MACHINE, * HKEY_USERS, * HKEY_PERFORMANCE_DATA, * HKEY_CURRENT_CONFIG, * HKEY_DYN_DATA. * * @param hKey HKEY_* to open. * * @return the RegistryKey requested. */ internal static RegistryKey GetBaseKey(IntPtr hKey) { return GetBaseKey(hKey, RegistryView.Default); } internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view) { int index = ((int)hKey) & 0x0FFFFFFF; BCLDebug.Assert(index >= 0 && index < hkeyNames.Length, "index is out of range!"); BCLDebug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!"); bool isPerf = hKey == HKEY_PERFORMANCE_DATA; // only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA. SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf); RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view); key.checkMode = RegistryKeyPermissionCheck.Default; key.keyName = hkeyNames[index]; return key; } /** * Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with * read-only access. * * @param name Name or path of subkey to open. * @param readonly Set to <b>true</b> if you only need readonly access. * * @return the Subkey requested, or <b>null</b> if the operation failed. */ public RegistryKey OpenSubKey(string name, bool writable) { ValidateKeyName(name); EnsureNotDisposed(); name = FixupName(name); // Fixup multiple slashes to a single slash SafeRegistryHandle result = null; int ret = Win32Native.RegOpenKeyEx(hkey, name, 0, GetRegistryKeyAccess(writable) | (int)regView, out result); if (ret == 0 && !result.IsInvalid) { RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView); key.checkMode = GetSubKeyPermissonCheck(writable); key.keyName = keyName + "\\" + name; return key; } // Return null if we didn't find the key. if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) { // We need to throw SecurityException here for compatibility reasons, // although UnauthorizedAccessException will make more sense. ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission); } return null; } /** * Returns a subkey with read only permissions. * * @param name Name or path of subkey to open. * * @return the Subkey requested, or <b>null</b> if the operation failed. */ public RegistryKey OpenSubKey(String name) { return OpenSubKey(name, false); } /// <summary> /// Retrieves an array of strings containing all the subkey names. /// </summary> public string[] GetSubKeyNames() { EnsureNotDisposed(); var names = new List<string>(); char[] name = ArrayPool<char>.Shared.Rent(MaxKeyLength + 1); try { int result; int nameLength = name.Length; while ((result = Win32Native.RegEnumKeyEx( hkey, names.Count, name, ref nameLength, null, null, null, null)) != Interop.Errors.ERROR_NO_MORE_ITEMS) { switch (result) { case Interop.Errors.ERROR_SUCCESS: names.Add(new string(name, 0, nameLength)); nameLength = name.Length; break; default: // Throw the error Win32Error(result, null); break; } } } finally { ArrayPool<char>.Shared.Return(name); } return names.ToArray(); } /// <summary> /// Retrieves an array of strings containing all the value names. /// </summary> public unsafe string[] GetValueNames() { EnsureNotDisposed(); var names = new List<string>(); // Names in the registry aren't usually very long, although they can go to as large // as 16383 characters (MaxValueLength). // // Every call to RegEnumValue will allocate another buffer to get the data from // NtEnumerateValueKey before copying it back out to our passed in buffer. This can // add up quickly- we'll try to keep the memory pressure low and grow the buffer // only if needed. char[] name = ArrayPool<char>.Shared.Rent(100); try { int result; int nameLength = name.Length; while ((result = Win32Native.RegEnumValue( hkey, names.Count, name, ref nameLength, IntPtr.Zero, null, null, null)) != Interop.Errors.ERROR_NO_MORE_ITEMS) { switch (result) { // The size is only ever reported back correctly in the case // of ERROR_SUCCESS. It will almost always be changed, however. case Interop.Errors.ERROR_SUCCESS: names.Add(new string(name, 0, nameLength)); break; case Interop.Errors.ERROR_MORE_DATA: if (IsPerfDataKey()) { // Enumerating the values for Perf keys always returns // ERROR_MORE_DATA, but has a valid name. Buffer does need // to be big enough however. 8 characters is the largest // known name. The size isn't returned, but the string is // null terminated. fixed (char* c = &name[0]) { names.Add(new string(c)); } } else { char[] oldName = name; int oldLength = oldName.Length; name = null; ArrayPool<char>.Shared.Return(oldName); name = ArrayPool<char>.Shared.Rent(checked(oldLength * 2)); } break; default: // Throw the error Win32Error(result, null); break; } // Always set the name length back to the buffer size nameLength = name.Length; } } finally { if (name != null) ArrayPool<char>.Shared.Return(name); } return names.ToArray(); } /** * Retrieves the specified value. <b>null</b> is returned if the value * doesn't exist. * * Note that <var>name</var> can be null or "", at which point the * unnamed or default value of this Registry key is returned, if any. * * @param name Name of value to retrieve. * * @return the data associated with the value. */ public Object GetValue(String name) { return InternalGetValue(name, null, false, true); } /** * Retrieves the specified value. <i>defaultValue</i> is returned if the value doesn't exist. * * Note that <var>name</var> can be null or "", at which point the * unnamed or default value of this Registry key is returned, if any. * The default values for RegistryKeys are OS-dependent. NT doesn't * have them by default, but they can exist and be of any type. * * @param name Name of value to retrieve. * @param defaultValue Value to return if <i>name</i> doesn't exist. * * @return the data associated with the value. */ public Object GetValue(String name, Object defaultValue) { return InternalGetValue(name, defaultValue, false, true); } public Object GetValue(String name, Object defaultValue, RegistryValueOptions options) { if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options)); } bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames); return InternalGetValue(name, defaultValue, doNotExpand, true); } internal Object InternalGetValue(String name, Object defaultValue, bool doNotExpand, bool checkSecurity) { if (checkSecurity) { // Name can be null! It's the most common use of RegQueryValueEx EnsureNotDisposed(); } Object data = defaultValue; int type = 0; int datasize = 0; int ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize); if (ret != 0) { if (IsPerfDataKey()) { int size = 65000; int sizeInput = size; int r; byte[] blob = new byte[size]; while (Win32Native.ERROR_MORE_DATA == (r = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref sizeInput))) { if (size == Int32.MaxValue) { // ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue Win32Error(r, name); } else if (size > (Int32.MaxValue / 2)) { // at this point in the loop "size * 2" would cause an overflow size = Int32.MaxValue; } else { size *= 2; } sizeInput = size; blob = new byte[size]; } if (r != 0) Win32Error(r, name); return blob; } else { // For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data). // Some OS's returned ERROR_MORE_DATA even in success cases, so we // want to continue on through the function. if (ret != Win32Native.ERROR_MORE_DATA) return data; } } if (datasize < 0) { // unexpected code path BCLDebug.Assert(false, "[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize"); datasize = 0; } switch (type) { case Win32Native.REG_NONE: case Win32Native.REG_DWORD_BIG_ENDIAN: case Win32Native.REG_BINARY: { byte[] blob = new byte[datasize]; ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize); data = blob; } break; case Win32Native.REG_QWORD: { // also REG_QWORD_LITTLE_ENDIAN if (datasize > 8) { // prevent an AV in the edge case that datasize is larger than sizeof(long) goto case Win32Native.REG_BINARY; } long blob = 0; BCLDebug.Assert(datasize == 8, "datasize==8"); // Here, datasize must be 8 when calling this ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize); data = blob; } break; case Win32Native.REG_DWORD: { // also REG_DWORD_LITTLE_ENDIAN if (datasize > 4) { // prevent an AV in the edge case that datasize is larger than sizeof(int) goto case Win32Native.REG_QWORD; } int blob = 0; BCLDebug.Assert(datasize == 4, "datasize==4"); // Here, datasize must be four when calling this ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize); data = blob; } break; case Win32Native.REG_SZ: { if (datasize % 2 == 1) { // handle the case where the registry contains an odd-byte length (corrupt data?) try { datasize = checked(datasize + 1); } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } } char[] blob = new char[datasize / 2]; ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { data = new String(blob, 0, blob.Length - 1); } else { // in the very unlikely case the data is missing null termination, // pass in the whole char[] to prevent truncating a character data = new String(blob); } } break; case Win32Native.REG_EXPAND_SZ: { if (datasize % 2 == 1) { // handle the case where the registry contains an odd-byte length (corrupt data?) try { datasize = checked(datasize + 1); } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } } char[] blob = new char[datasize / 2]; ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { data = new String(blob, 0, blob.Length - 1); } else { // in the very unlikely case the data is missing null termination, // pass in the whole char[] to prevent truncating a character data = new String(blob); } if (!doNotExpand) data = Environment.ExpandEnvironmentVariables((String)data); } break; case Win32Native.REG_MULTI_SZ: { if (datasize % 2 == 1) { // handle the case where the registry contains an odd-byte length (corrupt data?) try { datasize = checked(datasize + 1); } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } } char[] blob = new char[datasize / 2]; ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize); // make sure the string is null terminated before processing the data if (blob.Length > 0 && blob[blob.Length - 1] != (char)0) { try { char[] newBlob = new char[checked(blob.Length + 1)]; for (int i = 0; i < blob.Length; i++) { newBlob[i] = blob[i]; } newBlob[newBlob.Length - 1] = (char)0; blob = newBlob; } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } blob[blob.Length - 1] = (char)0; } IList<String> strings = new List<String>(); int cur = 0; int len = blob.Length; while (ret == 0 && cur < len) { int nextNull = cur; while (nextNull < len && blob[nextNull] != (char)0) { nextNull++; } if (nextNull < len) { BCLDebug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0"); if (nextNull - cur > 0) { strings.Add(new String(blob, cur, nextNull - cur)); } else { // we found an empty string. But if we're at the end of the data, // it's just the extra null terminator. if (nextNull != len - 1) strings.Add(String.Empty); } } else { strings.Add(new String(blob, cur, len - cur)); } cur = nextNull + 1; } data = new String[strings.Count]; strings.CopyTo((String[])data, 0); } break; case Win32Native.REG_LINK: default: break; } return data; } private bool IsSystemKey() { return (state & STATE_SYSTEMKEY) != 0; } private bool IsWritable() { return (state & STATE_WRITEACCESS) != 0; } private bool IsPerfDataKey() { return (state & STATE_PERF_DATA) != 0; } private void SetDirty() { state |= STATE_DIRTY; } /** * Sets the specified value. * * @param name Name of value to store data in. * @param value Data to store. */ public void SetValue(String name, Object value) { SetValue(name, value, RegistryValueKind.Unknown); } public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if (name != null && name.Length > MaxValueLength) { throw new ArgumentException(SR.Arg_RegValStrLenBug); } if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind)) throw new ArgumentException(SR.Arg_RegBadKeyKind, nameof(valueKind)); EnsureWriteable(); if (valueKind == RegistryValueKind.Unknown) { // this is to maintain compatibility with the old way of autodetecting the type. // SetValue(string, object) will come through this codepath. valueKind = CalculateValueKind(value); } int ret = 0; try { switch (valueKind) { case RegistryValueKind.ExpandString: case RegistryValueKind.String: { String data = value.ToString(); ret = Win32Native.RegSetValueEx(hkey, name, 0, valueKind, data, checked(data.Length * 2 + 2)); break; } case RegistryValueKind.MultiString: { // Other thread might modify the input array after we calculate the buffer length. // Make a copy of the input array to be safe. string[] dataStrings = (string[])(((string[])value).Clone()); int sizeInBytes = 0; // First determine the size of the array // for (int i = 0; i < dataStrings.Length; i++) { if (dataStrings[i] == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetStrArrNull); } sizeInBytes = checked(sizeInBytes + (dataStrings[i].Length + 1) * 2); } sizeInBytes = checked(sizeInBytes + 2); byte[] basePtr = new byte[sizeInBytes]; fixed (byte* b = basePtr) { IntPtr currentPtr = new IntPtr((void*)b); // Write out the strings... // for (int i = 0; i < dataStrings.Length; i++) { // Assumes that the Strings are always null terminated. String.InternalCopy(dataStrings[i], currentPtr, (checked(dataStrings[i].Length * 2))); currentPtr = new IntPtr((long)currentPtr + (checked(dataStrings[i].Length * 2))); *(char*)(currentPtr.ToPointer()) = '\0'; currentPtr = new IntPtr((long)currentPtr + 2); } *(char*)(currentPtr.ToPointer()) = '\0'; currentPtr = new IntPtr((long)currentPtr + 2); ret = Win32Native.RegSetValueEx(hkey, name, 0, RegistryValueKind.MultiString, basePtr, sizeInBytes); } break; } case RegistryValueKind.None: case RegistryValueKind.Binary: byte[] dataBytes = (byte[])value; ret = Win32Native.RegSetValueEx(hkey, name, 0, (valueKind == RegistryValueKind.None ? Win32Native.REG_NONE : RegistryValueKind.Binary), dataBytes, dataBytes.Length); break; case RegistryValueKind.DWord: { // We need to use Convert here because we could have a boxed type cannot be // unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail. int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture); ret = Win32Native.RegSetValueEx(hkey, name, 0, RegistryValueKind.DWord, ref data, 4); break; } case RegistryValueKind.QWord: { long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture); ret = Win32Native.RegSetValueEx(hkey, name, 0, RegistryValueKind.QWord, ref data, 8); break; } } } catch (OverflowException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind); } catch (InvalidOperationException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind); } catch (FormatException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind); } catch (InvalidCastException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind); } if (ret == 0) { SetDirty(); } else Win32Error(ret, null); } private RegistryValueKind CalculateValueKind(Object value) { // This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days. // Even though we could add detection for an int64 in here, we want to maintain compatibility with the // old behavior. if (value is Int32) return RegistryValueKind.DWord; else if (value is Array) { if (value is byte[]) return RegistryValueKind.Binary; else if (value is String[]) return RegistryValueKind.MultiString; else throw new ArgumentException(SR.Format(SR.Arg_RegSetBadArrType, value.GetType().Name)); } else return RegistryValueKind.String; } /** * Retrieves a string representation of this key. * * @return a string representing the key. */ public override String ToString() { EnsureNotDisposed(); return keyName; } /** * After calling GetLastWin32Error(), it clears the last error field, * so you must save the HResult and pass it to this method. This method * will determine the appropriate exception to throw dependent on your * error, and depending on the error, insert a string into the message * gotten from the ResourceManager. */ internal void Win32Error(int errorCode, String str) { switch (errorCode) { case Win32Native.ERROR_ACCESS_DENIED: if (str != null) throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)); else throw new UnauthorizedAccessException(); case Win32Native.ERROR_INVALID_HANDLE: /** * For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException. * However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the * SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues * in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception * on reentrant calls because of this error code path in RegistryKey * * Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this, * however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on * this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of * having serialized access). */ if (!IsPerfDataKey()) { hkey.SetHandleAsInvalid(); hkey = null; } goto default; case Win32Native.ERROR_FILE_NOT_FOUND: throw new IOException(SR.Arg_RegKeyNotFound, errorCode); default: throw new IOException(Interop.Kernel32.GetMessage(errorCode), errorCode); } } internal static String FixupName(String name) { BCLDebug.Assert(name != null, "[FixupName]name!=null"); if (name.IndexOf('\\') == -1) return name; StringBuilder sb = new StringBuilder(name); FixupPath(sb); int temp = sb.Length - 1; if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash sb.Length = temp; return sb.ToString(); } private static void FixupPath(StringBuilder path) { Debug.Assert(path != null); int length = path.Length; bool fixup = false; char markerChar = (char)0xFFFF; int i = 1; while (i < length - 1) { if (path[i] == '\\') { i++; while (i < length) { if (path[i] == '\\') { path[i] = markerChar; i++; fixup = true; } else break; } } i++; } if (fixup) { i = 0; int j = 0; while (i < length) { if (path[i] == markerChar) { i++; continue; } path[j] = path[i]; i++; j++; } path.Length += j - i; } } private void EnsureNotDisposed() { if (hkey == null) { ThrowHelper.ThrowObjectDisposedException(keyName, ExceptionResource.ObjectDisposed_RegKeyClosed); } } private void EnsureWriteable() { EnsureNotDisposed(); if (!IsWritable()) { ThrowHelper.ThrowUnauthorizedAccessException(ExceptionResource.UnauthorizedAccess_RegistryNoWrite); } } private static int GetRegistryKeyAccess(bool isWritable) { int winAccess; if (!isWritable) { winAccess = Win32Native.KEY_READ; } else { winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE; } return winAccess; } private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable) { if (checkMode == RegistryKeyPermissionCheck.Default) { return checkMode; } if (subkeyWritable) { return RegistryKeyPermissionCheck.ReadWriteSubTree; } else { return RegistryKeyPermissionCheck.ReadSubTree; } } static private void ValidateKeyName(string name) { if (name == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name); } int nextSlash = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase); int current = 0; while (nextSlash != -1) { if ((nextSlash - current) > MaxKeyLength) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug); current = nextSlash + 1; nextSlash = name.IndexOf("\\", current, StringComparison.OrdinalIgnoreCase); } if ((name.Length - current) > MaxKeyLength) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug); } static private void ValidateKeyView(RegistryView view) { if (view != RegistryView.Default && view != RegistryView.Registry32 && view != RegistryView.Registry64) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidRegistryViewCheck, ExceptionArgument.view); } } // Win32 constants for error handling private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; } [Flags] internal enum RegistryValueOptions { None = 0, DoNotExpandEnvironmentNames = 1 } // the name for this API is meant to mimic FileMode, which has similar values internal enum RegistryKeyPermissionCheck { Default = 0, ReadSubTree = 1, ReadWriteSubTree = 2 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http.Functional.Tests; using System.Net.Security; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Test.Common { public class Http2LoopbackConnection : GenericLoopbackConnection { private Socket _connectionSocket; private Stream _connectionStream; private TaskCompletionSource<bool> _ignoredSettingsAckPromise; private bool _ignoreWindowUpdates; public static TimeSpan Timeout => Http2LoopbackServer.Timeout; private int _lastStreamId; private readonly byte[] _prefix; public string PrefixString => Encoding.UTF8.GetString(_prefix, 0, _prefix.Length); public bool IsInvalid => _connectionSocket == null; public Http2LoopbackConnection(Socket socket, Http2Options httpOptions) { _connectionSocket = socket; _connectionStream = new NetworkStream(_connectionSocket, true); if (httpOptions.UseSsl) { var sslStream = new SslStream(_connectionStream, false, delegate { return true; }); using (var cert = Configuration.Certificates.GetServerCertificate()) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions(); options.EnabledSslProtocols = httpOptions.SslProtocols; var protocols = new List<SslApplicationProtocol>(); protocols.Add(SslApplicationProtocol.Http2); protocols.Add(SslApplicationProtocol.Http11); options.ApplicationProtocols = protocols; options.ServerCertificate = cert; options.ClientCertificateRequired = false; sslStream.AuthenticateAsServerAsync(options, CancellationToken.None).Wait(); } _connectionStream = sslStream; } _prefix = new byte[24]; if (!FillBufferAsync(_prefix).Result) { throw new Exception("Connection stream closed while attempting to read connection preface."); } } public async Task SendConnectionPrefaceAsync() { // Send the initial server settings frame. Frame emptySettings = new Frame(0, FrameType.Settings, FrameFlags.None, 0); await WriteFrameAsync(emptySettings).ConfigureAwait(false); // Receive and ACK the client settings frame. Frame clientSettings = await ReadFrameAsync(Timeout).ConfigureAwait(false); clientSettings.Flags = clientSettings.Flags | FrameFlags.Ack; await WriteFrameAsync(clientSettings).ConfigureAwait(false); // Receive the client ACK of the server settings frame. clientSettings = await ReadFrameAsync(Timeout).ConfigureAwait(false); } public async Task WriteFrameAsync(Frame frame) { byte[] writeBuffer = new byte[Frame.FrameHeaderLength + frame.Length]; frame.WriteTo(writeBuffer); await _connectionStream.WriteAsync(writeBuffer, 0, writeBuffer.Length).ConfigureAwait(false); } // Read until the buffer is full // Return false on EOF, throw on partial read private async Task<bool> FillBufferAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { int readBytes = await _connectionStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); if (readBytes == 0) { return false; } buffer = buffer.Slice(readBytes); while (buffer.Length > 0) { readBytes = await _connectionStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); if (readBytes == 0) { throw new Exception("Connection closed when expecting more data."); } buffer = buffer.Slice(readBytes); } return true; } public async Task<Frame> ReadFrameAsync(TimeSpan timeout) { using CancellationTokenSource timeoutCts = new CancellationTokenSource(timeout); return await ReadFrameAsync(timeoutCts.Token).ConfigureAwait(false); } private async Task<Frame> ReadFrameAsync(CancellationToken cancellationToken) { // First read the frame headers, which should tell us how long the rest of the frame is. byte[] headerBytes = new byte[Frame.FrameHeaderLength]; try { if (!await FillBufferAsync(headerBytes, cancellationToken).ConfigureAwait(false)) { return null; } } catch (IOException) { // eat errors when client aborts connection and return null. return null; } Frame header = Frame.ReadFrom(headerBytes); // Read the data segment of the frame, if it is present. byte[] data = new byte[header.Length]; if (header.Length > 0 && !await FillBufferAsync(data, cancellationToken).ConfigureAwait(false)) { throw new Exception("Connection stream closed while attempting to read frame body."); } if (_ignoredSettingsAckPromise != null && header.Type == FrameType.Settings && header.Flags == FrameFlags.Ack) { _ignoredSettingsAckPromise.TrySetResult(false); _ignoredSettingsAckPromise = null; return await ReadFrameAsync(cancellationToken).ConfigureAwait(false); } if (_ignoreWindowUpdates && header.Type == FrameType.WindowUpdate) { return await ReadFrameAsync(cancellationToken).ConfigureAwait(false); } // Construct the correct frame type and return it. switch (header.Type) { case FrameType.Settings: return SettingsFrame.ReadFrom(header, data); case FrameType.Data: return DataFrame.ReadFrom(header, data); case FrameType.Headers: return HeadersFrame.ReadFrom(header, data); case FrameType.Priority: return PriorityFrame.ReadFrom(header, data); case FrameType.RstStream: return RstStreamFrame.ReadFrom(header, data); case FrameType.Ping: return PingFrame.ReadFrom(header, data); case FrameType.GoAway: return GoAwayFrame.ReadFrom(header, data); default: return header; } } // Reset and return underlying networking objects. public (Socket, Stream) ResetNetwork() { Socket oldSocket = _connectionSocket; Stream oldStream = _connectionStream; _connectionSocket = null; _connectionStream = null; _ignoredSettingsAckPromise = null; return (oldSocket, oldStream); } // Set up loopback server to silently ignore the next inbound settings ack frame. // If there already is a pending ack frame, wait until it has been read. public async Task ExpectSettingsAckAsync(int timeoutMs = 5000) { // The timing of when we receive the settings ack is not guaranteed. // To simplify frame processing, just record that we are expecting one, // and then filter it out in ReadFrameAsync above. Task currentTask = _ignoredSettingsAckPromise?.Task; if (currentTask != null) { var timeout = TimeSpan.FromMilliseconds(timeoutMs); await currentTask.TimeoutAfter(timeout); } _ignoredSettingsAckPromise = new TaskCompletionSource<bool>(); } public void IgnoreWindowUpdates() { _ignoreWindowUpdates = true; } public async Task ReadRstStreamAsync(int streamId) { Frame frame = await ReadFrameAsync(Timeout); if (frame == null) { throw new Exception($"Expected RST_STREAM, saw EOF"); } if (frame.Type != FrameType.RstStream) { throw new Exception($"Expected RST_STREAM, saw {frame.Type}"); } if (frame.StreamId != streamId) { throw new Exception($"Expected RST_STREAM on stream {streamId}, actual streamId={frame.StreamId}"); } } // Wait for the client to close the connection, e.g. after the HttpClient is disposed. public async Task WaitForClientDisconnectAsync(bool ignoreUnexpectedFrames = false) { IgnoreWindowUpdates(); Frame frame = await ReadFrameAsync(Timeout).ConfigureAwait(false); if (frame != null) { if (!ignoreUnexpectedFrames) { throw new Exception($"Unexpected frame received while waiting for client disconnect: {frame}"); } } _connectionStream.Close(); _connectionSocket = null; _connectionStream = null; _ignoredSettingsAckPromise = null; _ignoreWindowUpdates = false; } public void ShutdownSend() { _connectionSocket.Shutdown(SocketShutdown.Send); } // This will cause a server-initiated shutdown of the connection. // For normal operation, you should send a GOAWAY and complete any remaining streams // before calling this method. public async Task WaitForConnectionShutdownAsync(bool ignoreUnexpectedFrames = false) { // Shutdown our send side, so the client knows there won't be any more frames coming. ShutdownSend(); await WaitForClientDisconnectAsync(ignoreUnexpectedFrames: ignoreUnexpectedFrames); } // This is similar to WaitForConnectionShutdownAsync but will send GOAWAY for you // and will ignore any errors if client has already shutdown public async Task ShutdownIgnoringErrorsAsync(int lastStreamId, ProtocolErrors errorCode = ProtocolErrors.NO_ERROR) { try { await SendGoAway(lastStreamId, errorCode).ConfigureAwait(false); await WaitForConnectionShutdownAsync(ignoreUnexpectedFrames: true).ConfigureAwait(false); } catch (IOException) { // Ignore connection errors } catch (SocketException) { // Ignore connection errors } } public async Task<int> ReadRequestHeaderAsync() { HeadersFrame frame = await ReadRequestHeaderFrameAsync(); return frame.StreamId; } public async Task<HeadersFrame> ReadRequestHeaderFrameAsync() { // Receive HEADERS frame for request. Frame frame = await ReadFrameAsync(Timeout).ConfigureAwait(false); if (frame == null) { throw new IOException("Failed to read Headers frame."); } Assert.Equal(FrameType.Headers, frame.Type); Assert.Equal(FrameFlags.EndHeaders | FrameFlags.EndStream, frame.Flags); return (HeadersFrame)frame; } private static (int bytesConsumed, int value) DecodeInteger(ReadOnlySpan<byte> headerBlock, byte prefixMask) { int value = headerBlock[0] & prefixMask; if (value != prefixMask) { return (1, value); } byte b = headerBlock[1]; if ((b & 0b10000000) != 0) { throw new Exception("long integers currently not supported"); } return (2, prefixMask + b); } private static (int bytesConsumed, string value) DecodeString(ReadOnlySpan<byte> headerBlock) { (int bytesConsumed, int stringLength) = DecodeInteger(headerBlock, 0b01111111); if ((headerBlock[0] & 0b10000000) != 0) { // Huffman encoded byte[] buffer = new byte[stringLength * 2]; int bytesDecoded = HuffmanDecoder.Decode(headerBlock.Slice(bytesConsumed, stringLength), buffer); string value = Encoding.ASCII.GetString(buffer, 0, bytesDecoded); return (bytesConsumed + stringLength, value); } else { string value = Encoding.ASCII.GetString(headerBlock.Slice(bytesConsumed, stringLength)); return (bytesConsumed + stringLength, value); } } private static readonly HttpHeaderData[] s_staticTable = new HttpHeaderData[] { new HttpHeaderData(":authority", ""), new HttpHeaderData(":method", "GET"), new HttpHeaderData(":method", "POST"), new HttpHeaderData(":path", "/"), new HttpHeaderData(":path", "/index.html"), new HttpHeaderData(":scheme", "http"), new HttpHeaderData(":scheme", "https"), new HttpHeaderData(":status", "200"), new HttpHeaderData(":status", "204"), new HttpHeaderData(":status", "206"), new HttpHeaderData(":status", "304"), new HttpHeaderData(":status", "400"), new HttpHeaderData(":status", "404"), new HttpHeaderData(":status", "500"), new HttpHeaderData("accept-charset", ""), new HttpHeaderData("accept-encoding", "gzip, deflate"), new HttpHeaderData("accept-language", ""), new HttpHeaderData("accept-ranges", ""), new HttpHeaderData("accept", ""), new HttpHeaderData("access-control-allow-origin", ""), new HttpHeaderData("age", ""), new HttpHeaderData("allow", ""), new HttpHeaderData("authorization", ""), new HttpHeaderData("cache-control", ""), new HttpHeaderData("content-disposition", ""), new HttpHeaderData("content-encoding", ""), new HttpHeaderData("content-language", ""), new HttpHeaderData("content-length", ""), new HttpHeaderData("content-location", ""), new HttpHeaderData("content-range", ""), new HttpHeaderData("content-type", ""), new HttpHeaderData("cookie", ""), new HttpHeaderData("date", ""), new HttpHeaderData("etag", ""), new HttpHeaderData("expect", ""), new HttpHeaderData("expires", ""), new HttpHeaderData("from", ""), new HttpHeaderData("host", ""), new HttpHeaderData("if-match", ""), new HttpHeaderData("if-modified-since", ""), new HttpHeaderData("if-none-match", ""), new HttpHeaderData("if-range", ""), new HttpHeaderData("if-unmodified-since", ""), new HttpHeaderData("last-modified", ""), new HttpHeaderData("link", ""), new HttpHeaderData("location", ""), new HttpHeaderData("max-forwards", ""), new HttpHeaderData("proxy-authenticate", ""), new HttpHeaderData("proxy-authorization", ""), new HttpHeaderData("range", ""), new HttpHeaderData("referer", ""), new HttpHeaderData("refresh", ""), new HttpHeaderData("retry-after", ""), new HttpHeaderData("server", ""), new HttpHeaderData("set-cookie", ""), new HttpHeaderData("strict-transport-security", ""), new HttpHeaderData("transfer-encoding", ""), new HttpHeaderData("user-agent", ""), new HttpHeaderData("vary", ""), new HttpHeaderData("via", ""), new HttpHeaderData("www-authenticate", "") }; private static HttpHeaderData GetHeaderForIndex(int index) { return s_staticTable[index - 1]; } private static (int bytesConsumed, HttpHeaderData headerData) DecodeLiteralHeader(ReadOnlySpan<byte> headerBlock, byte prefixMask) { int i = 0; (int bytesConsumed, int index) = DecodeInteger(headerBlock, prefixMask); i += bytesConsumed; string name; if (index == 0) { (bytesConsumed, name) = DecodeString(headerBlock.Slice(i)); i += bytesConsumed; } else { name = GetHeaderForIndex(index).Name; } string value; (bytesConsumed, value) = DecodeString(headerBlock.Slice(i)); i += bytesConsumed; return (i, new HttpHeaderData(name, value)); } private static (int bytesConsumed, HttpHeaderData headerData) DecodeHeader(ReadOnlySpan<byte> headerBlock) { int i = 0; byte b = headerBlock[0]; if ((b & 0b10000000) != 0) { // Indexed header (int bytesConsumed, int index) = DecodeInteger(headerBlock, 0b01111111); i += bytesConsumed; return (i, GetHeaderForIndex(index)); } else if ((b & 0b11000000) == 0b01000000) { // Literal with indexing return DecodeLiteralHeader(headerBlock, 0b00111111); } else if ((b & 0b11100000) == 0b00100000) { // Table size update throw new Exception("table size update not supported"); } else { // Literal, never indexed return DecodeLiteralHeader(headerBlock, 0b00001111); } } public async Task<byte[]> ReadBodyAsync() { byte[] body = null; Frame frame; do { frame = await ReadFrameAsync(Timeout).ConfigureAwait(false); if (frame == null || frame.Type == FrameType.RstStream) { throw new IOException( frame == null ? "End of stream" : "Got RST"); } Assert.Equal(FrameType.Data, frame.Type); if (frame.Length > 1) { DataFrame dataFrame = (DataFrame)frame; if (body == null) { body = dataFrame.Data.ToArray(); } else { byte[] newBuffer = new byte[body.Length + dataFrame.Data.Length]; body.CopyTo(newBuffer, 0); dataFrame.Data.Span.CopyTo(newBuffer.AsSpan().Slice(body.Length)); body= newBuffer; } } } while ((frame.Flags & FrameFlags.EndStream) == 0); return body; } public async Task<(int streamId, HttpRequestData requestData)> ReadAndParseRequestHeaderAsync(bool readBody = true) { HttpRequestData requestData = new HttpRequestData(); // Receive HEADERS frame for request. Frame frame = await ReadFrameAsync(Timeout).ConfigureAwait(false); if (frame == null) { throw new IOException("Failed to read Headers frame."); } Assert.Equal(FrameType.Headers, frame.Type); HeadersFrame headersFrame = (HeadersFrame) frame; // TODO CONTINUATION support Assert.Equal(FrameFlags.EndHeaders, FrameFlags.EndHeaders & headersFrame.Flags); int streamId = headersFrame.StreamId; requestData.RequestId = streamId; Memory<byte> data = headersFrame.Data; int i = 0; while (i < data.Length) { (int bytesConsumed, HttpHeaderData headerData) = DecodeHeader(data.Span.Slice(i)); byte[] headerRaw = data.Span.Slice(i, bytesConsumed).ToArray(); headerData = new HttpHeaderData(headerData.Name, headerData.Value, headerData.HuffmanEncoded, headerRaw); requestData.Headers.Add(headerData); i += bytesConsumed; } // Extract method and path requestData.Method = requestData.GetSingleHeaderValue(":method"); requestData.Path = requestData.GetSingleHeaderValue(":path"); if (readBody && (frame.Flags & FrameFlags.EndStream) == 0) { // Read body until end of stream if needed. requestData.Body = await ReadBodyAsync().ConfigureAwait(false); } return (streamId, requestData); } public async Task SendGoAway(int lastStreamId, ProtocolErrors errorCode = ProtocolErrors.NO_ERROR) { GoAwayFrame frame = new GoAwayFrame(lastStreamId, (int)errorCode, new byte[] { }, 0); await WriteFrameAsync(frame).ConfigureAwait(false); } public async Task PingPong() { byte[] pingData = new byte[8] { 1, 2, 3, 4, 50, 60, 70, 80 }; PingFrame ping = new PingFrame(pingData, FrameFlags.None, 0); await WriteFrameAsync(ping).ConfigureAwait(false); PingFrame pingAck = (PingFrame)await ReadFrameAsync(Timeout).ConfigureAwait(false); if (pingAck == null || pingAck.Type != FrameType.Ping || !pingAck.AckFlag) { throw new Exception("Expected PING ACK"); } Assert.Equal(pingData, pingAck.Data); } public async Task SendDefaultResponseHeadersAsync(int streamId) { byte[] headers = new byte[] { 0x88 }; // Encoding for ":status: 200" HeadersFrame headersFrame = new HeadersFrame(headers, FrameFlags.EndHeaders, 0, 0, 0, streamId); await WriteFrameAsync(headersFrame).ConfigureAwait(false); } public async Task SendDefaultResponseAsync(int streamId) { byte[] headers = new byte[] { 0x88 }; // Encoding for ":status: 200" HeadersFrame headersFrame = new HeadersFrame(headers, FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId); await WriteFrameAsync(headersFrame).ConfigureAwait(false); } public async Task SendResponseHeadersAsync(int streamId, bool endStream = true, HttpStatusCode statusCode = HttpStatusCode.OK, bool isTrailingHeader = false, bool endHeaders = true, IList<HttpHeaderData> headers = null) { // For now, only support headers that fit in a single frame byte[] headerBlock = new byte[Frame.MaxFrameLength]; int bytesGenerated = 0; if (!isTrailingHeader) { string statusCodeString = ((int)statusCode).ToString(); bytesGenerated += HPackEncoder.EncodeHeader(":status", statusCodeString, HPackFlags.None, headerBlock.AsSpan()); } if (headers != null) { foreach (HttpHeaderData headerData in headers) { bytesGenerated += HPackEncoder.EncodeHeader(headerData.Name, headerData.Value, headerData.HuffmanEncoded ? HPackFlags.HuffmanEncode : HPackFlags.None, headerBlock.AsSpan(bytesGenerated)); } } FrameFlags flags = endHeaders ? FrameFlags.EndHeaders : FrameFlags.None; if (endStream) { flags |= FrameFlags.EndStream; } HeadersFrame headersFrame = new HeadersFrame(headerBlock.AsMemory().Slice(0, bytesGenerated), flags, 0, 0, 0, streamId); await WriteFrameAsync(headersFrame).ConfigureAwait(false); } public async Task SendResponseDataAsync(int streamId, ReadOnlyMemory<byte> responseData, bool endStream) { DataFrame dataFrame = new DataFrame(responseData, endStream ? FrameFlags.EndStream : FrameFlags.None, 0, streamId); await WriteFrameAsync(dataFrame).ConfigureAwait(false); } public async Task SendResponseBodyAsync(int streamId, ReadOnlyMemory<byte> responseBody, bool isFinal = true) { // Only support response body if it fits in a single frame, for now // In the future we should separate the body into chunks as needed, // and if it's larger than the default window size, we will need to process window updates as well. if (responseBody.Length > Frame.MaxFrameLength) { throw new Exception("Response body too long"); } await SendResponseDataAsync(streamId, responseBody, isFinal).ConfigureAwait(false); } public override void Dispose() { ShutdownIgnoringErrorsAsync(_lastStreamId).GetAwaiter().GetResult(); } // // GenericLoopbackServer implementation // public override async Task<HttpRequestData> ReadRequestDataAsync(bool readBody = true) { (int streamId, HttpRequestData requestData) = await ReadAndParseRequestHeaderAsync(readBody).ConfigureAwait(false); _lastStreamId = streamId; return requestData; } public override Task<Byte[]> ReadRequestBodyAsync() { return ReadBodyAsync(); } public override async Task SendResponseAsync(HttpStatusCode? statusCode = null, IList<HttpHeaderData> headers = null, string body = null, bool isFinal = true, int requestId = 0) { // TODO: Header continuation support. Assert.NotNull(statusCode); if (headers != null) { bool hasDate = false; bool stripContentLength = false; foreach (HttpHeaderData headerData in headers) { // Check if we should inject Date header to match HTTP/1. if (headerData.Name.Equals("Date", StringComparison.OrdinalIgnoreCase)) { hasDate = true; } else if (headerData.Name.Equals("Content-Length") && headerData.Value == null) { // Hack used for Http/1 to avoid sending content-length header. stripContentLength = true; } } if (!hasDate || stripContentLength) { var newHeaders = new List<HttpHeaderData>(); foreach (HttpHeaderData headerData in headers) { if (headerData.Name.Equals("Content-Length") && headerData.Value == null) { continue; } newHeaders.Add(headerData); } newHeaders.Add(new HttpHeaderData("Date", $"{DateTimeOffset.UtcNow:R}")); headers = newHeaders; } } int streamId = requestId == 0 ? _lastStreamId : requestId; bool endHeaders = body != null || isFinal; if (string.IsNullOrEmpty(body)) { await SendResponseHeadersAsync(streamId, endStream: isFinal, (HttpStatusCode)statusCode, endHeaders: endHeaders, headers: headers); } else { await SendResponseHeadersAsync(streamId, endStream: false, (HttpStatusCode)statusCode, endHeaders: endHeaders, headers: headers); await SendResponseBodyAsync(body, isFinal: isFinal, requestId: streamId); } } public override Task SendResponseHeadersAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, int requestId = 0) { int streamId = requestId == 0 ? _lastStreamId : requestId; return SendResponseHeadersAsync(streamId, endStream: false, statusCode, isTrailingHeader: false, endHeaders: true, headers); } public override Task SendResponseBodyAsync(byte[] body, bool isFinal = true, int requestId = 0) { int streamId = requestId == 0 ? _lastStreamId : requestId; return SendResponseBodyAsync(streamId, body, isFinal); } public override async Task WaitForCancellationAsync(bool ignoreIncomingData = true, int requestId = 0) { int streamId = requestId == 0 ? _lastStreamId : requestId; Frame frame; do { frame = await ReadFrameAsync(TimeSpan.FromMilliseconds(TestHelper.PassingTestTimeoutMilliseconds)); Assert.NotNull(frame); // We should get Rst before closing connection. Assert.Equal(0, (int)(frame.Flags & FrameFlags.EndStream)); if (ignoreIncomingData) { Assert.True(frame.Type == FrameType.Data || frame.Type == FrameType.RstStream, $"Expected Data or RstStream, got {frame.Type}"); } else { Assert.Equal(FrameType.RstStream, frame.Type); } } while (frame.Type != FrameType.RstStream); Assert.Equal(streamId, frame.StreamId); } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.TimeZones; using NodaTime.TzdbCompiler.Tzdb; using NUnit.Framework; using System; using System.Globalization; using System.IO; using System.Linq; namespace NodaTime.TzdbCompiler.Test.Tzdb { /// <summary> /// Tests for TzdbZoneInfoParser. /// </summary> public class TzdbZoneInfoParserTest { private static Offset ToOffset(int hours, int minutes) { return Offset.FromHoursAndMinutes(hours, minutes); } private static void ValidateCounts(TzdbDatabase database, int ruleSets, int zoneLists, int links) { Assert.AreEqual(ruleSets, database.Rules.Count, "Rules"); Assert.AreEqual(zoneLists, database.Zones.Count, "Zones"); Assert.AreEqual(links, database.Aliases.Count, "Links"); } [Test] public void ParseDateTimeOfYear_emptyString() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize(""); Assert.Throws(typeof(InvalidDataException), () => parser.ParseDateTimeOfYear(tokens, true)); } [Test] public void ParseDateTimeOfYear_missingAt_invalidForRule() { var parser = new TzdbZoneInfoParser(); const string text = "Mar lastSun"; var tokens = Tokens.Tokenize(text); Assert.Throws(typeof(InvalidDataException), () => parser.ParseDateTimeOfYear(tokens, true)); } [Test] public void ParseDateTimeOfYear_missingOn_invalidForRule() { var parser = new TzdbZoneInfoParser(); const string text = "Mar"; var tokens = Tokens.Tokenize(text); Assert.Throws(typeof(InvalidDataException), () => parser.ParseDateTimeOfYear(tokens, true)); } [Test] public void ParseDateTimeOfYear_missingAt_validForZone() { var parser = new TzdbZoneInfoParser(); const string text = "Mar lastSun"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, false); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_missingOn_validForZone() { var parser = new TzdbZoneInfoParser(); const string text = "Mar"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, false); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 1, 0, false, LocalTime.Midnight); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onAfter() { var parser = new TzdbZoneInfoParser(); const string text = "Mar Tue>=14 2:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 14, (int)IsoDayOfWeek.Tuesday, true, new LocalTime(2, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onBefore() { var parser = new TzdbZoneInfoParser(); const string text = "Mar Tue<=14 2:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 14, (int)IsoDayOfWeek.Tuesday, false, new LocalTime(2, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onLast() { var parser = new TzdbZoneInfoParser(); const string text = "Mar lastTue 2:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int)IsoDayOfWeek.Tuesday, false, new LocalTime(2, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseLine_comment() { const string line = "# Comment"; var database = ParseText(line); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_commentWithLeadingWhitespace() { const string line = " # Comment"; var database = ParseText(line); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_emptyString() { var database = ParseText(""); ValidateCounts(database, 0, 0, 0); } // Assume that all lines work the same way - it's comment handling // that's important here. [Test] public void ParseLine_commentAtEndOfLine() { string line = "Link from to#Comment"; var database = ParseText(line); ValidateCounts(database, 0, 0, 1); Assert.AreEqual("from", database.Aliases["to"]); } [Test] public void ParseLine_link() { const string line = "Link from to"; var database = ParseText(line); ValidateCounts(database, 0, 0, 1); } [Test] public void ParseLine_whiteSpace() { const string line = " \t\t\n"; var database = ParseText(line); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_zone() { const string line = "Zone PST 2:00 US P%sT"; var database = ParseText(line); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.Zones.Values.Single().Count); } [Test] public void ParseLine_zonePlus() { string lines = "Zone PST 2:00 US P%sT\n" + " 3:00 US P%sT"; var database = ParseText(lines); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.Zones["PST"].Count); } [Test] public void ParseLink_emptyString_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize(""); Assert.Throws(typeof(InvalidDataException), () => parser.ParseLink(tokens)); } [Test] public void ParseLink_simple() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("from to"); var actual = parser.ParseLink(tokens); var expected = Tuple.Create("from", "to"); Assert.AreEqual(expected, actual); } [Test] public void ParseLink_tooFewWords_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("from"); Assert.Throws<InvalidDataException>(() => parser.ParseLink(tokens)); } [Test] public void ParseMonth_nullOrEmpty() { Assert.Throws<ArgumentException>(() => TzdbZoneInfoParser.ParseMonth("")); Assert.Throws<ArgumentException>(() => TzdbZoneInfoParser.ParseMonth(null!)); } [Test] public void ParseMonth_invalidMonth_default() { Assert.Throws<InvalidDataException>(() => TzdbZoneInfoParser.ParseMonth("Able")); } [Test] public void ParseMonth_shortMonthNames() { for (int i = 1; i < 12; i++) { var month = new DateTime(2000, i, 1).ToString("MMM", CultureInfo.InvariantCulture); Assert.AreEqual(i, TzdbZoneInfoParser.ParseMonth(month)); } } [Test] public void ParseMonth_longMonthNames() { for (int i = 1; i < 12; i++) { var month = new DateTime(2000, i, 1).ToString("MMMM", CultureInfo.InvariantCulture); Assert.AreEqual(i, TzdbZoneInfoParser.ParseMonth(month)); } } [Test] public void ParseZone_badOffset_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("asd US P%sT 1969 Mar 23 14:53:27.856s"); Assert.Throws(typeof(FormatException), () => parser.ParseZone("", tokens)); } [Test] public void ParseZone_emptyString_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize(""); Assert.Throws(typeof(InvalidDataException), () => parser.ParseZone("", tokens)); } [Test] public void ParseZone_optionalRule() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 - P%sT"); var expected = new ZoneLine("", ToOffset(2, 0), null, "P%sT", int.MaxValue, TzdbZoneInfoParser.StartOfYearZoneOffset); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_simple() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", int.MaxValue, TzdbZoneInfoParser.StartOfYearZoneOffset); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_tooFewWords1_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US"); Assert.Throws(typeof(InvalidDataException), () => parser.ParseZone("", tokens)); } [Test] public void ParseZone_tooFewWords2_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00"); Assert.Throws(typeof(InvalidDataException), () => parser.ParseZone("", tokens)); } [Test] public void ParseZone_withYear() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 1, 1, 0, false, LocalTime.Midnight)); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_withYearMonthDay() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 3, 23, 0, false, LocalTime.Midnight)); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_withYearMonthDayTime() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23 14:53:27.856"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 3, 23, 0, false, new LocalTime(14, 53, 27, 856))); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_withYearMonthDayTimeZone() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23 14:53:27.856s"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Standard, 3, 23, 0, false, new LocalTime(14, 53, 27, 856))); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_withDayOfWeek() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar lastSun"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight)); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void Parse_threeLines() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT\n" + " 3:00 - P%sT\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.Zones.Values.Single().Count); } [Test] public void Parse_threeLinesWithComment() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.Zones.Values.Single().Count); } [Test] public void Parse_twoLines() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.Zones.Values.Single().Count); } [Test] public void Parse_twoLinks() { const string text = "# First line must be a comment\n" + "Link from to\n" + "Link target source\n"; var database = ParseText(text); ValidateCounts(database, 0, 0, 2); } [Test] public void Parse_twoZones() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n" + " 4:00 - P%sT\n" + "Zone EST 2:00 US E%sT # An end of line comment\n" + " 3:00 - E%sT\n"; var database = ParseText(text); ValidateCounts(database, 0, 2, 0); Assert.AreEqual(3, database.Zones["PST"].Count); Assert.AreEqual(2, database.Zones["EST"].Count); } [Test] public void Parse_twoZonesTwoRule() { const string text = "# A comment\n" + "Rule US 1987 2006 - Apr Sun>=1 2:00 1:00 D\n" + "Rule US 2007 max - Mar Sun>=8 2:00 1:00 D\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n" + " 4:00 - P%sT\n" + "Zone EST 2:00 US E%sT # An end of line comment\n" + " 3:00 - E%sT\n"; var database = ParseText(text); ValidateCounts(database, 1, 2, 0); Assert.AreEqual(3, database.Zones["PST"].Count); Assert.AreEqual(2, database.Zones["EST"].Count); } // 2018f uses 25:00 for Japan's fallback transitions 1948-1951 [Test] public void Parse_2500_FromDay_AtLeast_Sunday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Sun>=1 25:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 2, 1, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtLeast_Sunday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Sun>=1 24:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 2, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtMost_Sunday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Sun<=7 24:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 2, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtLeast_Wednesday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Wed>=1 24:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 5, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtMost_Wednesday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Wed<=14 24:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 12, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Sun>=1 24:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 4, 1, (int)IsoDayOfWeek.Sunday, true, LocalTime.Midnight, true); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_Last() { var parser = new TzdbZoneInfoParser(); const string text = "Mar lastSun 24:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int)IsoDayOfWeek.Sunday, false, LocalTime.Midnight, true); Assert.AreEqual(expected, actual); } [Test] public void Parse_Fixed_Eastern() { const string text = "# A comment\n" + "Zone\tEtc/GMT-9\t9\t-\tGMT-9\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); var zone = database.Zones["Etc/GMT-9"].Single(); Assert.AreEqual(Offset.FromHours(9), zone.StandardOffset); Assert.IsNull(zone.Rules); Assert.AreEqual(int.MaxValue, zone.UntilYear); } [Test] public void Parse_Fixed_Western() { const string text = "# A comment\n" + "Zone\tEtc/GMT+9\t-9\t-\tGMT+9\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); var zone = database.Zones["Etc/GMT+9"].Single(); Assert.AreEqual(Offset.FromHours(-9), zone.StandardOffset); Assert.IsNull(zone.Rules); Assert.AreEqual(int.MaxValue, zone.UntilYear); } /// <summary> /// Helper method to create a database and call Parse with the given text. /// </summary> private TzdbDatabase ParseText(string line) { var parser = new TzdbZoneInfoParser(); var database = new TzdbDatabase("version"); parser.Parse(new StringReader(line), database); return database; } } }
using System; using System.IO; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NBitcoin; using Stratis.Bitcoin.Base.Deployments; using Stratis.Bitcoin.BlockPulling; using Stratis.Bitcoin.Builder; using Stratis.Bitcoin.Builder.Feature; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Configuration.Settings; using Stratis.Bitcoin.Connection; using Stratis.Bitcoin.Consensus; using Stratis.Bitcoin.Consensus.Validators; using Stratis.Bitcoin.Interfaces; using Stratis.Bitcoin.P2P; using Stratis.Bitcoin.P2P.Peer; using Stratis.Bitcoin.P2P.Protocol.Behaviors; using Stratis.Bitcoin.P2P.Protocol.Payloads; using Stratis.Bitcoin.Signals; using Stratis.Bitcoin.Utilities; [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Features.Consensus.Tests")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests")] namespace Stratis.Bitcoin.Base { /// <summary> /// Base node services, these are the services a node has to have. /// The ConnectionManager feature is also part of the base but may go in a feature of its own. /// The base features are the minimal components required to connect to peers and maintain the best chain. /// <para> /// The base node services for a node are: /// <list type="bullet"> /// <item>the ConcurrentChain to keep track of the best chain,</item> /// <item>the ConnectionManager to connect with the network,</item> /// <item>DatetimeProvider and Cancellation,</item> /// <item>CancellationProvider and Cancellation,</item> /// <item>DataFolder,</item> /// <item>ChainState.</item> /// </list> /// </para> /// </summary> public sealed class BaseFeature : FullNodeFeature { /// <summary>Global application life cycle control - triggers when application shuts down.</summary> private readonly INodeLifetime nodeLifetime; /// <summary>Information about node's chain.</summary> private readonly IChainState chainState; /// <summary>Access to the database of blocks.</summary> private readonly IChainRepository chainRepository; /// <summary>User defined node settings.</summary> private readonly NodeSettings nodeSettings; /// <summary>Locations of important folders and files on disk.</summary> private readonly DataFolder dataFolder; /// <summary>Thread safe chain of block headers from genesis.</summary> private readonly ConcurrentChain chain; /// <summary>Manager of node's network connections.</summary> private readonly IConnectionManager connectionManager; /// <summary>Provider of time functions.</summary> private readonly IDateTimeProvider dateTimeProvider; /// <summary>Factory for creating background async loop tasks.</summary> private readonly IAsyncLoopFactory asyncLoopFactory; /// <summary>Logger for the node.</summary> private readonly ILogger logger; /// <summary>Factory for creating loggers.</summary> private readonly ILoggerFactory loggerFactory; /// <summary>State of time synchronization feature that stores collected data samples.</summary> private readonly ITimeSyncBehaviorState timeSyncBehaviorState; /// <summary>Manager of node's network peers.</summary> private IPeerAddressManager peerAddressManager; /// <summary>Periodic task to save list of peers to disk.</summary> private IAsyncLoop flushAddressManagerLoop; /// <summary>Periodic task to save the chain to the database.</summary> private IAsyncLoop flushChainLoop; /// <summary>A handler that can manage the lifetime of network peers.</summary> private readonly IPeerBanning peerBanning; /// <summary>Provider of IBD state.</summary> private readonly IInitialBlockDownloadState initialBlockDownloadState; /// <inheritdoc cref="Network"/> private readonly Network network; private readonly IProvenBlockHeaderStore provenBlockHeaderStore; private readonly IConsensusManager consensusManager; private readonly IConsensusRuleEngine consensusRules; private readonly IBlockPuller blockPuller; private readonly IBlockStore blockStore; /// <inheritdoc cref="IFinalizedBlockInfoRepository"/> private readonly IFinalizedBlockInfoRepository finalizedBlockInfoRepository; /// <inheritdoc cref="IPartialValidator"/> private readonly IPartialValidator partialValidator; public BaseFeature(NodeSettings nodeSettings, DataFolder dataFolder, INodeLifetime nodeLifetime, ConcurrentChain chain, IChainState chainState, IConnectionManager connectionManager, IChainRepository chainRepository, IFinalizedBlockInfoRepository finalizedBlockInfo, IDateTimeProvider dateTimeProvider, IAsyncLoopFactory asyncLoopFactory, ITimeSyncBehaviorState timeSyncBehaviorState, ILoggerFactory loggerFactory, IInitialBlockDownloadState initialBlockDownloadState, IPeerBanning peerBanning, IPeerAddressManager peerAddressManager, IConsensusManager consensusManager, IConsensusRuleEngine consensusRules, IPartialValidator partialValidator, IBlockPuller blockPuller, IBlockStore blockStore, Network network, IProvenBlockHeaderStore provenBlockHeaderStore = null) { this.chainState = Guard.NotNull(chainState, nameof(chainState)); this.chainRepository = Guard.NotNull(chainRepository, nameof(chainRepository)); this.finalizedBlockInfoRepository = Guard.NotNull(finalizedBlockInfo, nameof(finalizedBlockInfo)); this.nodeSettings = Guard.NotNull(nodeSettings, nameof(nodeSettings)); this.dataFolder = Guard.NotNull(dataFolder, nameof(dataFolder)); this.nodeLifetime = Guard.NotNull(nodeLifetime, nameof(nodeLifetime)); this.chain = Guard.NotNull(chain, nameof(chain)); this.connectionManager = Guard.NotNull(connectionManager, nameof(connectionManager)); this.consensusManager = consensusManager; this.consensusRules = consensusRules; this.blockPuller = blockPuller; this.blockStore = blockStore; this.network = network; this.provenBlockHeaderStore = provenBlockHeaderStore; this.partialValidator = partialValidator; this.peerBanning = Guard.NotNull(peerBanning, nameof(peerBanning)); this.peerAddressManager = Guard.NotNull(peerAddressManager, nameof(peerAddressManager)); this.peerAddressManager.PeerFilePath = this.dataFolder; this.initialBlockDownloadState = initialBlockDownloadState; this.dateTimeProvider = dateTimeProvider; this.asyncLoopFactory = asyncLoopFactory; this.timeSyncBehaviorState = timeSyncBehaviorState; this.loggerFactory = loggerFactory; this.logger = loggerFactory.CreateLogger(this.GetType().FullName); } /// <inheritdoc /> public override async Task InitializeAsync() { await this.StartChainAsync().ConfigureAwait(false); if (this.provenBlockHeaderStore != null) { // If we find at this point that proven header store is behind chain we can rewind chain (this will cause a ripple effect and rewind block store and consensus) // This problem should go away once we implement a component to keep all tips up to date // https://github.com/stratisproject/StratisBitcoinFullNode/issues/2503 ChainedHeader initializedAt = await this.provenBlockHeaderStore.InitializeAsync(this.chain.Tip); this.chain.SetTip(initializedAt); } NetworkPeerConnectionParameters connectionParameters = this.connectionManager.Parameters; connectionParameters.IsRelay = this.connectionManager.ConnectionSettings.RelayTxes; connectionParameters.TemplateBehaviors.Add(new PingPongBehavior()); connectionParameters.TemplateBehaviors.Add(new ConsensusManagerBehavior(this.chain, this.initialBlockDownloadState, this.consensusManager, this.peerBanning, this.loggerFactory)); connectionParameters.TemplateBehaviors.Add(new PeerBanningBehavior(this.loggerFactory, this.peerBanning, this.nodeSettings)); connectionParameters.TemplateBehaviors.Add(new BlockPullerBehavior(this.blockPuller, this.initialBlockDownloadState, this.dateTimeProvider, this.loggerFactory)); connectionParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(this.connectionManager, this.loggerFactory)); this.StartAddressManager(connectionParameters); if (this.connectionManager.ConnectionSettings.SyncTimeEnabled) { connectionParameters.TemplateBehaviors.Add(new TimeSyncBehavior(this.timeSyncBehaviorState, this.dateTimeProvider, this.loggerFactory)); } else { this.logger.LogDebug("Time synchronization with peers is disabled."); } // Block store must be initialized before consensus manager. // This may be a temporary solution until a better way is found to solve this dependency. await this.blockStore.InitializeAsync().ConfigureAwait(false); await this.consensusRules.InitializeAsync(this.chain.Tip).ConfigureAwait(false); this.consensusRules.Register(); await this.consensusManager.InitializeAsync(this.chain.Tip).ConfigureAwait(false); this.chainState.ConsensusTip = this.consensusManager.Tip; } /// <summary> /// Initializes node's chain repository. /// Creates periodic task to persist changes to the database. /// </summary> private async Task StartChainAsync() { if (!Directory.Exists(this.dataFolder.ChainPath)) { this.logger.LogInformation("Creating {0}.", this.dataFolder.ChainPath); Directory.CreateDirectory(this.dataFolder.ChainPath); } if (!Directory.Exists(this.dataFolder.FinalizedBlockInfoPath)) { this.logger.LogInformation("Creating {0}.", this.dataFolder.FinalizedBlockInfoPath); Directory.CreateDirectory(this.dataFolder.FinalizedBlockInfoPath); } this.logger.LogInformation("Loading finalized block height."); await this.finalizedBlockInfoRepository.LoadFinalizedBlockInfoAsync(this.network).ConfigureAwait(false); this.logger.LogInformation("Loading chain."); ChainedHeader chainTip = await this.chainRepository.LoadAsync(this.chain.Genesis).ConfigureAwait(false); this.chain.SetTip(chainTip); this.logger.LogInformation("Chain loaded at height {0}.", this.chain.Height); this.flushChainLoop = this.asyncLoopFactory.Run("FlushChain", async token => { await this.chainRepository.SaveAsync(this.chain).ConfigureAwait(false); if (this.provenBlockHeaderStore != null) await this.provenBlockHeaderStore.SaveAsync().ConfigureAwait(false); }, this.nodeLifetime.ApplicationStopping, repeatEvery: TimeSpan.FromMinutes(1.0), startAfter: TimeSpan.FromMinutes(1.0)); } /// <summary> /// Initializes node's address manager. Loads previously known peers from the file /// or creates new peer file if it does not exist. Creates periodic task to persist changes /// in peers to disk. /// </summary> private void StartAddressManager(NetworkPeerConnectionParameters connectionParameters) { var addressManagerBehaviour = new PeerAddressManagerBehaviour(this.dateTimeProvider, this.peerAddressManager, this.peerBanning, this.loggerFactory); connectionParameters.TemplateBehaviors.Add(addressManagerBehaviour); if (File.Exists(Path.Combine(this.dataFolder.AddressManagerFilePath, PeerAddressManager.PeerFileName))) { this.logger.LogInformation($"Loading peers from : {this.dataFolder.AddressManagerFilePath}."); this.peerAddressManager.LoadPeers(); } this.flushAddressManagerLoop = this.asyncLoopFactory.Run("Periodic peer flush", token => { this.peerAddressManager.SavePeers(); return Task.CompletedTask; }, this.nodeLifetime.ApplicationStopping, repeatEvery: TimeSpan.FromMinutes(5.0), startAfter: TimeSpan.FromMinutes(5.0)); } /// <inheritdoc /> public override void Dispose() { this.logger.LogInformation("Flushing peers."); this.flushAddressManagerLoop.Dispose(); this.logger.LogInformation("Disposing peer address manager."); this.peerAddressManager.Dispose(); if (this.flushChainLoop != null) { this.logger.LogInformation("Flushing headers chain."); this.flushChainLoop.Dispose(); } this.logger.LogInformation("Disposing time sync behavior."); this.timeSyncBehaviorState.Dispose(); this.logger.LogInformation("Disposing block puller."); this.blockPuller.Dispose(); this.logger.LogInformation("Disposing partial validator."); this.partialValidator.Dispose(); this.logger.LogInformation("Disposing consensus manager."); this.consensusManager.Dispose(); this.logger.LogInformation("Disposing consensus rules."); this.consensusRules.Dispose(); this.logger.LogInformation("Saving chain repository."); this.chainRepository.SaveAsync(this.chain).GetAwaiter().GetResult(); this.chainRepository.Dispose(); if (this.provenBlockHeaderStore != null) { this.logger.LogInformation("Saving proven header store."); this.provenBlockHeaderStore.SaveAsync().GetAwaiter().GetResult(); this.provenBlockHeaderStore.Dispose(); } this.logger.LogInformation("Disposing finalized block info repository."); this.finalizedBlockInfoRepository.Dispose(); this.logger.LogInformation("Disposing block store."); this.blockStore.Dispose(); } } /// <summary> /// A class providing extension methods for <see cref="IFullNodeBuilder"/>. /// </summary> public static class FullNodeBuilderBaseFeatureExtension { /// <summary> /// Makes the full node use all the required features - <see cref="BaseFeature"/>. /// </summary> /// <param name="fullNodeBuilder">Builder responsible for creating the node.</param> /// <returns>Full node builder's interface to allow fluent code.</returns> public static IFullNodeBuilder UseBaseFeature(this IFullNodeBuilder fullNodeBuilder) { fullNodeBuilder.ConfigureFeature(features => { features .AddFeature<BaseFeature>() .FeatureServices(services => { services.AddSingleton<DBreezeSerializer>(); services.AddSingleton(fullNodeBuilder.NodeSettings.LoggerFactory); services.AddSingleton(fullNodeBuilder.NodeSettings.DataFolder); services.AddSingleton<INodeLifetime, NodeLifetime>(); services.AddSingleton<IPeerBanning, PeerBanning>(); services.AddSingleton<FullNodeFeatureExecutor>(); services.AddSingleton<Signals.Signals>().AddSingleton<ISignals, Signals.Signals>(provider => provider.GetService<Signals.Signals>()); services.AddSingleton<FullNode>().AddSingleton((provider) => { return provider.GetService<FullNode>() as IFullNode; }); services.AddSingleton<ConcurrentChain>(new ConcurrentChain(fullNodeBuilder.Network)); services.AddSingleton<IDateTimeProvider>(DateTimeProvider.Default); services.AddSingleton<IInvalidBlockHashStore, InvalidBlockHashStore>(); services.AddSingleton<IChainState, ChainState>(); services.AddSingleton<IChainRepository, ChainRepository>(); services.AddSingleton<IFinalizedBlockInfoRepository, FinalizedBlockInfoRepository>(); services.AddSingleton<ITimeSyncBehaviorState, TimeSyncBehaviorState>(); services.AddSingleton<IAsyncLoopFactory, AsyncLoopFactory>(); services.AddSingleton<NodeDeployments>(); services.AddSingleton<IInitialBlockDownloadState, InitialBlockDownloadState>(); // Consensus services.AddSingleton<ConsensusSettings>(); services.AddSingleton<ICheckpoints, Checkpoints>(); // Connection services.AddSingleton<INetworkPeerFactory, NetworkPeerFactory>(); services.AddSingleton<NetworkPeerConnectionParameters>(); services.AddSingleton<IConnectionManager, ConnectionManager>(); services.AddSingleton<ConnectionManagerSettings>(); services.AddSingleton<PayloadProvider>(new PayloadProvider().DiscoverPayloads()); services.AddSingleton<IVersionProvider, VersionProvider>(); services.AddSingleton<IBlockPuller, BlockPuller>(); // Peer address manager services.AddSingleton<IPeerAddressManager, PeerAddressManager>(); services.AddSingleton<IPeerConnector, PeerConnectorAddNode>(); services.AddSingleton<IPeerConnector, PeerConnectorConnectNode>(); services.AddSingleton<IPeerConnector, PeerConnectorDiscovery>(); services.AddSingleton<IPeerDiscovery, PeerDiscovery>(); services.AddSingleton<ISelfEndpointTracker, SelfEndpointTracker>(); // Consensus services.AddSingleton<IConsensusManager, ConsensusManager>(); services.AddSingleton<IChainedHeaderTree, ChainedHeaderTree>(); services.AddSingleton<IHeaderValidator, HeaderValidator>(); services.AddSingleton<IIntegrityValidator, IntegrityValidator>(); services.AddSingleton<IPartialValidator, PartialValidator>(); services.AddSingleton<IFullValidator, FullValidator>(); // Console services.AddSingleton<INodeStats, NodeStats>(); }); }); return fullNodeBuilder; } } }
/* ==================================================================== 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. ==================================================================== */ namespace NPOI.HSSF.Record.Chart { using System; using System.Text; using NPOI.Util; public enum DateUnit { Days = 0, Months = 1, Years = 2 } /* * The axis options record provides Unit information and other various tidbits about the axis. * NOTE: This source is automatically generated please do not modify this file. Either subclass or * Remove the record in src/records/definitions. * @author Andrew C. Oliver(acoliver at apache.org) */ // /// <summary> /// The AxcExt record specifies additional extension properties of a date axis (section 2.2.3.6), /// along with a CatSerRange record (section 2.4.39). /// </summary> public class AxcExtRecord : StandardRecord { public const short sid = 0x1062; private short field_1_catMin; private short field_2_catMax; private short field_3_catMajor; private short field_4_duMajor; private short field_5_catMinor; private short field_6_duMinor; private short field_7_duBase; private short field_8_catCrossDate; private short field_9_options; private BitField fAutoMin = BitFieldFactory.GetInstance(0x1); private BitField fAutoMax = BitFieldFactory.GetInstance(0x2); private BitField fAutoMajor = BitFieldFactory.GetInstance(0x4); private BitField fAutoMinor = BitFieldFactory.GetInstance(0x8); private BitField fDateAxis = BitFieldFactory.GetInstance(0x10); private BitField fAutoBase = BitFieldFactory.GetInstance(0x20); private BitField fAutoCross = BitFieldFactory.GetInstance(0x40); private BitField fAutoDate = BitFieldFactory.GetInstance(0x80); public AxcExtRecord() { } /* * Constructs a AxisOptions record and Sets its fields appropriately. * * @param in the RecordInputstream to Read the record from */ public AxcExtRecord(RecordInputStream in1) { field_1_catMin = in1.ReadShort(); field_2_catMax = in1.ReadShort(); field_3_catMajor = in1.ReadShort(); field_4_duMajor = in1.ReadShort(); field_5_catMinor = in1.ReadShort(); field_6_duMinor = in1.ReadShort(); field_7_duBase = in1.ReadShort(); field_8_catCrossDate = in1.ReadShort(); field_9_options = in1.ReadShort(); } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[AXCEXT]\n"); buffer.Append(" .catMin = ") .Append("0x").Append(HexDump.ToHex(MinimumDate)) .Append(" (").Append(MinimumDate).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .catMax = ") .Append("0x").Append(HexDump.ToHex(MaximumDate)) .Append(" (").Append(MaximumDate).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .catMajor = ") .Append("0x").Append(HexDump.ToHex(MajorInterval)) .Append(" (").Append(MajorInterval).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .duMajor = ") .Append("0x").Append(HexDump.ToHex((short)MajorUnit)) .Append(" (").Append(MajorUnit).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .catMinor = ") .Append("0x").Append(HexDump.ToHex(MinorInterval)) .Append(" (").Append(MinorInterval).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .duMinor = ") .Append("0x").Append(HexDump.ToHex((short)MinorUnit)) .Append(" (").Append(MinorUnit).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .duBase = ") .Append("0x").Append(HexDump.ToHex((short)BaseUnit)) .Append(" (").Append(BaseUnit).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .catCrossDate = ") .Append("0x").Append(HexDump.ToHex(CrossDate)) .Append(" (").Append(CrossDate).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .options = ") .Append("0x").Append(HexDump.ToHex(Options)) .Append(" (").Append(Options).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .fAutoMin = ").Append(IsAutoMin).Append('\n'); buffer.Append(" .fAutoMax = ").Append(IsAutoMax).Append('\n'); buffer.Append(" .fAutoMajor = ").Append(IsAutoMajor).Append('\n'); buffer.Append(" .fAutoMinor = ").Append(IsAutoMinor).Append('\n'); buffer.Append(" .fDateAxis = ").Append(IsDateAxis).Append('\n'); buffer.Append(" .fAutoBase = ").Append(IsAutoBase).Append('\n'); buffer.Append(" .fAutoCross = ").Append(IsAutoCross).Append('\n'); buffer.Append(" .fAutoDate = ").Append(IsAutoDate).Append('\n'); buffer.Append("[/AXCEXT]\n"); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(field_1_catMin); out1.WriteShort(field_2_catMax); out1.WriteShort(field_3_catMajor); out1.WriteShort(field_4_duMajor); out1.WriteShort(field_5_catMinor); out1.WriteShort(field_6_duMinor); out1.WriteShort(field_7_duBase); out1.WriteShort(field_8_catCrossDate); out1.WriteShort(field_9_options); } /* * Size of record (exluding 4 byte header) */ protected override int DataSize { get { return 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2; } } public override short Sid { get { return sid; } } public override Object Clone() { AxcExtRecord rec = new AxcExtRecord(); rec.field_1_catMin = field_1_catMin; rec.field_2_catMax = field_2_catMax; rec.field_3_catMajor = field_3_catMajor; rec.field_4_duMajor = field_4_duMajor; rec.field_5_catMinor = field_5_catMinor; rec.field_6_duMinor = field_6_duMinor; rec.field_7_duBase = field_7_duBase; rec.field_8_catCrossDate = field_8_catCrossDate; rec.field_9_options = field_9_options; return rec; } /* * Get the minimum category field for the AxisOptions record. */ public short MinimumDate { get { return field_1_catMin; } set { this.field_1_catMin = value; } } /* * Get the maximum category field for the AxisOptions record. */ public short MaximumDate { get { return field_2_catMax; } set { this.field_2_catMax = value; } } /* * Get the major Unit value field for the AxisOptions record. */ // /// <summary> /// specifies the interval at which the major tick marks are displayed on the axis (section 2.2.3.6), /// in the unit defined by duMajor. /// </summary> public short MajorInterval { get { return field_3_catMajor; } set { this.field_3_catMajor = value; } } /* * Get the major Unit field for the AxisOptions record. */ // /// <summary> /// specifies the unit of time to use for catMajor when the axis (section 2.2.3.6) is a date axis (section 2.2.3.6). /// If fDateAxis is set to 0, MUST be ignored. /// </summary> public DateUnit MajorUnit { get { return (DateUnit)field_4_duMajor; } set { this.field_4_duMajor = (short)value; } } /* * Get the minor Unit value field for the AxisOptions record. */ // /// <summary> /// specifies the interval at which the minor tick marks are displayed on the axis (section 2.2.3.6), /// in a unit defined by duMinor. /// </summary> public short MinorInterval { get { return field_5_catMinor; } set { this.field_5_catMinor = value; } } /* * Get the minor Unit field for the AxisOptions record. */ public DateUnit MinorUnit { get { return (DateUnit)field_6_duMinor; } set { this.field_6_duMinor = (short)value; } } /* * Get the base Unit field for the AxisOptions record. */ // /// <summary> /// specifies the smallest unit of time used by the axis (section 2.2.3.6). /// </summary> public DateUnit BaseUnit { get { return (DateUnit)field_7_duBase; } set { this.field_7_duBase = (short)value; } } /* * Get the crossing point field for the AxisOptions record. */ // /// <summary> /// specifies at which date, as a date in the date system specified by the Date1904 record (section 2.4.77), /// in the units defined by duBase, the value axis (section 2.2.3.6) crosses this axis (section 2.2.3.6). /// </summary> public short CrossDate { get { return field_8_catCrossDate; } set { this.field_8_catCrossDate = value; } } /* * Get the options field for the AxisOptions record. */ public short Options { get { return field_9_options; } set { this.field_9_options = value; } } /* * use the default minimum category * @return the default minimum field value. */ // /// <summary> /// specifies whether MinimumDate is calculated automatically. /// </summary> public bool IsAutoMin { get { return fAutoMin.IsSet(field_9_options); } set { field_9_options = fAutoMin.SetShortBoolean(field_9_options, value); } } /* * use the default maximum category * @return the default maximum field value. */ /// <summary> /// specifies whether MaximumDate is calculated automatically. /// </summary> public bool IsAutoMax { get { return fAutoMax.IsSet(field_9_options); } set { field_9_options = fAutoMax.SetShortBoolean(field_9_options, value); } } /* * use the default major Unit * @return the default major field value. */ public bool IsAutoMajor { get { return fAutoMajor.IsSet(field_9_options); } set { field_9_options = fAutoMajor.SetShortBoolean(field_9_options, value); } } /* * use the default minor Unit * @return the default minor Unit field value. */ public bool IsAutoMinor { get { return fAutoMinor.IsSet(field_9_options); } set { field_9_options = fAutoMinor.SetShortBoolean(field_9_options, value); } } /* * this is a date axis * @return the IsDate field value. */ public bool IsDateAxis { get { return fDateAxis.IsSet(field_9_options); } set { field_9_options = fDateAxis.SetShortBoolean(field_9_options, value); } } /* * use the default base Unit * @return the default base field value. */ public bool IsAutoBase { get { return fAutoBase.IsSet(field_9_options); } set { field_9_options = fAutoBase.SetShortBoolean(field_9_options, value); } } /* * use the default crossing point * @return the default cross field value. */ public bool IsAutoCross { get { return fAutoCross.IsSet(field_9_options); } set { field_9_options = fAutoCross.SetShortBoolean(field_9_options, value); } } /* * use default date Setttings for this axis * @return the default date Settings field value. */ public bool IsAutoDate { get { return fAutoDate.IsSet(field_9_options); } set { field_9_options = fAutoDate.SetShortBoolean(field_9_options, value); } } } }